Friday, May 28, 2010

Converting comma delimeter string into a table

It would be nice to split the incoming comma delimeter string into a table and returns a table back to the caller.

For example, you would like to turn 'A,B' into a table.

select *
from dbo.fn_to_table ('''A'',''B''')

select count(*)
from dbo.fn_to_table ('''A'',''B''')



create function dbo.fn_to_table (@str nvarchar(max))
returns @tb table (code nvarchar(50))
as
begin

declare
@pos int,
@prev_pos int,
@s nvarchar(50)

select @pos = charindex(',', @str)
select @prev_pos = 0

if ((len(@str) > 0) and (@pos = 0))
insert into @tb (code)
select replace(@str, '''','');

while @pos > 0
begin
select @s = replace( substring(@str, @prev_pos,
@pos - @prev_pos), '''','');
-- select @prev_pos, @pos, @s
insert into @tb (code)
select @s

select @prev_pos = @pos + 1;
select @pos = charindex(',', @str, @pos + 1);
end

if ((@prev_pos > 0) and (@pos = 0))
begin
insert into @tb (code)
select replace( substring(@str, @prev_pos,
len(@str) - @prev_pos), '''','');
end

return

end

No comments:

Post a Comment