Thursday, May 31, 2012

How to insert comma - delimited string value in a table



How to insert comma - delimited string value in a table

Here is the script that will insert comma separated string (values separated by comma). String may have only one value as well. This script will work in both the cases.

declare @string varchar(50)
declare @tabvar table(val varchar(50))
set @string = 'a,db,c,dd,eee,f'
while(LEN(@string) > 0)
begin
       if(charindex(',', @string) > 0)
       begin 
              insert into @tabvar
              select substring(@string,1 , charindex(',', @string) - 1)
       end
       else
       begin 
              insert into @tabvar
              select @string
              break
       end
       set @string = substring(@string,charindex(',', @string) + 1, len(@string))
end
select * from @tabvar

No comments:

Post a Comment