我想参数化这个:
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'.
答案 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));
}