我的前两个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
答案 0 :(得分:1)
您可以在存储过程中访问两个特殊表。可以检查表以反映数据的状态。请务必了解在某些情况下可以批量处理多个操作。
答案 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