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

若如初见. 提交于 2019-12-31 01:47:49

问题


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')"?


回答1:


@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)



回答2:


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; 



回答3:


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)


来源:https://stackoverflow.com/questions/400819/using-an-in-operator-with-a-sql-command-object-and-c-sharp-2-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!