Parsing Comma Delemeted String in Sql

I will just go with the Example as its Self Exclamatory.

Sql Query:

declare @string varchar(500)

declare @pos INT
declare @piece varchar(500)

-- Need to tack a delimiter onto the end of the input string if one doesn’t exist
if right(rtrim(@string),1) <> ','
set @string = @string + ','

set @pos = patindex('%,%' , @string)
while @pos <> 0
set @piece = left(@string, @pos - 1)

-- You have a piece of data, so insert it, print it, do whatever you want to with it.
print cast(@piece as varchar(500))

set @string = stuff(@string, 1, @pos, '')
set @pos = patindex('%,%' , @string)



One thought on “Parsing Comma Delemeted String in Sql

Leave a Reply

Your email address will not be published. Required fields are marked *