如何调试数据库触发器无效的原因?

时间:2017-05-10 18:00:54

标签: sql sql-server

我的前两个IF语句工作正常(我已经测试过它们),但由于某种原因,ELSE IF语句不会触发。我尝试了整个ELSE IF语句的不同设置,与@DiscountPercent的不同安排,以及IF语句的顺序不同,但没有任何作用。当需要30时,这一切都会导致.3。有人可以指出我可以了解我做错的方向吗?

USE MyGuitarshop

GO

CREATE TRIGGER Products_UPDATE
    ON Products
    FOR UPDATE, INSERT

AS

DECLARE
    @DiscountPercent int;

BEGIN

SET @DiscountPercent = (SELECT DiscountPercent FROM INSERTED);

IF @DiscountPercent < 0
    BEGIN
        ROLLBACK TRANSACTION;
        THROW 528732,'Discount Percent cannot be less than 0.',1;
    END;

IF @DiscountPercent > 100 
    BEGIN
        ROLLBACK TRANSACTION;
        THROW 528733,'Discount Percent cannot be greatter than 100%.',1;
    END;

ELSE IF @DiscountPercent < 1 
        UPDATE Products
            SET @DiscountPercent = ((SELECT DiscountPercent FROM INSERTED) * 100)
            WHERE ProductID IN (Select ProductID FROM Inserted);

END;

GO

UPDATE Products
    SET DiscountPercent = .3
        WHERE ProductID = 1;

GO

USE MyGuitarShop

SELECT * FROM Products

3 个答案:

答案 0 :(得分:1)

您可以在存储过程中访问两个特殊表。可以检查表以反映数据的状态。请务必了解在某些情况下可以批量处理多个操作。

Trigger - Inserted and Deleted Tables

答案 1 :(得分:0)

您需要从DiscountPercent表中获取INSERTED的值,然后检查它:

DECLARE
    @DiscountPercent int;
Begin
SET @DiscountPercent = (SELECT DiscountPercent FROM INSERTED);
.
.
.

Update/Insert一行时,如果行数超过1 Updated/Inserted,那么你将需要使用其他方式来获取所有值。

答案 2 :(得分:0)

想出来!!!!这就是代码需要工作的地方:

USE MyGuitarshop

GO

CREATE TRIGGER Products_UPDATE
    ON Products
    FOR UPDATE, INSERT

AS

DECLARE
    @DiscountPercent int;

BEGIN

SET @DiscountPercent = (SELECT DiscountPercent FROM INSERTED);

IF @DiscountPercent < 0
    BEGIN
        ROLLBACK TRANSACTION;
        THROW 528732,'Discount Percent cannot be less than 0.',1;
    END;

IF @DiscountPercent > 100 
    BEGIN
        ROLLBACK TRANSACTION;
        THROW 528733,'Discount Percent cannot be greatter than 100%.',1;
    END;

ELSE
    UPDATE Products
        SET DiscountPercent = (SELECT DiscountPercent FROM INSERTED) * 100
            FROM Products
                Join Inserted
                    On Products.ProductID = Inserted.ProductID
            WHERE (SELECT DiscountPercent FROM INSERTED) < 1

END;

GO

UPDATE Products
    SET DiscountPercent = .3
        WHERE ProductID = 4;

GO

USE MyGuitarShop

SELECT * FROM Products