I want to give this discussion a little more context. This seems to fall under the topic of "how do I get multiple rows of data to sql". In @Kate's case she is trying to DELETE-WHERE-IN, but useful strategies for this user case are very similar to strategies for UPDATE-FROM-WHERE-IN or INSERT INTO-SELECT FROM. The way I see it there are a few basic strategies.
String Concatenation
This is the oldest and most basic way. You do a simple "SELECT * FROM MyTable WHERE ID IN (" + someCSVString + ");"
- Super simple
- Easiest way to open yourself to a SQL Injection attack.
- Effort you put into cleansing the string would be better spent on one of the other solutions
Object Mapper
As @MarcGravell suggested you can use something like dapper-dot-net, just as Linq-to-sql or Entity Framework would work. Dapper lets you do connection.Execute("delete from MyTable where ID in @ids", new { ids=listOfIds });
Similarly Linq would let you do something like from t in MyTable where myIntArray.Contains( t.ID )
- Object mappers are great.
- However, if your project is straight ADO this is a pretty serious change to accomplish a simple task.
CSV Split
In this strategy you pass a CSV string to SQL, whether ad-hoc or as a stored procedure parameter. The string is processed by a table valued UDF that returns the values as a single column table.
- This has been a winning strategy since SQL-2000
- @TimSchmelter gave a great example of a csv split function.
- If you google this there are hundreds of articles examining every aspect from the basics to performance analysis across various string lengths.
Table Valued Parameters
In SQL 2008 custom "table types" can be defined. Once the table type is defined it can be constructed in ADO and passed down as a parameter.
- The benefit here is it works for more scenarios than just an integer list -- it can support multiple columns
- strongly typed
- pull string processing back up to a layer/language that is quite good at it.
- This is a fairly large topic, but Table-Valued Parameters in SQL Server 2008 (ADO.NET) is a good starting point.