SQL

Comma Delimited List as Stored Procedure Parameter

May 22 2007

The crew at 4 Guys From Rolla have come through for me again (as they frequently do in matters of ASP, .NET and SQL). In building a new webservice, I wanted to be able to pass in a comma-delimited list of ID's to a SQL stored procedure. Unfortunately, there isn't a SQL datatype for something like "comma delimited list". I could have taken the "easy" way out and built the SQL query dynamically in C# instead of calling a stored procedure, but then I would have been mad at myself for breaking the rule that we agreed on that all the webservices would strictly call stored procedures. I figured I'd have to use SQL to parse a passed in string into ID's, and build the SQL query from there. However, this seemed like something someone else probably would have done in the past. I found a few techniques online but this one seemed the cleanest and best-implemented. You basically pass in a big varchar string of id's into the stored procedure and then call a SQL User Defined Function called "Split" which returns a table of the ID's which you can join to. It's simpler than it sounds...instead of having something like

SELECT *
FROM table
WHERE id in (--lots of convoluted code to parse out the ids--)

you just call

SELECT *
FROM table
WHERE id in ( SELECT convert(int,Value) FROM dbo.Split(@list_string,',') )

The complete code for the function and examples of how to use it are listed in the article. Thanks to "4 Guys" for saving me a couple hours and some headaches with this nifty technique!

Archives
December, 2011 (1)
April, 2011 (1)
November, 2010 (1)
May, 2010 (5)
April, 2010 (3)
January, 2010 (2)
November, 2009 (1)
October, 2009 (1)
January, 2009 (1)
October, 2008 (1)
July, 2008 (1)
May, 2008 (3)
April, 2008 (1)
March, 2008 (1)
February, 2008 (1)
January, 2008 (1)
November, 2007 (2)
October, 2007 (1)
September, 2007 (2)
August, 2007 (3)
Tags
.NET ASP award awards Banner blog Campaign Design Development DryJoys Flash FootJoy Forms Hacks Information Architecture Information Archtecture Interaction Internationalization iPad iPhone Launch Microsite Microsoft MITX mobile Nomenclature PhizzPop process Usability Web Standards
Contributors
Brandon (9)
Denis (4)
Denise (31)
Jon (12)