【问题标题】:How to add parameter in SELECT query for fieldName IN @fieldName construction [duplicate]如何在 SELECT 查询中为 fieldName IN @fieldName 构造添加参数 [重复]
【发布时间】:2015-08-13 17:05:17
【问题描述】:
string idVariable = "qwerty";
string sqlQuery = "select id from user where id = @id";
sqlCommand.Parameters.Add("@id", SqlDbType.VarChar).Value = idVariable;

为特定字段添加值是可以的。

如果我需要在 WHERE 子句中有几个 id 和 IN 怎么办?

List<string> ids = new List<string>{"qwe", "asd", "zxc"};
string sqlQuery = "select id from user where id IN @ids";
sqlCommand.Parameters.Add("@ids", SqlDbType.???).Value = ids;

【问题讨论】:

    标签: c# sql sqlcommand


    【解决方案1】:

    您不能直接执行此操作,因为 IN 运算符需要一个值列表,而您的参数是包含列表的单个值。

    解决它的一种方法是使用表值参数 (here is an example),另一种方法是为 IN 以及查询动态创建参数:

    List<string> ids = new List<string>{"qwe", "asd", "zxc"};
    string sqlQuery = "select id from user where id IN(";
    for(int i=0; i < ids.Count; i++)
    {
        sqlQuery += "@Id"+ i + ",";
        sqlCommand.Parameters.Add("@id" + i, SqlDbType.varchar).Value = ids[i];
    }
    sqlQuery = sqlQuery.TrimEnd(",") + ")";
    

    【讨论】:

    • 您正在向具有相同名称 (@ids) 的 SqlCommand 对象添加多个参数。
    • @ThomasStringer 不错!固定。
    【解决方案2】:

    您需要单独添加它们。

    List<string> ids = new List<string>{"qwe", "asd", "zxc"};
    string sqlQuery = "select id from user where id IN (@id1, @id2, @id3)";
    
    sqlCommand.Parameters.Add("@id1", SqlDbType.VarChar).Value = ids[0];
    sqlCommand.Parameters.Add("@id2", SqlDbType.VarChar).Value = ids[1];
    sqlCommand.Parameters.Add("@id3", SqlDbType.VarChar).Value = ids[2];
    

    【讨论】:

      【解决方案3】:

      是的,您不能动态更改查询的性质。您可以编写具有固定数量选择的 in 并将它们添加为参数,或者您可以动态构建 SQL 字符串本身以添加 @id 参数的数量和它的值。由于您已经在命令中使用 SQL 字符串,因此这种动态 SQL 不是问题。如果您使用的是存储过程,这将不那么容易,但是您可以使用带有一堆可选参数的存储过程,然后只传递您需要的数量。当然,您也可以使用 Entity Framework 和 LINQ 来构建查询逻辑,并让 LINQ to EF 的提供者构建原始 SQL 查询。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-27
        • 2020-08-27
        • 1970-01-01
        • 2019-06-14
        相关资源
        最近更新 更多