c# - 使用 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:'','附近的语法不正确。'
解决方案
最简单的方法是这样的:
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));
推荐阅读
- mysql - MySQL 更新表 WHERE 列中的另一个是
- google-apps-script - 有没有办法从 Google Doc 中的图像、按钮或链接调用 myFunction(),而不是使用菜单?
- oracle - oracle中如何通过查询加快下单速度
- javascript - 提出请求后,Request.body 为空对象
- web-applications - 如何将非服务应用程序作为服务运行
- php - 来自 JSON 字段的对象的 Getter
- python - 用另一个数据集中的列中的值填充空值
- bash - 通过 PyCharm IDE 打开时,在 bash 中向上滚动一行
- three.js - WebGL 1 中的 `blendFunci` 是否有等价物?
- unity3d - Snapped GO 的旋转无法正常工作