The following code sample shows how to get Comma seperated values as table values
CREATE FUNCTION [dbo].[fnParseArray] (@strArray VARCHAR(8000), @separator VARCHAR(30))
RETURNS @Parameters TABLE (i varchar(2000))
AS BEGIN -- @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(8000) -- this holds each array value as it is returned
-- 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 @strArray = @strArray + @separator
-- Loop through the string searching for separtor characters while patindex('%' + @separator + '%' , @strArray) <> 0 begin
-- patindex matches the a pattern against a string select @separator_position = patindex('%' + @separator + '%' , @strArray) select @array_value = left(@strArray, @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
-- select Array_Value = @array_value insert into @Parameters values(@array_value)
-- This replaces what we just processed with and empty string -- if LEN(@separator)=1 -- select @strArray = stuff(@strArray, 1, @separator_position, '') -- else SELECT @strArray = stuff(@strArray, 1, @separator_position + (len(@separator)-1), '')
end
RETURN END
------------------------------------------
Exmaple
SELECT * FROM dbo.fnParseArray('one,two,three,four',',')
i --------------------------------- one two three four
(4 row(s) affected)
SELECT * FROM dbo.fnParseArray('First$Second$Third$Fourth','$')
i --------------------------------- First Second Third Fourth
(4 row(s) affected)
|
No responses found. Be the first to respond and make money from revenue sharing program.
|