I would like to call a sql statement such as:
Select * From Table Where Column in (\'value1\', \'value2\', \'value3\')
Is it as simple as s
@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)
if you only have three parameters for the in clause then yes you can use the parameters. Otherwise you can build dynamic SQL (Be careful of SQL injection attacks).
Another approach is to create a UDF which takes a delimited string and returns a table. then you could modify your query to be:
select * from
table inner join
dbo.fn_stringToTable(@params)
Another option is to set the SqlCommand's commandtype to "text" and construct the entire Sql string in code... Assuming Column is a varchar, and you have the Values in a string arrray, named "paramValues"
StringBuilder sbSql = new StringBuilder
("Select * From Table Where Column in (");
string[] paramValues = new string[] {"value1", "value2", "value3"};
foreach (string val in paramValues)
sbSql.Append("'" + val + "', ");
sbSql = sbSql.Remove(sbSql.Length - 2, 2);
sbSql.Append(")");
SqlCommand cmd = new SqlCommand(sbSql.ToString());
cmd.CommandType = CommandType.Text;