I have a varchar @a='a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p' , wich have | delimitted values. I want to split this variable in a array or a table. Do anyone have any idea about this.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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
回答2:
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.
回答3:
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;
回答4:
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,'&','&'),'<','<'),'|','</a><a>')+'</a>';
SELECT x.n.value('.','VARCHAR(1)') AS singleValue
FROM @xml.nodes('/a') AS x(n)
;