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.
+2
A:
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
Pandiya Chendur
2010-05-07 05:26:57
+1 for delimitter passing...
chandru_cp
2010-05-07 05:29:31
-1 for using a loop
gbn
2010-05-07 05:29:57
@gbn does table of numbers execute faster than a loop.... Please explain a bit more...
Pandiya Chendur
2010-05-07 05:31:48
Please see my links in my answer
gbn
2010-05-07 05:37:16
+1
A:
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.
gbn
2010-05-07 05:29:34
A:
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;
mrp
2010-05-08 11:42:51