回滚事务多个查询

时间:2014-04-15 10:34:50

标签: sql sql-server transactions rollback

我有一个如下的商店程序:

DECLARE @FinalQuery varchar(max), @TableName varchar(200)
DECLARE ListTable CURSOR FOR SELECT....
DECLARE @isError bit=0
OPEN ListTable 
FETCH NEXT FROM ListTable INTO @TableName
WHILE @@FETCH_STATUS=0
BEGIN
    //Some code to generate @FinalQuery to merge data into table @TableName
    BEGIN TRY
        EXEC(@FinalQuery)
    END TRY
    BEGIN CATCH
        Set @IsError = 1
        //Some code to write error to log file.
    END CATCH
    FETCH NEXT FROM ListTable INTO @TableName
END
CLOSE ListTable 
DEALLOCATE ListTable 

现在,我想在我的商店程序中添加事务和回滚。我想要执行所有动态@FinalQuery查询,最后,当它完成时,如果存在任何错误(@ IsError = 1),则回滚所有内容。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

 BEGIN TRAN
 BEGIN TRY
   EXEC(@FinalQuery)
END TRY
BEGIN CATCH
    Set @IsError = 1
    //Some code to write error to log file.
ROLLBACK
END CATCH
COMMIT

答案 1 :(得分:0)

如果您希望在发生错误时回滚所有更改,您是否尝试将事务移出循环?

OPEN ListTable 
FETCH NEXT FROM ListTable INTO @TableName
BEGIN TRY
    WHILE @@FETCH_STATUS=0
    BEGIN
        //Some code to generate @FinalQuery to merge data into table @TableName
        EXEC(@FinalQuery)
        FETCH NEXT FROM ListTable INTO @TableName
    END
    COMMIT
END TRY
BEGIN CATCH
    Set @IsError = 1
    //Some code to write error to log file.
    ROLLBACK
END CATCH
CLOSE ListTable 
DEALLOCATE ListTable