如何在另一个表获取插入记录时使用减法更新表中的记录?

时间:2014-09-11 15:48:27

标签: tsql

我有一个包含ProductID和数量的dbo.Warehouse表和一个dbo.Orders表,其中包含为每个产品制作的订单等。 我创建了一个触发器,当新记录插入Order表时,它将更新Warehouse表, 然而,问题在于,当插入新记录时,所有记录都会更新而不仅仅是新的1,基本上如果我已经为ProductID 3放置了2个先前的订单,而且已经为ProductID 2放置了2个订单,而不仅仅是ProductID 3数量值得到更新(扣除),但也有产品ID 2已经扣除,请告知我可以用我的代码完成这项工作,谢谢。

ALTER TRIGGER Trg_AI_UpdateQty ON dbo.Orders
AFTER INSERT
AS


IF EXISTS (SELECT A.ProductID, A.Qty
       FROM dbo.Warehouse AS A
       INNER JOIN dbo.Orders AS B  ON A.ProductID = B.ProductID
       WHERE B.OrderQty > A.Qty
         )

BEGIN 
RAISERROR ('You do not have enough Products in stock, please order more', 1, 1)
END

ELSE

BEGIN

UPDATE B
SET B.Qty = (B.Qty - A.OrderQty) 
FROM dbo.Orders AS A
INNER JOIN dbo.Warehouse AS B  ON A.ProductID = B.ProductID
WHERE A.ProductID = B.ProductID

END

2 个答案:

答案 0 :(得分:1)

您需要连接插入的表而不是触发器在SO上的基础表:

以下是有关特殊删除和插入表格的更多信息

http://msdn.microsoft.com/en-us/library/ms191300.aspx

ALTER TRIGGER Trg_AI_UpdateQty ON dbo.Orders
AFTER INSERT
AS


IF EXISTS (SELECT A.ProductID, A.Qty
       FROM dbo.Warehouse AS A
       INNER JOIN inserted AS B  ON A.ProductID = B.ProductID
       WHERE B.OrderQty > A.Qty
         )

BEGIN 
RAISERROR ('You do not have enough Products in stock, please order more', 1, 1)
END

ELSE

BEGIN

UPDATE B
SET B.Qty = (B.Qty - A.OrderQty) 
FROM inserted AS A
INNER JOIN dbo.Warehouse AS B  ON A.ProductID = B.ProductID
WHERE A.ProductID = B.ProductID

END

答案 1 :(得分:0)

试试这个

ALTER TRIGGER Trg_AI_UpdateQty ON dbo.Orders
AFTER INSERT
AS
IF EXISTS (SELECT 1
       FROM dbo.Warehouse AS A
       INNER JOIN inserted AS B  ON A.ProductID = B.ProductID
       WHERE B.OrderQty > A.Qty)
BEGIN 
RAISERROR ('You do not have enough Products in stock, please order more', 1, 1)
END
ELSE
BEGIN
UPDATE B
SET B.Qty = (B.Qty - A.OrderQty) 
FROM inserted AS A
INNER JOIN dbo.Warehouse AS B  ON A.ProductID = B.ProductID
WHERE A.ProductID = B.ProductID 
END

在旁注上,当您使用select 1

时,请尝试if exists