使用In()参数不起作用

时间:2012-01-20 23:15:52

标签: c# ado.net

我似乎无法使用sql参数

string itemIds = "86,74,32";

cmd.Parameters.AddWithValue("Items", itemIds);

                    string sql = "SELECT * " +
                                 "FROM Items " +
                                 "WHERE ItemIds IN(@Items)";

2 个答案:

答案 0 :(得分:2)

您应该单独添加每个参数。

string item1 = "86";
string item2 = "32";

cmd.Parameters.AddWithValue("item1", item1);
cmd.Parameters.AddWithValue("item2", item2);

                    string sql = "SELECT * " +
                                 "FROM Items " +
                                 "WHERE ItemIds IN(@item1,@item2)";

这可能会奏效。

使用for循环进行编辑

string [] numbers = {"12", "23", "34"};
string [] parameters = new string[numbers.Length];
for (int i = 0; i < numbers.Length; i++)
{
     cmd.Parameters.AddWithValue("param"+i, numbers[i]);
     parameters[i] = "@param" + i;
}

var str = String.Join(",", parameters);
string sql = String.Format("SELECT * FROM Items WHERE ItemIds IN({0})",str);

答案 1 :(得分:1)

您不能将In()个参数的完整列表放在一个 SQL参数中,而是必须将每个参数放在一个单独的参数中。

这是构造查询字符串并添加参数的优雅方法:
Parameterize an SQL IN clause