SQL单行到多行用逗号分隔

时间:2014-02-10 04:15:58

标签: sql-server

我想从SQL Server获取数据列表,包括在新行中用逗号分隔的数据。

注意:我只有一个列名DATA

我有一个类似

的值
DATA
new
old,yes,now
ok,for
no

我要求的输出是:

DATA
new
old
yes
now
ok
for
no

1 个答案:

答案 0 :(得分:0)

你需要的是分割功能,看看这是否适合你

        CREATE FUNCTION FNC_SPLIT(@MYSTR VARCHAR(500), @DELIMITER CHAR(1))
        RETURNS @MYTBL  TABLE (idx smallint, value varchar(8000))
        AS 
        BEGIN
         DECLARE @RET VARCHAR(500)
         DECLARE @INDEX INT
         DECLARE @COUNTER smallint

         --Get the first position of delimiter in the main string
         SET @INDEX = CHARINDEX(@DELIMITER,@MYSTR)
         SET @COUNTER = 0

         --Loop if delimiter exists in the main string
         WHILE @INDEX > 0
         BEGIN
            --extract the result substring before the delimiter found
            SET @RET = SUBSTRING(@MYSTR,1, @INDEX-1 )
            --set mainstring right part after the delimiter found
            SET @MYSTR = SUBSTRING(@MYSTR,@INDEX+1 , LEN(@MYSTR) - @INDEX )
            --increase the counter
            SET @COUNTER = @COUNTER  + 1 
            --add the result substring to the table
            INSERT INTO @MYTBL (idx, value)
            VALUES (@COUNTER, @RET)
            --Get the next position of delimiter in the main string
            SET @INDEX = CHARINDEX(@DELIMITER,@MYSTR)
         END

         --if no delimiter is found then simply add the mainstring to the table
         IF @INDEX = 0 
         BEGIN
            SET @COUNTER = @COUNTER  + 1
            INSERT INTO @MYTBL (idx, value)
            VALUES (@COUNTER, @MYSTR)
         END 
         RETURN   
        END

        GO

        declare @table table(dt varchar(100));
        insert into @table values
        ('DATA'),
        ('new'),
        ('old,yes,now'),
        ('ok,for');

        select * from @table

        select value from  @table t cross apply dbo.FNC_SPLIT(t.dt,',')