1
我有一个字段由多个字符串组成的字段,由'+'分隔。将字符串分成若干行
字符串的每个部分的长度都是2或3个字符。例如:'ab+cde+fg'
。
每行有1到3个部分(所以有些行不需要分割)。上述示例应返回3行:'ab'
,'cd'
和'fg'
。
我已经搜索了互联网上的存储过程,但没有一个似乎适用于我的特殊需求。我自己没有SQL技能来编写这样的程序。
我有一个字段由多个字符串组成的字段,由'+'分隔。将字符串分成若干行
字符串的每个部分的长度都是2或3个字符。例如:'ab+cde+fg'
。
每行有1到3个部分(所以有些行不需要分割)。上述示例应返回3行:'ab'
,'cd'
和'fg'
。
我已经搜索了互联网上的存储过程,但没有一个似乎适用于我的特殊需求。我自己没有SQL技能来编写这样的程序。
一般的算法是这样的:
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行AA
,CCC
,D
到临时表#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;
完美的作品!非常感谢你的时间 – Philippe 2011-03-18 14:37:09