简体   繁体   中英

Transaction in stored procedure not rolling back

I have stored procedure sp_Insert with 2 options eg. INSERT INTO Table1 and INSERT INTO Table2 .

I have declared 3 variables @choice (which can be 1 , 2 or 3 ), @insertDataToTable1 and @insertDataToTable2 as inputs.

So code structure looks like:

CREATE PROC sp_MyProc
@choice... 
@insertDataToTable1...
@insertDataToTable2...
AS
BEGIN TRAN
IF(@choice = 1 OR @choice = 3) 
BEGIN
   BEGIN TRY
      //my query to insert to Table 1
   END TRY
   BEGIN CATCH
      // print error
      ROLLBACK //should rollback transaction
      RETURN
   END CATCH
END
ELSE IF (@choice = 2 OR @choice = 3)
BEGIN
   BEGIN TRY
      //my query to insert to Table 1
   END TRY
   BEGIN CATCH
      // print error
      ROLLBACK //should rollback transaction
      RETURN
   END CATCH
END
COMMIT

So If @choice = 1 than run only first query (instert to table1), if @choice = 2 run only 2nd query (inster to 2nd table), if @choice = 3 run both 1st and 2nd queries to insert databa to 1st and 2nd table.

PROBLEM:

Everything would be fine, except problem with transaction. Transaction not rolling back if one of blocks fails. I mean If 1st query is succssful (inserted data to table1) and second query fails (for example problems with primary key) It not rolling back, value stay inserted to table1. Where is the problem?

You will never meet both conditions even if you would do @choice = 3 as you have ELSE IF in the second condition. When you make @choice = 3 then the first IF would be true and it will not go to the ELSE. If you want to go to the second part change ELSE IF to just IF.

CREATE TABLE a (a int)
GO

CREATE PROC sp_MyProc
@choice int
AS
BEGIN TRAN
IF(@choice = 1 OR @choice = 3) 
BEGIN
   BEGIN TRY
      INSERT INTO a VALUES (1);
   END TRY
   BEGIN CATCH
      PRINT 'WAS HERE'
      ROLLBACK 
      RETURN
   END CATCH
END
IF (@choice = 2 OR @choice = 3)
BEGIN
   BEGIN TRY
      INSERT INTO a VALUES ('a');
   END TRY
   BEGIN CATCH
      PRINT 'WAS HERE 2'
      ROLLBACK 
      RETURN
   END CATCH
END
COMMIT
GO
EXEC sp_MyProc 3
GO
SELECT * FROM a
GO
DROP TABLE a;
GO
DROP PROC sp_MyProc
GO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM