我正在使用SQL Server,我已经成功地将表的行转换为逗号分隔的值,现在我想将该字符串的逗号分隔值转换回表的行。
我有这个字串(Varchar)
Varchar
DECLARE @str AS varchar(Max) SET @str = '0.00,0.00,1576.95,0.00,4105.88,1017.87,0.00,6700.70'
我希望这些值成行。
喜欢
0.00 0.00 1576 ...
创建一个函数:
CREATE FUNCTION [dbo].[Split](@String nvarchar(4000), @Delimiter char(1)) RETURNS @Results TABLE (Items nvarchar(4000)) AS BEGIN DECLARE @Index INT DECLARE @Slice nvarchar(4000) -- HAVE TO SET TO 1 SO IT DOESN鈥橳 EQUAL ZERO FIRST TIME IN LOOP SELECT @Index = 1 WHILE @Index !=0 BEGIN SELECT @Index = CHARINDEX(@Delimiter,@String) --Getting the indexof the first Occurrence of the delimiter -- Saving everything to the left of the delimiter to the variable SLICE IF @Index !=0 SELECT @Slice = LEFT(@String,@Index - 1) ELSE SELECT @Slice = @String -- Inserting the value of Slice into the Results SET INSERT INTO @Results(Items) VALUES(@Slice) --Remove the Slice value from Main String SELECT @String = RIGHT(@String,LEN(@String) - @Index) -- Break if Main String is empty IF LEN(@String) = 0 BREAK END RETURN END
将字符串@str和定界符(,)传递给函数。
@str
SELECT Items FROM [dbo].[Split] (@str, ',')
它将结果返回为表格:
Items 0.00 0.00 1576.95 0.00 4105.88 1017.87 0.00 6700.70
请参见 SQL Fiddle