Working with a SqlCommand in C# I’ve created a query that contains a IN (list…) part in the where clause. Instead of looping through my string list generating the list I need for the query (dangerous if you think in sqlInjection). I thought that I could create a parameter like:
SELECT blahblahblah WHERE blahblahblah IN @LISTOFWORDS
Then in the code I try to add a parameter like this:
DataTable dt = new DataTable(); dt.Columns.Add('word', typeof(string)); foreach (String word in listOfWords) { dt.Rows.Add(word); } comm.Parameters.Add('LISTOFWORDS', System.Data.SqlDbType.Structured).Value = dt;
But this doesn’t work.
Questions:
- Am I trying something impossible?
- Did I took the wrong approach?
- Do I have mistakes in this approach?
Thanks for your time 🙂
What you are trying to do is possible but not using your current approach. This is a very common problem with all possible solutions prior to SQL Server 2008 having trade offs related to performance, security and memory usage.
This link shows some approaches for SQL Server 2000/2005
SQL Server 2008 supports passing a table value parameter.
I hope this helps.