开发者

How to split a string in T-SQL?

I have a varchar @a='a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p', which has | delimited values. I want to split this variable in a 开发者_开发百科array or a table.

How can I do this?


Use a table valued function like this,

CREATE FUNCTION Splitfn(@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

and get your variable and use this function like this,

SELECT i.items FROM dbo.Splitfn(@a,'|') AS i


In general, this is such a common question here

I'll give the common answer: Arrays and Lists in SQL Server 2005 and Beyond by Erland Sommarskog

I'd recommend a table of numbers, not a loop, for general use.


Try this one:

declare @a varchar(10) 
set @a = 'a|b|c|'
while len(@a) > 1
begin
insert into #temp
select substring(@a,1,patindex('%|%',@a)-1);
set @a = substring(@a,patindex('%|%',@a)+1,len(@a))
end;


Here's an alternative XML based solution. It seems to have a similar performance as the Splitfn() solution.

This converts varchar a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p into XML <a>a</a><a>b</a><a>c</a><a>d</a><a>e</a><a>f</a><a>g</a><a>h</a><a>i</a><a>j</a><a>k</a><a>l</a><a>m</a><a>n</a><a>o</a><a>p</a> and extracts the value from each XML <a> node.

declare @a      varchar(max);
set @a  =   'a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p';

declare @xml    xml;
set @xml    
    =   '<a>'+replace(replace(replace(@a,'&','&amp;'),'<','&lt;'),'|','</a><a>')+'</a>';

SELECT  x.n.value('.','VARCHAR(1)') AS  singleValue
FROM    @xml.nodes('/a') AS  x(n)
;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜