【问题标题】:Insert Trigger Cannot capture value from INSERTED插入触发器无法从 INSERTED 捕获值
【发布时间】:2014-05-07 14:24:32
【问题描述】:
   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

插入记录时无法出错。但是记录被插入。

【问题讨论】:

  • 请分享您的表结构和插入语句

标签: sql-server tsql


【解决方案1】:

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

例如,这个脚本:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-24
    • 2013-04-24
    • 1970-01-01
    相关资源
    最近更新 更多