Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何从CSV值列中获取值_Sql - Fatal编程技术网

Sql 如何从CSV值列中获取值

Sql 如何从CSV值列中获取值,sql,Sql,表1 从上表中,我需要输出如下所示: Column A Column B Column C Column D =========================================================== 1 2 3 a,b,c 这里有一个通用的解决方案,希望能对你的问题有所帮助 Result from query ----------------- Column A Colum

表1

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

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
你在使用什么数据库?MySQL、Postgresql、SQL Server或其他什么?这个问题太广泛了。你试过什么?您使用的是什么工具?当它以特定于供应商的代码表示时,它怎么可能是通用解决方案?
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