Skip to content
Advertisement

How to get stored procedure with transaction to execute if else code block?

I have stored procedure that takes multiple parameters. Based on parameters values either Insert or Edit process will be executed. In each process there are multiple Update/Insert statements (more than one table is updated or inserted). Here is example that I have:

Code above will execute code in both If and Else statement. I’m not sure why, even parameters passed in the SP are this:

I’m not sure if my if/else block statement is correct or there is something else that I missed. Please let me know if you see why the code is failing and executing both statements no matter what parameters are passe in SP.

Advertisement

Answer

If you plan to execute multiple commands for the if and/or else block, you must wrap that set of commands in a BEGIN/END pair, eg:

The BEGIN/END are optional if there is only a single command in the if and/or else block; when in doubt, include the BEGIN/END wrapper.

Also, the @@error variable is (re)set after each command; I’m guessing you want to rollback your transaction if any of the commands error out, which means you’ll need to add some more logic to test @@error after each command; whether you abort after the first error, or at the end of the if/then block is your call.

One other item, if your proc is called within a higher level transaction (eg, you’re running in chained mode), then your rollback transaction will actually rollback all transactions. [Nested transaction management is a whole ‘nother topic.]

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement