Multiple batches in a SQL transaction - sql

I want to create several stored procedures (or user-defined functions) within a transaction. CREATE PROCEDURE statement must be the only statement in the batch, so I have to use following template:
BEGIN TRANSACTION MyTransaction
USE MyDatabase
GO
CREATE PROCEDURE A
AS
-- The body of procedure A
GO
CREATE PROCEDURE B
AS
-- The body of procedure B
GO
CREATE PROCEDURE C
AS
-- The body of procedure C
GO
COMMIT TRANSACTION MyTransaction
The problem appears if an error occurs within one of the batches. For example, if error occurs while procedure B is creating, MyTransaction with procedures A and B will be rolled back. But the script will continue to run. So, the procedure C will be created.
Also it's not possible to skip the statement using GOTO and ##error counter checking, because it cannot go to a label outside the batch in which GOTO is placed.
How to prevent any database changes if an error occurs?

You can try to do something like this with SET XACT_ABORT ON.
IF EXISTS (SELECT * FROM tempdb..sysobjects WHERE id=OBJECT_ID('tempdb..#tmpErrors')) DROP TABLE #tmpErrors
GO
CREATE TABLE #tmpErrors (Error int)
GO
SET XACT_ABORT ON
GO
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
GO
BEGIN TRANSACTION
GO
PRINT N'Creating [Proc A]'
GO
-------------------------------------------------------------------------
CREATE PROCEDURE A
AS
-- The body of procedure A
GO
-------------------------------------------------------------------------
IF ##ERROR<>0 AND ##TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF ##TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
PRINT N'Creating [Proc B]'
GO
-------------------------------------------------------------------------
CREATE PROCEDURE B
AS
-- The body of procedure B
GO
-------------------------------------------------------------------------
IF ##ERROR<>0 AND ##TRANCOUNT>0 ROLLBACK TRANSACTION
GO
IF ##TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
GO
IF EXISTS (SELECT * FROM #tmpErrors) ROLLBACK TRANSACTION
GO
IF ##TRANCOUNT>0 BEGIN
PRINT 'The database update succeeded'
COMMIT TRANSACTION
END
ELSE PRINT 'The database update failed'
GO
DROP TABLE #tmpErrors
GO

Related

SQL Server transaction with custom template

I would ask a basilar thing, I would use the native transaction stuffs to rollback a bunch of tables if some conditions are verified.
I really have to check how many updates results based of some stored procedure that gather data from tables populated by input reports, too less changes or too many changes means rollback because we will reject the reports. I would implements this feature with the native transaction of T-SQL, this is a pseudo of my idea:
CREATE PROCEDURE mytest
AS
BEGIN
BEGIN TRANSACTION
BEGIN TRY
EXEC foo
EXEC bar
EXEC baz
END TRY
IF true
COMMIT TRANSACTION
ELSE
ROLLBACK TRANSACTION
END
Of course, this is not working because of incorrect syntax near the keyword 'IF', maybe because it's not the right way to use transaction.
Fixed this I will think how to count the changes of a table, if need to use a temporary table or if I can use some SQL features. I'm search for docs or example but I'm, not finding anything.
Any hints?
Your pseudo-code is missing a catch block. Below is an example that includes the error handling and other improvements.
CREATE PROCEDURE mytest
AS
SET XACT_ABORT ON; --best practice with explict transactions in procs
BEGIN TRY
BEGIN TRAN;
EXEC foo;
EXEC bar;
EXEC baz;
IF (<your-validation-succeeded-condition-here>)
COMMIT;
ELSE
ROLLBACK;
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0 ROLLBACK;
THROW;
END CATCH;
The problem, as I mention in the comment, isn't the IF...ELSE it's that you have no CATCH. A TRY...CATCH requires both a TRY and a CATCH; unlike an IF...ELSE which can only have an IF.
You likely, therefore, want something like this:
CREATE PROCEDURE dbo.MyTest AS
BEGIN
SET NOCOUNT ON;
BEGIN TRANSACTION MyTransaction;
BEGIN TRY
EXEC FOO;
EXEC BAR;
EXEC BAZ;
IF {Your Boolean Expression}
COMMIT TRANSACTION MyTransaction;
ELSE
ROLLBACK TRANSACTION MyTransaction;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION MyTransaction;
THROW;
END CATCH;
END;

Write stored procedure so if one statement fails it should not effect the other?

I have this procedure which basically insert data.
Begin Transaction
Insert into [dbo].Values
(
EQ
)
values
(
#EQ
)
End
--Set #STATUSRet= 'Created'
--Set #ErrorRet= ''
Commit Transaction
End Try
Begin Catch
Set #STATUSRet= 'Failed'
Set #ErrorRet= (Select ERROR_MESSAGE())
Rollback Transaction
End Catch
Now I want to add a piece of code that calls another database server and insert data into the table in that server i.e. remotely. That's ok I will do that but if that fails then that should not effect my current process of inserting the data as I have described above i.e. if the remote data insertion fails it should not effect the prior insert in any way and should return successfully to the calling application behaving like nothing happened.
The default method of controlling transactions is auto-commit:
Any single statement that changes data and executes by itself is
automatically an atomic transaction. Whether the change affects one
row or thousands of rows, it must complete successfully for each row
to be committed. You cannot manually rollback an auto-commit
transaction.
So, if the two inserts are not wrapped in explicit transaction this will be the behavior. If you have more code blocks, then you can use two separate explicit transactions blocks like this:
DECLARE #ExecuteSecondTransaction BIT = 0;
-- local database
BEGIN TRY
BEGIN TRANSACTION;
-- CODE BLOCK GOES HERE
SET #ExecuteSecondTransaction = 1;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION
END;
-- GET ERRORS DETAILS OR THROW ERROR
END CATCH;
-- remote database
IF #ExecuteSecondTransaction = 1
BEGIN
BEGIN TRY
BEGIN TRANSACTION;
-- CODE BLOCK GOES HERE
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF ##TRANCOUNT > 0
BEGIN
ROLLBACK TRANSACTION
END;
-- GET ERRORS DETAILS OR THROW ERROR
END CATCH;
END;

How to handle Transaction in Nested procedure in SQL server?

I have 2 proc i.e. Proc1 and Proc2.
I am executing proc1 inside proc2. There are multiple DML operation in both procedure. output of proc1 is used in proc2 for DML operation.
if Error occurred in proc2 then
how to handle transaction in both proc for rollback all DML operation?
Should I write transaction in both proc?
We use a generic error handler procedure based on http://www.sommarskog.se/error_handling/Part1.html that we - when applicable - include in our (nested) transactions to ensure the chain is managed properly:
CREATE PROCEDURE [dbo].[sp_ErrorHandler](#caller VARCHAR(255))
AS BEGIN
SET NOCOUNT ON;
DECLARE #errmsg NVARCHAR(2048), #severity TINYINT, #state TINYINT, #errno INT, #lineno INT;
SELECT #errmsg=REPLACE(ERROR_MESSAGE(), 'DatabaseException: ', 'DatabaseException: '+QUOTENAME(#caller)+' --> ')
, #severity=ERROR_SEVERITY()
, #state=ERROR_STATE()
, #errno=ERROR_NUMBER()
, #lineno=ERROR_LINE();
IF #errmsg NOT LIKE 'DatabaseException%' BEGIN
SELECT #errmsg=N'DatabaseException: '+QUOTENAME(#caller)+N', Line '+LTRIM(STR(#lineno))+N', Error '+LTRIM(STR(#errno))+N': '+#errmsg;
END;
RAISERROR('%s', #severity, #state, #errmsg);
END;
(Compiled in the master database and marked as system procedure)
We use this error handler as follows. In the demo I have an outer proc and an inner proc both using a transaction.
CREATE PROCEDURE dbo.uspOuterProc
AS
BEGIN
SET NOCOUNT, XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
EXEC dbo.uspInnerProc;
PRINT 1;
COMMIT;
END TRY
BEGIN CATCH
IF ##trancount > 0
ROLLBACK TRANSACTION;
EXEC master.dbo.sp_ErrorHandler #caller = 'dbo.uspOuterProc';
END CATCH;
END;
GO
CREATE PROCEDURE dbo.uspInnerProc
AS
BEGIN
SET NOCOUNT, XACT_ABORT ON;
BEGIN TRY
BEGIN TRANSACTION;
PRINT 2;
SELECT 1 / 0;
PRINT 3;
COMMIT;
END TRY
BEGIN CATCH
IF ##trancount > 0
ROLLBACK TRANSACTION;
EXEC master.dbo.sp_ErrorHandler #caller = 'dbo.uspInnerProc';
END CATCH;
END;
GO
After you compile this and run:
EXEC dbo.uspOuterProc
You should get this result:
2
Msg 50000, Level 16, State 1, Procedure sp_ErrorHandler, Line 13 [Batch Start Line 48]
DatabaseException: [dbo.uspOuterProc] --> [dbo.uspInnerProc], Line 12, Error 8134: Divide by zero error encountered.
You can handle the transaction in the outer procedure ( in your case proc2). If any error will be occurred in proc1 it will be taken care of by proc2 transaction handler.
Am assuming that proc1 will not be called directly, it will be called inside the proc2.
There are 3 basic transaction handling statements (and a few advanced ones I'm not gonna mention):
BEGIN TRANSACTION: Will raise the ##TRANCOUNT session variable by 1. If it goes from 0 to 1 then this marks the start of a transaction. Any value higher than 1 will keep the same transaction ongoing.
COMMIT: Will lower the ##TRANCOUNT session variable by 1. If it goes from 1 to 0 then the transaction is marked as finished and will impact all changes done since it was first created.
ROLLBACK: Will decrease the ##TRANCOUNT session variable to 0 (whichever it's value was), as long as it was at least 1 or higher. This will close the transaction and revert all changes done since it was first created.
Nested transactions are a bunch of BEGIN TRANSACTION statements put together. The only point where the transaction gets fully commited and the changes are made permanent is when there is a COMMIT that lowers the transaction count from 1 to 0. That means you need one COMMIT for each BEGIN TRANSACTION you executed, like a pyramid.
Check the following example:
BEGIN TRANSACTION
SELECT ##TRANCOUNT -- 1
BEGIN TRANSACTION
SELECT ##TRANCOUNT -- 2
COMMIT TRANSACTION
SELECT ##TRANCOUNT -- 1 (no change is permanent yet, not even the last one)
BEGIN TRANSACTION
SELECT ##TRANCOUNT -- 2
ROLLBACK
SELECT ##TRANCOUNT -- 0 (all changes were discarded)
When you have an SP that executes another SP and both have their transactions, the only thing you need to care about is to CATCH errors and do the proper ROLLBACK IF there's an open/active transaction ongoing (if not the ROLLBACK statement will fail saying that there is nothing to rollback).
A very basic CATCH would be like the following:
BEGIN TRY
BEGIN TRANSACTION
/* Do some operations */
/* Execute another SP that might have the following:
BEGIN TRANSACTION
-- Some other operations
COMMIT
*/
COMMIT
END TRY
BEGIN CATCH
DECLARE #v_ErrorMessage VARCHAR(MAX) = ERROR_MESSAGE()
IF ##TRANCOUNT > 0 -- Only rollback if there is an active transaction
ROLLBACK
RAISERROR (#v_ErrorMessage, 16, 1)
END CATCH
You can read this post if you want to delve deeply into the best way for handling transactions on SQL Server.

Stored Procedure: only commit when successful

I would like to build a stored procedure that:
1. truncates Table A
2. truncates Table B
3. inserts (lots) of rows in table A
4. inserts (lots) of rows in table B
The stored procedure should only commit the statements after step 4 so that the tables are not locked and experience no down time.
If an error occurs (for instance in step 4) all changes must be rolled back. I tried writing it myself but it committed after each statement.
create or replace PROCEDURE upall as
BEGIN
execute immediate 'truncate table MAIN.SET';
insert into MAIN.SET select * from MAIN.SET_STAG;
execute immediate 'truncate table MAIN.TYPE';
insert into MAIN.TYPE select * from MAIN.TYPE_STAG;
COMMIT;
EXCEPTION WHEN OTHERS THEN
ROLLBACK;
RAISE;
END;
In Oracle, TRUNCATE TABLE is a DDL statement that cannot be used in a transaction (or, more accurately, cannot be rolled back).If there is a transaction in progress when the statement is executed, the transaction is committed and then the TRUNCATE is executed and cannot be undone.
Try DELETE FROM YourTable and finally update stats of your table (since DELETE will outdate it)
It will looks like :
CREATE or REPLACE PROCEDURE upall as
BEGIN
delete from MAIN.SET;
insert into MAIN.SET select * from MAIN.SET_STAG;
delete from MAIN.TYPE;
insert into MAIN.TYPE select * from MAIN.TYPE_STAG;
COMMIT;
EXEC DBMS_STATS.GATHER_TABLE_STATS ('MAIN', 'SET');
EXEC DBMS_STATS.GATHER_TABLE_STATS ('MAIN', 'TYPE');
EXCEPTION WHEN OTHERS THEN
ROLLBACK;
RAISE;
END;

Nested transaction can't be rolled back

I have SQL Server 2008 and want to do such a transaction:
begin transaction oo;
......
begin try
save transaction xx;
alter table ....; -- this will fail
alter table ....;
alter table ....;
end try
begin catch
rollback transaction xx; -- error here
end catch;
......
commit transaction oo;
At rollback transaction xx;, I get the message
3931 The current transaction cannot be committed and cannot be rolled back to a savepoint. Roll back the entire transaction.
What am I doing wrong here?
Update To explain the scenario:
There is a big transaction "oo", which will change the table structures of the database from product version X to product version Y.
In the nested transactions, user-specific-tables should be tried to be changed (= inner transaction).
If an user-specific-table is somehow corrupted, the whole product-upgrade process should not be rolled back.
On the other hand, the user-specific-tables should not be upgraded if something else failed during the main product table upgrade (outer transaction).
Reference
you have to use this line inside CATCH block
ROLLBACK TRANSACTION;
which will rollback all transaction,
when you use this one in your above statement (posted in Q) then it will
give us error
The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
for it you have to put this line in TRY block
COMMIT TRANSACTION oo;
then finally your statement like that
BEGIN TRANSACTION oo;
BEGIN TRY
SAVE TRANSACTION xx;
CREATE TABLE test (ID INT); -- this will fail from second time
SELECT 3;
COMMIT TRANSACTION oo;
END TRY
BEGIN catch
ROLLBACK TRANSACTION;
END CATCH;
UPDATE after comment
BEGIN TRY
BEGIN TRANSACTION xx1;
select 1; -- this will always success
COMMIT TRANSACTION xx1;
BEGIN TRANSACTION xx2;
CREATE TABLE test (id int); -- this will fail from second time
COMMIT TRANSACTION xx2;
BEGIN TRANSACTION xx3;
select 3; -- this will fail from second time
COMMIT TRANSACTION xx3;
END TRY
BEGIN catch
ROLLBACK TRANSACTION
END CATCH;