Joseph Michael Pesch
VP Programming

SQL Function to Convert Delimited String to Table

by 24. December 2015 07:58

This is a SQL function to convert a delimited string into a table.

create function [dbo].[DelimToTable] 
(@StringInput varchar(max), @Delimiter nvarchar(1))
returns @OutputTable table([String] varchar(255)) as begin
declare @String varchar(255)
while len(@StringInput) > 0 begin
set @String = left(@StringInput
, isnull(nullif(charindex(@Delimiter, @StringInput) - 1, -1)
, len(@StringInput)))
set @StringInput = substring(@StringInput
, isnull(nullif(charindex(@Delimiter, @StringInput), 0)
, len(@StringInput)) + 1, len(@StringInput))
insert into @OutputTable ([String]) values(@String)
end
return
end

Tags:

SQL Server