【发布时间】:2015-09-17 16:23:28
【问题描述】:
我正在尝试使用单个 Update 语句来更新具有不同值的多条记录(我不是在尝试更新许多行以具有相同的值,这非常简单)。这是我现在正在尝试的:
using (var cn = GetOpenConnection()) {
// get items where we need to set calculated fields that will now be persisted in the DB
var items = cn.Query<MaintenanceItem>("select TOP 500 * from [Maintenance] where Tolerance IS NOT NULL");
foreach (var mi in maintItems)
{
// Set calculated fields on multiple recrods
logic.CalculateToleranceFields(mi, true);
}
var updateInput = items.Select(a => new {a.ToleranceMonths, a.ToleranceDays, a.ToleranceHours, a.ToleranceLandings, a.ToleranceCycles, a.ToleranceRIN }).ToList();
// THIS DOESN'T WORK - attempting to update multiple rows with different values
var numResults = cn.Execute(@"UPDATE rm
SET rm.ToleranceMonths=ur.ToleranceMonths,
rm.ToleranceDays=ur.ToleranceDays,
rm.ToleranceHours=ur.ToleranceHours,
rm.ToleranceLandings=ur.ToleranceLandings,
rm.ToleranceCycles=ur.ToleranceCycles,
rm.ToleranceRIN=ur.ToleranceRIN
from [RoutineItems] rm
Inner Join @UpdatedRecords ur ON rm.AircraftId=ur.AircraftId AND rm.ItemNumber=ur.ItemNumber", updateInput);
Assert.IsTrue(numResults == maintItems.Count());
}
Dapper 可以进行这种批量更新吗?我宁愿批量更新,也不愿使用 for 循环将数据推送到数据库中。
【问题讨论】:
-
你可以在 Sql Server 中创建一个用户类型,或者你可以通过使用 XML 和创建临时表等来模拟批量插入功能。做一个谷歌搜索,网上有很多例子。
标签: c# sql-server dapper