游标内的事务

时间:2017-03-30 14:10:45

标签: sql sql-server

以下是在游标中使用事务的正确方法:

SET CURSOR_CLOSE_ON_COMMIT ON;

DECLARE cur CURSOR LOCAL FOR 
    SELECT * FROM @ordersToProcess;
OPEN cur;

DECLARE @OrderId int;

FETCH NEXT FROM cur INTO @OrderId;
WHILE @@FETCH_STATUS = 0 BEGIN
    BEGIN TRY
        BEGIN TRAN;
        EXEC process_order @OrderId;
        COMMIT TRAN;
        DEALLOCATE cur;                 
        SET CURSOR_CLOSE_ON_COMMIT OFF;
    END TRY
    BEGIN CATCH
        ROLLBACK TRAN;
        DEALLOCATE cur;
        SET CURSOR_CLOSE_ON_COMMIT OFF;
        THROW;
    END CATCH;  

    FETCH NEXT FROM cur INTO @OrderId;
END;

2 个答案:

答案 0 :(得分:2)

没有。你有这个代码:

WHILE @@FETCH_STATUS = 0 BEGIN
    BEGIN TRY
        BEGIN TRAN;
        EXEC process_order @OrderId;
        COMMIT TRAN;
        DEALLOCATE cur;                 
        SET CURSOR_CLOSE_ON_COMMIT OFF;
    END TRY
    . . . 

这次循环运行一次,然后释放光标。 。 。好吧,你第二次在循环中遇到问题。

我认为您打算在 while循环之后取消

答案 1 :(得分:0)

光标结束后取消分配并关闭:

DECLARE cur CURSOR LOCAL FOR 
    SELECT * FROM @ordersToProcess;
OPEN cur;
DECLARE @OrderId int;

FETCH NEXT FROM cur INTO @OrderId;
WHILE @@FETCH_STATUS = 0 BEGIN
    BEGIN TRY
        BEGIN TRAN;
        EXEC process_order @OrderId;
        COMMIT TRAN;
    END TRY
    BEGIN CATCH
        ROLLBACK TRAN;
        THROW;
    END CATCH;  

    FETCH NEXT FROM cur INTO @OrderId;
END;

BEGIN TRY      
    CLOSE Cursor1
    DEALLOCATE Cursor1                                  
END TRY
BEGIN CATCH
 --Do nothing
END CATCH