我是SQL Server和触发器的新手。我有一个现有的触发器,我需要自定义。有两个表产品(包含库存中的产品总数。数量)和OrdersLines(包含有关订单的所有信息。示例行将包含OrderID,ProductID和Amount) 当我下订单时,产品金额是保留的。 我需要触发器来检查新的订购金额是否超过数量。如果是,抛出RAISERROR,如果没有,让事务继续。
我无法识别要检查库存数量的总订单数量。
触发器适用于OrdersLines表 我正在考虑做一些事情:
IF EXISTS ((SELECT *
FROM Products AS p
JOIN inserted AS i
ON p.ProductID = i.ProductID
JOIN OrdersLines AS o
ON p.ProductID = o.ProductID
WHERE (SUM(o.Amount) + i.Amount) <= p.Quantity)
BEGIN
GOTO ContinueTransaction
END ELSE BEGIN
GOTO RollbackTransaction
END
但我认为这不正确。同样在ELSE我需要RAISERROR来通知订单没有添加,但我不确定如何。有些论据可以放在那里,现在让我感到困惑。
答案 0 :(得分:0)
create trigger CheckOrderAmount
On orderLines
for insert, update
As
Begin
Set NoCount On;
if exists (Select * from inserted I
join products p
on p.ProductID = i.ProductID
group by i.ProductID
having SUM(i.Amount) > p.Quantity)
begin
rollback transaction
raiserror("There are not enough items in inventory", 16, 1)
end
end
答案 1 :(得分:0)
以下问题解决了。 对于插入触发器:
IF EXISTS (SELECT *
FROM atbv_Sales_Products p
JOIN inserted i
ON p.ProductID = i.ProductID
JOIN atbv_Sales_OrdersLines ol
ON p.ProductID = i.ProductID
GROUP BY i.ProductID, i.Amount, p.Quantity
HAVING (SUM(ol.Amount) + i.Amount) > p.Quantity)
BEGIN
DECLARE @ProductName NVARCHAR(60)
SET @ProductName = (SELECT p.ProductName
FROM atbv_Sales_Products p
JOIN inserted i
ON i.ProductID = p.ProductID)
RAISERROR ('----There is not enough items (%s) left----', 18, 1, @ProductName) ROLLBACK TRANSACTION
RETURN
END
更新触发器:
IF EXISTS (SELECT *
FROM atbv_Sales_Products p
JOIN atbv_Sales_OrdersLines ol
ON ol.ProductID = p.ProductID
GROUP BY p.ProductID, ol.Amount, p.Quantity
HAVING SUM(ol.Amount) > p.Quantity)
BEGIN
DECLARE @ProductName NVARCHAR(60)
SET @ProductName = (SELECT p.ProductName
FROM atbv_Sales_Products p
JOIN atbv_Sales_OrdersLines ol
ON ol.ProductID = p.ProductID
GROUP BY p.ProductID, ol.Amount, p.Quantity, p.ProductName
HAVING SUM(ol.Amount) > p.Quantity)
RAISERROR ('----There is not enough items (%s) left----', 18, 1, @ProductName) ROLLBACK TRANSACTION
RETURN
END