2011-06-01 206 views
1

我很难理解这段代码在做什么。有人可以帮助我逐行理解这段代码,以便我能够理解它在做什么。SQL语句。需要帮助了解它

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 

回答

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 
+0

-1根据我的问题在我的答案。即使你是正确的,代码也是错误的。 – gbn 2011-06-02 07:27:22

+0

他并没有要求我找到一个错误,他要求解释代码。 – Nix 2011-06-02 12:09:23

1

在触发将阻止该行的插入在Order如果客户的信用等级太低回滚...

inserted是包含插排(S)的虚拟表。

+1

对于一个随机的客户,如果插入很多订单... – gbn 2011-06-01 11:56:08

0

INSERTED是一个包含新的(或改变UPDATE)排在Order

此副本是用来窥视Customer表中找到信用评级一个特殊的表。

如果信用等级过低,则会引发错误

的一些问题:

  • 它不会处理多行(例如,许多订单一气呵成)。实际的信用评级被检查将是一个随机排出来的但是许多插入
  • 没有try/catch块,以提供更好的错误处理,并停止触发因素是批次中止
  • 失踪SET NOCOUNT ON将使大部分的客户在某些时候

注:

  • 触发器是INSERT语句范围的部分,关联交易
0

如果评级小于5,那么它将检查正在创建订单的客户的“CreditRating”,并且出现错误并且交易将回滚。我希望编码器已经使用BEGIN TRANSACTION别的其他明智ROLLBACK TRANSACTION地方没有开始将报错

1

的错误是第7行与i.c.更换v.

+0

+1用于发现错误 – harag 2011-06-01 13:16:59