将多行更新为一个查询

Update multiple rows into one query

我需要以更快的方式更新多行和相同的列名。 直到现在我都在用这个;

Begin Transaction;
Update Inventory set Quantity-=1 where ID=1;
Update Inventory set Quantity-=4 where ID=2;
Update Inventory set Quantity-=1 where ID=1;
Update Inventory set Quantity-=5 where ID=4;
Commit;

此方法效果很好,但我不认为在相同的 table.Any 建议中快速编写每个值的所有查询? 正如我所读 sql 服务器不支持重复密钥更新...

对于简单的更新,您可以使用 CASE 语句:

UPDATE Inventory
SET Quantity += CASE ID
    WHEN 1 THEN -1
    WHEN 2 THEN -4
    WHEN 4 THEN -5
    ...
END
WHERE ID IN (1,2,4);

但是,这对于大量更新来说效率不高。在那些情况下,我更喜欢 'chunked' UPDATE 按具有相同更新的 ID 值分组:

UPDATE Inventory
SET Quantity += a
END
WHERE ID IN (X...);

UPDATE Inventory
SET Quantity += b
END
WHERE ID IN (Y...);

...

两者之间的组合也是可能的。 祝你好运。