一尘不染

在SQL Server中以逗号分隔的字符串到表的列中

sql

我正在使用SQL Server,我已经成功地将表的行转换为逗号分隔的值,现在我想将该字符串的逗号分隔值转换回表的行。

我有这个字串(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
...

阅读 139

收藏
2021-03-10

共1个答案

一尘不染

创建一个函数:

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和定界符(,)传递给函数。

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

2021-03-10