在查询的where子句中参数化多个OR

时间:2014-08-28 04:18:18

标签: c# sql-server

我想参数化这个:

select * from myTable where column1='1' or TaxRateRef='18'

这样的事情:

String query = "select * from myTable where "; // column1='1' or column1='18'

var parameters = new List<SqlParameter>();

for(int i = 0; i < data.Rows.Count;i++)
{
   blah blah blah

   query += " Column1='@column1' or";

   parameters.Add(new SqlParameter("@column1", i));

 }

然而我得到了一个例外

System.Data.SqlClient.SqlException :The variable name '@column1' has already been declared.Variable names must be unique within a query batch or stored procedure.
Incorrect syntax near 'or'.

2 个答案:

答案 0 :(得分:2)

错误很明显。您在for循环中添加了多次参数。你应该添加这一行...

parameters.Add(new SqlParameter("@column1", i));

在您的查询中只有一次。如果需要在循环的每次迭代中添加不同的值,只需将迭代编号(i)附加到参数名称,以使其唯一...

 query += string.Format(" Column1='@column1{0}' or", i);
 parameters.Add(new SqlParameter(string.Format("@column1{0}", i), i));

答案 1 :(得分:1)

原因是因为@column1一直在追加。使用下面的

parameters.Add(new SqlParameter(string.Format("@column1{0}", i), i));

String query = "select * from myTable where "; // column1='1' or column1='18'

var parameters = new List<SqlParameter>();

for(int i = 0; i < data.Rows.Count;i++)
{
  blah blah blah

  query += " Column1='@column1' or";

  parameters.Add(new SqlParameter("@column1", i));
  parameters.Add(new SqlParameter(string.Format("@column1{0}", i), i));

}