用于将给定CSV字符串转换为行的存储过程。例如。输入字符串:' a,b,c,d'

时间:2013-06-17 05:18:47

标签: sql sql-server sql-server-2008-r2

必需的输出

String
abc
bbbc
cdd

我试过这个但是不行。

create procedure CSVtoROWS(in 'str' varchar(50))

begin 
declare i int;
declare j int;
declare temp_str varchar(50);
/*find number of words in given string which is equal to rows*/ 

set i= length(str)-length(replace(str,',',''))+1;

set j=1;

drop table if exists #tabQ1
create table #tabQ1
    (
     String varchar(50) null default null
    );
while(j<=i) do
set temp_str=LEFT(str,charIndex(',',str)-1,len(str))
set str= SUBSTRING(str,(CHARINDEX(',', @StringInput),
                             LEN(@StringInput)) + 1, LEN(@StringInput))
insert into tabQ1
values(temp_str);
setj=j+1;
End while;
select * from TableforQ1;   
END 

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

create procedure CSVtoROWS
  @S varchar(50)
as

declare @T table(string varchar(50))

while len(@S) > 0
begin
  insert into @T values(left(@S, charindex(',', @S+',')-1))
  set @S = stuff(@S, 1, charindex(',', @S+','), '')
end

select string from @T

或者您可以使用您选择的字符串拆分功能 Split strings the right way – or the next best way

答案 1 :(得分:0)

试试这个

CREATE PROCEDURE CSVtoROWS
(
  @S VARCHAR(100)
) -- CSVtoROWS 'String,abc,bbbc,cdd'
AS 
BEGIN

 SELECT Split.a.value('.', 'VARCHAR(100)') AS String  
 FROM  (SELECT CAST ('<M>' + REPLACE(@S, ',', '</M><M>') + '</M>' AS XML) AS String ) AS A 
 CROSS APPLY String.nodes ('/M') AS Split(a);

END

并查看以下链接以供参考

http://www.sqljason.com/2010/05/converting-single-comma-separated-row.html