插入触发器无法从INSERTED捕获值

时间:2014-05-07 05:54:13

标签: sql-server tsql

   CREATE TRIGGER [dbo].[TUI_CRS] ON [dbo].[C_Rates_Shadow] 
   FOR UPDATE, INSERT
   AS BEGIN

    if exists (select 1 from INSERTED) begin

     RAISERROR('Result', 16, 1) 

    end

插入记录时我无法收到错误。但记录插入。

1 个答案:

答案 0 :(得分:3)

仅仅因为您生成了错误消息,这并不意味着事务将自动回滚。在某些情况下,您可能希望报告错误情况对数据库产生永久性影响。因此,如果您想阻止插入活动并报告错误,您必须自己这两个

所以,例如,这个脚本:

create table T (ID int not null)
go
create trigger T_T on T
after insert
as
    if exists(select * from inserted)
    begin
        RAISERROR('I''m an error but so what?',16,1)
    end
go
insert into T(ID) values (1),(2)
go
select * from T

产地:

Msg 50000, Level 16, State 1, Procedure T_T, Line 6
I'm an error but so what?

ID
-----------
1
2

然而,如果我们重新编写触发器:

delete from T
go
drop trigger T_T
go
create trigger T_T on T
after insert
as
    if exists(select * from inserted)
    begin
        RAISERROR('I''m an error and we''re going to stop',16,1)
        rollback
    end
go
insert into T(ID) values (1),(2)
go
select * from T

我们得到:

Msg 50000, Level 16, State 1, Procedure T_T, Line 6
I'm an error and we're going to stop
Msg 3609, Level 16, State 1, Line 1
The transaction ended in the trigger. The batch has been aborted.
ID
-----------