SQL Server - Split Comma Separated String To Table

Split Comma Separated String To Table In SQL
(or any other delimiter)

If you ever need to send, for example, a list of primary key Ids to a stored procedure, this SQL function below will help  you out by returning those Ids or values to you as rows in a table.





create function [dbo].[fn_SplitString]
(
@MyString 	varchar(8000) ,
@Delimiter	varchar(10)
)
returns @tbl table (Val varchar(1000))
as
/*
Usage:- select * from dbo.fn_SplitString ('1,223,24,43,22', ',')*/
begin
declare @i int ,
	@j int
	select 	@i = 1
	while @i <= len(@MyString )
	begin
		select	@j = charindex(@Delimiter, @MyString , @i)
		if @j = 0
		begin
			select	@j = len(@MyString ) + 1
		end
		insert	@tbl select substring(@MyString , @i, @j - @i)
		select	@i = @j + len(@Delimiter)
	end
	return
end

GO

Author: Kevin Dark - 8/3/2016 5:45:43 PM