SQL Server将CSV分成多行

我意识到这个问题之前已经被问过了,但由于某种原因,我无法得到它的工作。

我正在使用从这个SQL团队线程 (第二篇文章)分裂function和以下查询。

--This query converts the interests field from text to varchar select cp.id ,cast(cp.interests as varchar(100)) as interests into #client_profile_temp from client_profile cp --This query is supposed to split the csv ("Golf","food") into multiple rows select cpt.id ,split.data from #client_profile_temp cpt cross apply dbo.split( cpt.interests, ',') as split <--Error is on this line 

不过,我正在得到一个

 Incorrect syntax near '.' 

我在上面标记的错误。

最后,我想要

 ID INTERESTS 000CT00002UA "Golf","food" 

成为

 ID INTERESTS 000CT00002UA "Golf" 000CT00002UA "food" 

我正在使用SQL Server 2008和基于我的答案在这个StackOverflow的问题 。 我相当新的SQL,所以任何其他智慧的话,将不胜感激。

 from #client_profile_temp cpt cross apply dbo.split( #client_profile_temp.interests, ',') as split <--Error is on this line 

我认为#client_profile_temp明确命名后,你给它一个别名是一个问题,尝试做最后一行:

  cpt.interests, ',') as split <--Error is on this line 

编辑你说

我做了这个改变,并没有改变任何东西

尝试粘贴下面的代码(进入一个新的SSMS窗口)

 create table #client_profile_temp (id int, interests varchar(500)) insert into #client_profile_temp values (5, 'Vodka,Potassium,Trigo'), (6, 'Mazda,Boeing,Alcoa') select cpt.id ,split.data from #client_profile_temp cpt cross apply dbo.split(cpt.interests, ',') as split 

看看它是否按预期工作; 我正在使用SQL Server 2008,这对我来说就是我想要的结果。

任何机会,当你说“我做了改变”,你只是改变了一个存储过程,但没有运行它,或者改变了一个脚本来创build一个存储过程,并没有运行,这些行? 正如我所说,它似乎为我工作。

 x-----------------x--------------------x | ID | INTERESTS | x-----------------x--------------------x | 000CT00002UA | Golf,food | | 000CT12303CB | Cricket,Bat | x------x----------x--------------------x 

方法1:使用XML格式

 SELECT ID,Split.a.value('.', 'VARCHAR(100)') 'INTERESTS' FROM ( -- To change ',' to any other delimeter, just change ',' before '</M><M>' to your desired one SELECT ID, CAST ('<M>' + REPLACE(INTERESTS, ',', '</M><M>') + '</M>' AS XML) AS Data FROM TEMP ) AS A CROSS APPLY Data.nodes ('/M') AS Split(a) 
  • SQL FIDDLE

方法2:使用函数dbo.Split

 SELECT a.ID, b.items FROM #TEMP a CROSS APPLY dbo.Split(a.INTERESTS, ',') b 
  • SQL FIDDLE

dbo.Splitfunction在这里。

 CREATE FUNCTION [dbo].[Split](@String varchar(8000), @Delimiter char(1)) returns @temptable TABLE (items varchar(8000)) as begin declare @idx int declare @slice varchar(8000) select @idx = 1 if len(@String)<1 or @String is null return while @idx!= 0 begin set @idx = charindex(@Delimiter,@String) if @idx!=0 set @slice = left(@String,@idx - 1) else set @slice = @String if(len(@slice)>0) insert into @temptable(Items) values(@slice) set @String = right(@String,len(@String) - @idx) if len(@String) = 0 break end return end 

最后结果

在这里输入图像描述

尝试这个:

 --This query is supposed to split the csv ("Golf","food") into multiple rows select cpt.id ,split.data from #client_profile_temp cpt cross apply dbo.split(cpt.interests, ',') as split <--Error is on this line 

定义它时,您必须使用表别名而不是表名。