2011-03-18 94 views
1

我有一個字段由多個字符串組成的字段,由'+'分隔。將字符串分成若干行

字符串的每個部分的長度都是2或3個字符。例如:'ab+cde+fg'

每行有1到3個部分(所以有些行不需要分割)。上述示例應返回3行:'ab','cd''fg'

我已經搜索了互聯網上的存儲過程,但沒有一個似乎適用於我的特殊需求。我自己沒有SQL技能來編寫這樣的程序。

回答

2

一般的算法是這樣的:

DECLARE input CHAR(100); 
DECLARE separator_position INTEGER; 

SET input = 'AA+CCC+D'; 

CREATE TABLE 
    #output 
(
    part CHAR(10) 
); 

SET separator_position = POSITION('+' IN input); 

WHILE separator_position > 0 DO 

    INSERT INTO #output (part) VALUES (SUBSTRING(input, 1, separator_position - 1)); 
    SET input = SUBSTRING(input, separator_position + 1, 100); 

    SET separator_position = POSITION('+' IN input); 
END WHILE; 

INSERT INTO #output(part) VALUES (SUBSTRING(input, 1, 10)); 

SELECT * FROM #output; 

此代碼將插入3行AACCCD到臨時表#output。

這裏是一個多字符分隔符兼容版本,並且還包含了部分計:

DECLARE @input STRING; 
DECLARE @delimiter_position INTEGER; 
DECLARE @delimiter STRING; 

TRY DROP TABLE #output; CATCH ALL END TRY; 

SET @delimiter = CHAR(13) + CHAR(10); 
SET @input = 'AA' + CHAR(13) + CHAR(10) + 'CCC' + CHAR(13) + CHAR(10) + 'D'; 

CREATE TABLE 
    #output 
(
    counter AUTOINC 
    , part CHAR(10) 
); 

SET @delimiter_position = POSITION(@delimiter IN @input); 

WHILE @delimiter_position > 0 DO 

    INSERT INTO #output (part) VALUES (LEFT(@input, @delimiter_position - 1)); 
    SET @input = RIGHT(@input, LENGTH(@input) - (@delimiter_position + LENGTH(@delimiter)) + 1); 

    SET @delimiter_position = POSITION(@delimiter IN @input); 
END WHILE; 

INSERT INTO #output(part) VALUES (LEFT(@input, LENGTH(@input))); 

SELECT * FROM #output; 
+0

完美的作品!非常感謝你的時間 – Philippe 2011-03-18 14:37:09