Using an 'IN' operator with a SQL Command Object and C# 2.0

c#-2.0, sql

Solution

@Charles: You're going into the right direction, but we're using parametrized queries to mainly prevent SQL injections. Putting 'external' values (`params string[] args`) hardcoded in queries is asking for trouble. You can iterate the arguments, but you still have to use parameters like this:

   string[] values = new [] {"value1", "value2", "value3", "value4"};
   StringBuilder query = new StringBuilder("Select * From Table Where Column in (");
   SqlCommand cmd = new SqlCommand();
   cmd.Connection = new SqlConnection("Your connection string");
   for(int i = 0; i < columns.Length; i++)
   {
       string arg = string.Format("@arg{0}", i);
       cmd.Parameters.AddwithValue(arg, SanatizeSqlString(columns[i]));
       sb.AppendFormat("{0}, ", arg);
   }
   sb = sb.Remove(sb.Length -2, 2);
   sb.Append(")");
   cmd.CommandText = sb.ToString();

This way you'll end up with a query like:

select * from table where column in (@arg0, @arg1, @arg2, @arg3)

Problem

I would like to call a sql statement such as: ``` Select * From Table Where Column in ('value1', 'value2', 'value3') ``` Is it as simple as setting a command parameter's value equal to "`('value1', 'value2', 'value3')`"?

Original source

Related problems