Categories
SQL Server

Handling comma-delimited lists as stored procedure input

Comma-delimited lists can be used as input to stored procedure, assuming their length is predictable.
Handling them inside the body of the stored procedure, is not a native matter (no FOREACH construct) and requires minor programming.
For example, using an input variable called @sad_date:


WHILE (LEN(@sad_date) > 0)
BEGIN
-- extract the string at the head of the list
SET @commaPos = CHARINDEX(',', @sad_date);
IF (@commaPos > 0)
BEGIN
SET @dateStr = SUBSTRING(@sad_date, 1, (@commaPos-1));
SET @sad_date = SUBSTRING(@sad_date, (@commaPos+1), LEN(@sad_date));
END
ELSE
-- we reached the last substring
BEGIN
SET @dateStr = SUBSTRING(@sad_date, 1, LEN(@sad_date));
SET @sad_date = '';
END
--
-- do something with the input here....
---
END

Share

Leave a Reply

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

 

Share