一种可能的解决方案是尽量减少更新表所需的时间。
我将首先创建一个临时表以从仓库中下载数据。
如果您必须在决赛桌中进行“插入、更新和删除”
让我们假设决赛桌是这样的:
Table Products:
ProductId int
QuantityOnHand Int
您需要从仓库更新 QuantityOnHand。
首先创建一个临时表,如:
Table Prodcuts_WareHouse
ProductId int
QuantityOnHand Int
然后像这样创建一个“操作”表:
Table Prodcuts_Actions
ProductId int
QuantityOnHand Int
Action Char(1)
更新过程应该是这样的:
1.截断表Prodcuts_WareHouse
2.截断表Prodcuts_Actions
3.用仓库中的数据填充Prodcuts_WareHouse表
4. 用这个填充 Prodcuts_Actions 表:
插入:
INSERT INTO Prodcuts_Actions (ProductId, QuantityOnHand,Action)
SELECT SRC.ProductId, SRC.QuantityOnHand, 'I' AS ACTION
FROM Prodcuts_WareHouse AS SRC LEFT OUTER JOIN
Products AS DEST ON SRC.ProductId = DEST.ProductId
WHERE (DEST.ProductId IS NULL)
删除
INSERT INTO Prodcuts_Actions (ProductId, QuantityOnHand,Action)
SELECT DEST.ProductId, DEST.QuantityOnHand, 'D' AS Action
FROM Prodcuts_WareHouse AS SRC RIGHT OUTER JOIN
Products AS DEST ON SRC.ProductId = DEST.ProductId
WHERE (SRC.ProductId IS NULL)
更新
INSERT INTO Prodcuts_Actions (ProductId, QuantityOnHand,Action)
SELECT SRC.ProductId, SRC.QuantityOnHand, 'U' AS Action
FROM Prodcuts_WareHouse AS SRC INNER JOIN
Products AS DEST ON SRC.ProductId = DEST.ProductId AND SRC.QuantityOnHand <> DEST.QuantityOnHand
到目前为止,您还没有锁定决赛桌。
5.在事务中更新最终表:
BEGIN TRANS
DELETE Products FROM Products INNER JOIN
Prodcuts_Actions ON Products.ProductId = Prodcuts_Actions.ProductId
WHERE (Prodcuts_Actions.Action = 'D')
INSERT INTO Prodcuts (ProductId, QuantityOnHand)
SELECT ProductId, QuantityOnHand FROM Prodcuts_Actions WHERE Action ='I';
UPDATE Products SET QuantityOnHand = SRC.QuantityOnHand
FROM Products INNER JOIN
Prodcuts_Actions AS SRC ON Products.ProductId = SRC.ProductId
WHERE (SRC.Action = 'U')
COMMIT TRAN
通过上述所有过程,您可以将要更新的记录数量减至最少,从而缩短最终表在更新时被锁定的时间。
您甚至可以在最后一步不使用事务,因此在命令之间将释放表。