Wednesday, August 28, 2013

CSV (Comma Separated Values) of integer to Table (SQL)

This is how you can convert CSV (Comma Separated Values) of integer to Table in SQL 
1. Run the following Function in SQL Server
CREATE function [dbo].[FN_CsvToInt] (@id varchar(5000))
returns @table table (wd_code int identity(1,1), [id] int)
as
begin
 declare @separator char(1)
 set @separator = ,
 declare @separator_position int
 declare @array_value varchar(5000)
 set @id = @id + ,
 while patindex(%,% , @id) <> 0
 begin
   select @separator_position =  patindex(%,% , @id)
   select @array_value = left(@id, @separator_position 1)
 if(@array_value = null)
  insert @table ([id])
  values (null)
 else
  insert @table ([id])
  values (cast(@array_value as int))
   select @id = stuff(@id, 1, @separator_position, )
 end
 return
end


2. Thats it, Execute the following query
select * from dbo.FN_CsvToInt(11,15,13,18)

3. Output:
CodeId
111
215
313
418
Regards,
Sheryar Nizar

No comments: