请你帮我完成我的触发器。到目前为止我得到了什么:
CREATE TRIGGER [dbo].[atbl_Sales_OrdersLines_ITrigGG]
ON [dbo].[atbl_Sales_OrdersLines]
FOR INSERT
AS
BEGIN
DECLARE @ID INT = (SELECT ProductID
FROM INSERTED)
DECLARE @OrderedQ INT = (SELECT SUM(Amount)
FROM atbl_Sales_OrdersLines
WHERE ProductID = @ID)
DECLARE @CurrentQ INT = (SELECT Quantity
FROM atbl_Sales_Products
WHERE ProductID = @ID)
DECLARE @PossibleQ INT = (SELECT Amount
FROM INSERTED
WHERE ProductID = @ID)
IF (@CurrentQ - @OrderedQ >= @PossibleQ)
ELSE
END
我需要完成代码。无法弄清楚该怎么做。如果满足条件,我需要 - 触发器允许插入。如果是,则触发器将停止插入/或回滚,并提示数量不足的消息。
此外,如果insert是具有不同产品ID的多行,此代码是否有效?
感谢。
答案 0 :(得分:1)
这样的事可能有用。此触发器检查插入中的产品,汇总已订购的总数(现在和过去),如果其中任何一个超过可用数量,则回滚整个事务。每当编写触发器时,您都希望避免任何假设,即插入/更新/删除单行,并避免使用游标。您只想使用基于基本集的操作。
CREATE TRIGGER [dbo].[atbl_Sales_OrdersLines_ITrigGG]
ON [dbo].[atbl_Sales_OrdersLines]
FOR INSERT
AS
BEGIN
IF (exists (select 1 from (
select x.ProductId, totalOrdersQty, ISNULL(asp.Quantity, 0) PossibleQty from (
select i.ProductId, sum(aso.Amount) totalOrdersQty
from (select distinct ProductId from inserted) i
join atbl_Sales_OrdersLines aso on aso.ProductId = i.ProductId
group by productId) x
left join atbl_Sales_Product asp on asp.ProductId = x.ProductId
) x
where PossibleQty < totalOrdersQty))
BEGIN
RAISERROR ('Quantity is not sufficient' ,10,1)
ROLLBACK TRANSACTION
END
END
我仍然认为这是一个可怕的想法。
答案 1 :(得分:0)
试试这个,
CREATE TRIGGER [dbo].[atbl_Sales_OrdersLines_ITrigGG]
ON [dbo].[atbl_Sales_OrdersLines]
INSTEAD OF INSERT --FOR INSERT
AS
BEGIN
DECLARE @ID INT = (SELECT ProductID
FROM INSERTED)
DECLARE @OrderedQ INT = (SELECT SUM(Amount)
FROM atbl_Sales_OrdersLines
WHERE ProductID = @ID)
DECLARE @CurrentQ INT = (SELECT Quantity
FROM atbl_Sales_Products
WHERE ProductID = @ID)
DECLARE @PossibleQ INT = (SELECT Amount
FROM INSERTED
WHERE ProductID = @ID)
IF (@CurrentQ - @OrderedQ >= @PossibleQ)
BEGIN
INSERT INTO YOURTABLE (COLUMN1, COLUMN2, COLUMN3, ..)
SELECT COLUMN1, COLUMN2, COLUMN3, ..
FROM inserted
END
ELSE
BEGIN
RAISERROR ('Quantity is not sufficient' ,10,1)
ROLLBACK TRANSACTION
END