A scenario I've repeatedly encountered in database development is to create a stored procedure that accepts a range of values as a comma delimited list and returns a result set that contains at least one of the values from the list. To do this, the parameter value must be parsed as something that can be understood by the IN clause. I prefer to turn the delimited list into a single tabled column. Because this task is so common, I wrote the following function that takes a comma delimited string and returns a table variable.
CREATE FUNCTION [dbo].[fnCommaDelimitedToTable]
(
@CommaDelimited varchar(5000)
)
RETURNS @returntable TABLE
(
FilterColumn varchar(50)
)
AS
BEGIN
SET @CommaDelimited = REPLACE(@CommaDelimited, ', ', ',')
WHILE CHARINDEX(',' , @CommaDelimited) > 0
BEGIN
INSERT INTO
@returntable
VALUES
(
SUBSTRING(@CommaDelimited, 0, CHARINDEX(',', @CommaDelimited))
)
SET @CommaDelimited = SUBSTRING(@CommaDelimited, CHARINDEX(',', @CommaDelimited) + 1,
LEN(@CommaDelimited))
END
-- Insert the last one, or if there was only one supplied.
INSERT INTO
@returntable
VALUES
(
@CommaDelimited
)
RETURN
END
With this function you can now write queries like
SELECT *
FROM
Customers
WHERE
Name IN (SELECT SearchFilter FROM dbo.fnCommaDelimitedToTable(@DelimitedNames))