【问题标题】:update multiple rows using list of id in c#使用c#中的id列表更新多行
【发布时间】:2020-04-20 10:48:53
【问题描述】:

我有 id 列表,我想更新数据库表。我正在做这样的事情:

sql = "update table set col = 'something' where id in (@Ids)"

using (var connection = new SqlConnection(_connection)){
   connection.Query(sql, new { Ids = ids});
}

错误是:

System.Data.SqlClient.SqlException: '',' 附近的语法不正确。'

【问题讨论】:

  • 有很多例子可以说明如何做到这一点。 Here's one

标签: c# database


【解决方案1】:

最简单的方法是这样的:

var parameters = new string[ids.Length];
var cmd = new SqlCommand();
for (int i = 0; i < ids.Length; i++)
{
    parameters[i] = string.Format("@Id{0}", i);
    cmd.Parameters.AddWithValue(parameters[i], ids[i]);
}

  cmd.CommandText = string.Format("update table set col = 'something' where id in ({0})", string.Join(", ", parameters));

【讨论】:

    【解决方案2】:

    解决方案:这对我有用

    sql = "update table set col = 'something' where id in ("+string.Join(",", ids) + ");";
    
    using (var connection = new SqlConnection(_connection)){
       connection.Query(sql);
    }
    

    【讨论】:

    猜你喜欢
    • 2014-03-02
    • 2018-08-18
    • 1970-01-01
    • 2014-10-05
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    相关资源
    最近更新 更多