T-SQL:出现错误时控制流程

时间:2011-08-17 12:40:39

标签: tsql

Sup人,INSERT或UPDATE是否可能抛出一个会停止程序的异常?我有点像泡菜,因为我把交易挂在似乎是防弹代码的地方。

    BEGIN TRANSACTION;

SET @sSystemLogDataId  = CONVERT(NCHAR(36), NEWID());
INSERT INTO crddata.crd_systemlogdata (systemdataid,systemlogid,userid,
    actiondatetime,actionstate)
    VALUES(@sSystemLogDataId,@inSystemLogId,@sUserId,GETDATE(),@nActionState);
SET @nError = @@ERROR;

IF (1 = @nChangeMassprintTaskStatus) AND (0 = @nError)
BEGIN
    UPDATE crddata.crd_massprinttasks SET massprinttaskstatus=@nMassprintTaskStatus
        WHERE massprinttaskid = @inMassprintTaskId;
    SET @nError = @@ERROR;
END

IF (@MassprintTaskType <> 1) AND (27 = @nActionState) AND (0 = @nError)
BEGIN
    UPDATE crddata.crd_massprinttasks SET massprinttasktype=1
        WHERE massprinttaskid = @inMassprintTaskId;
    SET @nError = @@ERROR;
END

IF 0 = @nError
BEGIN
    COMMIT TRANSACTION;
END
ELSE
BEGIN
    ROLLBACK TRANSACTION;
END 

哈尔普,有人吗?

2 个答案:

答案 0 :(得分:5)

没有TRY / CATCH,这不是防弹。

错误可以是批量中止(例如,数据类型转换或从触发器抛出的错误),这意味着ROLLBACK不会运行。

使用TRY / CATCH而且我也一直使用SET XACT_ABORT

SET XACT_ABORT, NOCOUNT ON;
BEGIN TRY

    BEGIN TRANSACTION;

    SET @sSystemLogDataId  = CONVERT(NCHAR(36), NEWID());
    INSERT INTO crddata.crd_systemlogdata (systemdataid,systemlogid,userid,
        actiondatetime,actionstate)
        VALUES(@sSystemLogDataId,@inSystemLogId,@sUserId,GETDATE(),@nActionState);

    IF (1 = @nChangeMassprintTaskStatus)
    BEGIN
        UPDATE crddata.crd_massprinttasks SET massprinttaskstatus=@nMassprintTaskStatus
            WHERE massprinttaskid = @inMassprintTaskId;
    END

    IF (@MassprintTaskType <> 1) AND (27 = @nActionState)
    BEGIN
        UPDATE crddata.crd_massprinttasks SET massprinttasktype=1
            WHERE massprinttaskid = @inMassprintTaskId;
    END

    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    IF XACT_STATE() <> 0 --may already be rolled back by SET XACT_ABORT or a trigger
         ROLLBACK TRANSACTION;
    RAISERROR [rethrow caught error using ERROR_NUMBER(), ERROR_MESSAGE(), etc]
END CATCH

强制性背景阅读是Erland Sommarskog的"Error Handling in SQL 2005 and Later":我们稍后会对你进行测试......

答案 1 :(得分:0)

如果插入/更新不正确,则创建一个引发异常的触发器

示例:

create table t (id int)

go

create trigger tr on t 
for insert 
as
if exists(select 1 from inserted where id = 0)
    raiserror('id is not valid', 16, 1)

go

insert t select 1

select @@error

insert t select 0

select @@error