小编Rez*_*eza的帖子

选择一个 CSV 字符串作为多列

我正在使用 SQL Server 2014 并且我有一个包含一列包含CSV字符串的表:

110,200,310,130,null
Run Code Online (Sandbox Code Playgroud)

该表的输出如下所示:

选择结果

我想选择第二列作为多列,将 CSV 字符串的每个项目放在一个单独的列中,如下所示:

预期结果

所以我创建了一个用于拆分字符串的函数:

create FUNCTION [dbo].[fn_splitstring]
(
    @List nvarchar(2000),
    @SplitOn nvarchar(5)
)  
RETURNS @RtnValue table 
(
    Id int identity(1,1),
    Value nvarchar(100)
) 
AS  
BEGIN 
    while (Charindex(@SplitOn,@List)>0)
    begin
        insert into @RtnValue (value)
        select 
            Value = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1)))

        set @List = Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))
    end
    insert Into @RtnValue (Value)
    select Value = ltrim(rtrim(@List))

    return
END
Run Code Online (Sandbox Code Playgroud)

我想像这样使用它:

select Val , (select value from tvf_split_string(cchar1,','))  from table1
Run Code Online (Sandbox Code Playgroud)

但是上面的代码显然行不通,因为该函数将返回多于一行,导致子查询返回多于一个值并破坏代码。

我可以使用类似的东西:

select Val ,
(select value from …
Run Code Online (Sandbox Code Playgroud)

sql-server sql-server-2014 csv string-manipulation

6
推荐指数
2
解决办法
8695
查看次数