Software Development : A dizzy job...keeping abreast and being competitive is a 24X7 involvement
Jun 20, 2007
SQL Server - Parse a delimited string
alter procedure web_ParseArray
( @Array varchar(1000),
@separator char(1) )
AS
-- Created by graz@sqlteam.com
-- Modified to result a table by Bart@prove.be
set nocount on
-- @Array is the array we wish to parse
-- @Separator is the separator charactor such as a comma
declare @separator_position int -- This is used to locate each separator character
declare @array_value varchar(1000) -- this holds each array value as it is returned
create table #ParsedArrays (array_Value varchar(1000))
-- For my loop to work I need an extra separator at the end. I always look to the
-- left of the separator character for each array value
set @array = @array + @separator
-- Loop through the string searching for separtor characters
while patindex('%' + @separator + '%' , @array) <> 0
begin
-- patindex matches the a pattern against a string
select @separator_position = patindex('%' + @separator + '%' , @array)
select @array_value = left(@array, @separator_position - 1)
-- This is where you process the values passed.
-- Replace this select statement with your processing
-- @array_value holds the value of this element of the array
insert #ParsedArrays VALUES (@array_value)
-- This replaces what we just processed with and empty string
select @array = stuff(@array, 1, @separator_position, '')
end
set nocount off
select * from #ParsedArrays
drop table #ParsedArrays
go