Saturday, 11 May 2019

MSSQL - Fix Error - The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.

Msg 3902, Level 16, State 1, Line 13
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.



Watch this example on YouTube


To fix it replace ( add IF @@TRANCOUNT > 0)

Declare @Error Varchar(max)
Declare @ID int = 0

BEGIN TRAN
    Insert into ProductHistory (NewName) values ('test')
    IF @ID = 0
    BEGIN
        SET @Error = 'some error'
        ROLLBACK TRAN
    END
    Select * From ProductHistory
COMMIT TRAN

with

Declare @Error Varchar(max)
Declare @ID int = 0

BEGIN TRAN
    Insert into ProductHistory (NewName) values ('test')
    IF @ID = 0
    BEGIN
        SET @Error = 'some error'
        ROLLBACK TRAN
    END
    Select * From ProductHistory
IF @@TRANCOUNT > 0
COMMIT TRAN

No comments:

Post a Comment