首页 > 解决方案 > 使用 c# 中的 id 列表更新多行

问题描述

我有 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:'','附近的语法不正确。'

标签: c#database

解决方案


最简单的方法是这样的:

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));

推荐阅读