T-SQL Nested procedure & transactions

来源:互联网 发布:mysql free result 编辑:程序博客网 时间:2024/05/16 01:49
 IF OBJECT_ID('sp_ThrowExp') IS NOT NULL
    DROP PROC sp_ThrowExp
GO

CREATE PROC sp_ThrowExp
AS
    RAISERROR('Error occurs.', 16, 1)
GO

IF OBJECT_ID('sp_OuterProc') IS NOT NULL
    DROP PROC sp_OuterProc
GO

CREATE PROC sp_OuterProc
AS
BEGIN TRAN
BEGIN TRY
    --db operations
    INSERT Customer SELECT 3, 'exxx', 7

    PRINT 'Before throw'
    EXEC sp_ThrowExp
    PRINT 'After throw'
END TRY
BEGIN CATCH
    PRINT 'Catch exp'
    IF @@TRANCOUNT > 0
    BEGIN
        ROLLBACK TRAN
        PRINT 'Roll back tran'
        RETURN
    END
END CATCH

PRINT 'Outside try/catch'
IF @@TRANCOUNT > 0
BEGIN
    COMMIT TRAN
    PRINT 'Commit tran'
END
GO

EXEC sp_OuterProc

/* OUTPUT

(1 row(s) affected)
Before throw
Catch exp
Roll back tran

*/