sql update触发器没有执行

时间:2013-11-26 14:19:31

标签: sql-server tsql triggers sql-update

我在名为Products的表上有此触发器,但无论我将DiscountPercent值设置为什么,它似乎都没有做任何事情。

    CREATE TRIGGER Products_UPDATE
ON Products
AFTER UPDATE
    AS 
    DECLARE @NewData decimal
    IF (SELECT DiscountPercent FROM Inserted) < 0 AND (SELECT DiscountPercent FROM Inserted) > 100
BEGIN;
    THROW 50001, 'Please enter a valid discount percent', 1
    ROLLBACK TRAN
END
    IF (SELECT DiscountPercent FROM Inserted) < 1
UPDATE Products
SET DiscountPercent = (SELECT DiscountPercent FROM Inserted) * 100
WHERE ProductID = (SELECT ProductID FROM Inserted)

2 个答案:

答案 0 :(得分:1)

如果折扣是&lt;

我想你想抛出一个错误0 OR &gt; 100 所以这一行

IF (SELECT DiscountPercent FROM Inserted) < 0 AND (SELECT DiscountPercent FROM Inserted) > 100

应该成为这一行

IF (SELECT DiscountPercent FROM Inserted) < 0 OR (SELECT DiscountPercent FROM Inserted) > 100

编辑:您还可以尝试更改raiserror

的投掷
RAISERROR (N'This is message %s %d.', -- Message text.
            10, -- Severity,
            1   -- State
          )

答案 1 :(得分:1)

首先,我建议使用EXISTS() statement

其次,确保所有触发逻辑都使用set-based logic。否则,如果用户插入两条或更多条记录,您的触发器将会爆炸。我更新了你的IF和UPDATE语句。

第三,使用RAISERROR() statement。如果您使用的是SQL Server 2012,请仅使用THROW() statement

CREATE TRIGGER Products_UPDATE
ON Products
AFTER UPDATE
AS 

    IF EXISTS (SELECT 1 FROM Inserted WHERE DiscountPercent NOT BETWEEN 0 AND 100)
    BEGIN
        ROLLBACK TRAN
        RAISERROR('Please enter a valid discount percent', 16, 10)
    END
    ELSE
        UPDATE Products
        SET DiscountPercent = Inserted.DiscountPercent * 100
        FROM Products
            Join Inserted
            On Products.ProductID = Inserted.ProductID -- IFF ProductID is PK
        WHERE Inserted.DiscountPercent < 1
GO