我有一个名为idList的整数列表。我想在Tasks表中为该idList中的每个id更新TaskState。这就是我的代码现在的样子:
using (SqlConnection dataconnection = new SqlConnection(DB))
{
SqlCommand sqlCommandDelete = new SqlCommand()
{
Connection = dataconnection
};
dataconnection.Open();
foreach (var id in idList)
{
qlCommandDelete.CommandText = $"UPDATE Tasks SET TaskState = 2 WHERE TaskID = {id}";
sqlCommandDelete.ExecuteNonQuery();
}
}
现在的问题是每次循环触发时都会执行。有没有办法连接所有TaskID并只执行一次?
答案 0 :(得分:2)
你可以这样做
var ids = idList.Aggregate((x, y) => $"{x}, {y}")
然后按如下所示编写sql文本
qlCommandDelete.CommandText = $"UPDATE Tasks SET TaskState = 2 WHERE TaskID in ({ids})";