我发现很难理解这段代码在做什么。有人可以帮我逐行理解这段代码,以便我能理解它在做什么。
CREATE TRIGGER LowCredit ON Order
AFTER INSERT
AS
DECLARE @creditrating tinyint
SELECT @creditrating = v.CreditRating
FROM Customer c INNER JOIN inserted i
ON c.custID = i.custID
IF @creditrating = 5
BEGIN
RAISERROR ('This customers''s credit rating
is too low to accept new orders.’)
ROLLBACK TRANSACTION
END
答案 0 :(得分:2)
正在检查信用评级是否为某个值,如果信用评级太低则引发错误并回滚交易。
--Declare a trigger with name `LowCredit` on table `Order`,
--run the trigger after
CREATE TRIGGER LowCredit ON Order
insert.
AFTER INSERT
AS
--start definition
--declare int
DECLARE @creditrating tinyint
--select from existing customer record the
-- inserted rows credit ranking (by custID)
-- inserted is the vt containing the changed rows
SELECT @creditrating = v.CreditRating
FROM Customer c INNER JOIN inserted i
ON c.custID = i.custID
--if lower than 5 roll back
IF @creditrating = 5
BEGIN
--raise error to the session
RAISERROR ('This customers''s credit rating
is too low to accept new orders.’)
--roll back transaction
ROLLBACK TRANSACTION
END
答案 1 :(得分:1)
如果客户的信用评级太低,触发器中的ROLLBACK将阻止在Order
中插入行...
inserted
是一个包含插入行的虚拟表。
答案 2 :(得分:1)
错误在第7行。将v.
替换为i.
或c.
。
答案 3 :(得分:0)
INSERTED
是一个特殊的表,其中包含Order
表中新的(或更改为UPDATE)行的副本
这用于查看Customer
表以查找信用评级。
如果信用评级过低,则会引发错误
一些问题:
注意:
答案 4 :(得分:0)
如果评级小于5,则会检查客户订单的“CreditRating”,并且会引发错误并且交易将是回滚。我希望编码器在其他地方使用Begin Transaction其他明智的RollBack事务而没有Begin会给出错误