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?

Answers


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

Need Your Help

Loading Chosen.jquery.js file in html file does not work

javascript jquery html css jquery-chosen

I am trying to load chosen.jquery.js file in my html/css file to achieve searchable dropdown but it doesnt seem to work. I downloaded the chosen.js plugin from http://harvesthq.github.io/chosen/. A...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.