我有一个Reorders表,其中包含ProductID,ReorderAmount和Reorder Date字段。我还有一个名为Products的表,其中包含ProductID,ProductName,ProductDesc,VendorID,QtyOnHand,ReorderLevel和ReorderAmount字段。
我想要创建的是一个触发器,只要Products表中的QtyOnHand低于ReorderAmount,就会在Reorders表中创建一个条目,当然还要检查以确保订单尚未放置。然后我想要另一个触发器,当QtyOnHand超过ReorderAmount时,它将从Reorders表中删除条目。
我一直在查找如何操作的语法,但我仍然很困惑。 好像我需要这样做......
CREATE TRIGGER trReorder ON Products /*Not sure if I should
use Reorders instead of Products*/
IF EXISTS (SELECT * FROM Products WHERE QtyOnHand < ReorderAmount)
FOR
INSERT INTO Reorders
(ProductID, ReorderAmount, ReorderDate) VALUES (/*Not sure how to get
it to pull the ProductID and ReorderAmount from the specific Product
that was edited and how to get the current date*/)
我已经看到了很多不同的方法,我试着遵循最简单的方法,但我不确定我是否朝着正确的方向前进。
非常感谢任何帮助!我也很好奇是否一旦我弄清楚如何进行INSERT,如果DELETE类似地完成。提前致谢! :)
答案 0 :(得分:0)
快速鞭打这些,让我知道我是否错过了什么。
CREATE TRIGGER [dbo].[trReorder]
ON [dbo].[Products]
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS( SELECT p.ProductID
FROM Products p
INNER JOIN inserted i
ON p.ProductID = i.ProductID
WHERE p.ProductID = i.ProductID
AND p.QtyOnHand <= p.ReorderAmount)
BEGIN
INSERT INTO dbo.Reorders
SELECT p.ProductID, p.ReorderAmount, GETDATE()
FROM Products p
INNER JOIN inserted i
ON p.ProductID = i.ProductID
WHERE p.ProductID = i.ProductID
AND p.ProductID NOT IN (SELECT ProductID FROM dbo.Reorders)
END
END
CREATE TRIGGER [dbo].[trDelReorder]
ON [dbo].[Products]
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS( SELECT p.ProductID
FROM Products p
INNER JOIN inserted i
ON p.ProductID = i.ProductID
WHERE p.ProductID = i.ProductID
AND p.QtyOnHand > p.ReorderAmount)
BEGIN
DELETE
FROM dbo.Reorders
FROM dbo.Reorders r
INNER JOIN inserted i
ON r.ProductID = i.ProductID
END
END