如何处理触发器中的异常?

时间:2015-01-27 06:17:45

标签: c# sql sql-server triggers

我知道这个问题可能与this question重复。但我没有通过这个问题清除我的困惑。在SQL中,我们使用触发器对数据库进行操作,例如插入,更新,删除查询。但是我们如何处理触发器中的After insert语句中发生的异常?例如..

CREATE TRIGGER triggerAfterInsert ON Employee 
FOR INSERT
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit varchar(100);

select @empid=i.Emp_ID from inserted i; 
select @empname=i.Emp_Name from inserted i; 
select @empsal=i.Emp_Sal from inserted i;   
set @audit='Inserted Record -- After Insert Trigger.';

insert into Employee_Audit
       (Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp) 
values(@empid,@empname,@empsal,@audit_action,getdate());

PRINT 'AFTER INSERT trigger executed.'
GO

在上面插入查询时,我设置文本值而不是整数到empid,即@ empid = a然后它在触发器中抛出异常,我不知道如何处理这些异常,任何人都可以建议我这个问题吗?

2 个答案:

答案 0 :(得分:1)

实施例: 创建时

CREATE TRIGGER tr_Ins_Test_Trig ON dbo.Test_Trig
AFTER INSERT
AS
BEGIN
    BEGIN TRY
        BEGIN TRANSACTION

        INSERT INTO Test_Trig2
        SELECT id + 1 FROM INSERTED
        COMMIT TRANSACTION 
    END TRY

    BEGIN CATCH

    ROLLBACK TRANSACTION
    INSERT INTO Trig_Error
    SELECT *,'err' FROM inserted

    END CATCH
END
GO 

实施例: 改变时

ALTER TRIGGER tr_Ins_Test_Trig ON dbo.Test_Trig
AFTER INSERT
AS
BEGIN
    BEGIN TRY
        BEGIN TRANSACTION

        INSERT INTO Test_Trig2
        SELECT id + 1 FROM INSERTED
        COMMIT TRANSACTION 
    END TRY

    BEGIN CATCH

    DECLARE @Trig_Error TABLE(
    id INT, col CHAR(3)
    );

    INSERT INTO @Trig_Error
    SELECT *,'err' FROM inserted

    ROLLBACK TRANSACTION

    INSERT INTO Trig_Error
    SELECT * FROM @Trig_Error

    END CATCH
END
GO 

答案 1 :(得分:1)

他更像是通过程序处理案件。

这是使用用户定义的异常进行异常处理的示例:

DECLARE
v_cnt NUMBER;
count_more_than_one EXCEPTION;
BEGIN
select count(*) into v_cnt
from whatever 
where whatever;

if v_cnt > 1 then
raise count_more_than_one;
else
whatever;
end if;
EXCEPTION
when count_more_than_one then
dbms_output.put_line('Some error message you can build here or up above');

when no_data_found then
this is a built-in exception;
END;