如何从CSV值列中获取值

时间:2014-04-23 12:44:40

标签: sql

TABLE1

Column A    Column B    Column C    Column D
===========================================================
1           2                3           a,b,c

从上表中我需要输出如下所示:

Result from query
-----------------
Column A    Column B    Column C    Column D
===========================================================
1           2                3           a
1           2                3           b
1           2                3           c

1 个答案:

答案 0 :(得分:0)

这是针对您的问题的通用解决方案,希望它会有所帮助...

declare @t table
(
ID int identity(1,1),
columnA int,
columnB int,
columnC int,
columnD varchar(20) 
)

insert into @t select 1,2,3,'a,b,c' union all select 4,5,6,'a,b,d' union all select 7,8,9,'a'
--select * from @t

declare @tt table
(
ID int identity(1,1),
columnA int,
columnB int,
columnC int,
columnD varchar(20) 
)

declare @count int
set @count = (select count(*) from @t)
declare @i int = 1
declare @str varchar(20) 

while (@i <= @count)
BEGIN
    set @str = (select columnD from @t where ID = @i)
    while charindex(',' , @str) <> 0 
    begin
        Insert @tt (columnA, columnB, columnC, columnD) select columnA, columnB, columnC, left(@str, charindex(',' , @str) - 1) from @t where ID = @i
        SET @str = stuff(@str, 1, charindex(',' , @str), '')
    end
    Insert @tt (columnA, columnB, columnC, columnD) select columnA, columnB, columnC, @str from @t where ID = @i

    SET @i = @i + 1
END

select * from @tt