THROW语句是否包含ROLLBACK?

时间:2017-03-23 09:10:10

标签: triggers sql-server-2012 throw

我目前正在学习SQL Server 2012,这是我在ANIMALS表上的触发器,它不允许插入超过3种相同类型的动物。

可能有更好的解决方案来实现这一点,但我对THROWROLLBACK语句感到好奇。

问题是:THROW是否包含ROLLBACK并且是否有必要(或者更好)使用这两种语句?我尝试了他们两个并分开,触发始终工作...

create trigger TRI_ANIMALS 
on ANIMALS
after insert
as
begin
    declare @NewAnimalId int

    select @NewAnimalId = inserted.FK_ANIMAL_TYPE 
    from inserted

    if (select count(*) from ANIMALS
        where @NewAnimalId = ANIMALS.FK_ANIMAL_TYPE) > 4
    begin;
        throw 50002, 'There are already 3 animals of the same type', 1;
        rollback;
    end;
end
go

/* test */
insert into ANIMALS(NAME, FK_ANIMAL_TYPE) values('Bono', 2);
insert into ANIMALS(NAME, FK_ANIMAL_TYPE) values('Cesar', 2);
insert into ANIMALS(NAME, FK_ANIMAL_TYPE) values('Ron', 2);
/* this must not be inserted */
insert into ANIMALS(NAME, FK_ANIMAL_TYPE) values('Ares', 2);

0 个答案:

没有答案