How to get actual exception in SQL transaction when xact_abort is ON - sql

How can I preserve/retrieve the error state or return the actual error when using xact_abort ON?
Currently, when I excecute this stored procedure with an outer transaction already initiated.
begin tran
exec TestFK 2
I get this generic error which hides the actual error
The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction.
But when I execute without an external transaction
exec TestFK 2
I get the proper error.
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__t2__a__3B783965". The conflict occurred in database "XXX", table "dbo.t1", column 'a'.
Setup Code
ALTER procedure [dbo].[TestFK]
#Id int
as
begin
SET NOCOUNT ON
SET xact_abort ON
DECLARE #trancount INT
SET #trancount = ##TRANCOUNT
begin try
IF #trancount = 0
BEGIN TRANSACTION
INSERT INTO t2 VALUES (#Id); -- Foreign key error for #Id = 2
IF #trancount = 0
COMMIT TRANSACTION
end try
begin catch
IF Xact_state() <> 0 AND #trancount = 0
ROLLBACK TRANSACTION
Exec uspInsErrorInfo -- Here I want to preserve the Error State somehow
end catch
END
CREATE TABLE t1 (a INT NOT NULL PRIMARY KEY);
CREATE TABLE t2 (a INT NOT NULL REFERENCES t1(a));
INSERT INTO t1 VALUES (1);
INSERT INTO t1 VALUES (3);
INSERT INTO t1 VALUES (4);
INSERT INTO t1 VALUES (6);

So, the solution I used was to simply remove the try/catch block in this scenario.
Since,
When SET XACT_ABORT is ON, if a Transact-SQL statement raises a
run-time error, the entire transaction is terminated and rolled back.
ALTER procedure [dbo].[TestFK]
#Id int
as
begin
SET NOCOUNT ON
SET xact_abort ON
DECLARE #trancount INT
SET #trancount = ##TRANCOUNT
IF #trancount = 0
BEGIN TRANSACTION
INSERT INTO t2 VALUES (#Id); -- Foreign key error for #Id = 2
-- + some other statements
IF #trancount = 0
COMMIT TRANSACTION
END

Related

Nested transactions and ##trancount count (issue with the practice question for 70-761)

Got a practice question from Measure up and not sure if it is badly worded or I'm missing something regarding nested transactions.
Basically gives me a definition of a stored procedure and states
When the sp is run, what is the value of ##trancount?
I get that SQL Server only cares about the outer transaction but ##trancount should be 0 since everything is committed and if it fails everything is rolled back which would still be 0 but it is telling me it should be 1.
It doesn't specify in the code where the ##trancount is run but the wording suggest it is run after the sp is executed.
I ran the sp with some dummy data with ##trancount at the end and got 0.
Create Procedure dbo.up_CreateSalesInvoice
(
#Date date,
#customerID int,
#stockItemID Int,
#quantity int,
#unitPrice decimal(8,2),
#invoiceID int out
)
As
Begin
Declare #retval int;
Begin Transaction;
Begin Try
Begin Transaction;
Insert into dbo.SalesInvoice (invoiceDate, CustomerID)
Values (#date, #customerID);
Set #invoiceID = Scope_identity();
Commit Transaction;
Begin Transaction;
Insert into dbo.SalesInvoiceLine (InvoiceID, StockItemID, Quantity,
UnitPrice)
Values (#InvoiceID, #stockItemID, #quantity, #UnitPrice);
Commit Transaction;
Commit transaction;
set #retval = 0;
End try
Begin catch
Rollback Transaction;
Set #retval = 1;
End catch
Return #retval;
End ;
Expect ##trancount to be 0 as there are no open transactions for it to count.

Create SQL Server procedure in a transaction

I need to create two procedures in a SQL Server transaction. If failure, I need to rollback the create(s) and any other executed queries in this transaction. I know the create statement must be the first statement in query batch, but I need to know how handle the transaction with multiple batches.
BEGIN TRANSACTION
CREATE PROCEDURE [dbo].[SP_SP-1]
#id BIGINT
AS
BEGIN
SET NOCOUNT ON;
-- SQL statements
END
GO
CREATE PROCEDURE [dbo].[SP_SP-2]
#id BIGINT
AS
BEGIN
SET NOCOUNT ON;
-- SP-2 statements
END
GO
UPDATE Table
SET Value = '1.0.0.5'
COMMIT TRANSACTION / ROLLBACK TRANSACTION
Below is one method to execute multiple batches in a transaction. This uses a temp table to indicate if any batch erred and perform a final COMMIT or ROLLLBACK accordingly.
Another method is to encapsulate statements that must be in single-statement batch (CREATE PROCEDURE, CREATE VIEW, etc.) but that can get rather ugly when quotes within the literal text must be escaped.
CREATE TABLE #errors (error varchar(5));
GO
BEGIN TRANSACTION
GO
CREATE PROCEDURE [dbo].[USP_SP-1]
#id bigint
AS
BEGIN
SET NOCOUNT ON;
-- SP Statments
END;
GO
IF ##ERROR <> 0 INSERT INTO #errors VALUES('error');
GO
CREATE PROCEDURE [dbo].[USP_SP-2]
#id BIGINT
AS
BEGIN
SET NOCOUNT ON;
-- SP-2 Statments
END;
GO
IF ##ERROR <> 0 INSERT INTO #errors VALUES('error');
GO
UPDATE Table SET Value='1.0.0.5'
GO
IF ##ERROR <> 0 INSERT INTO #errors VALUES('error');
GO
IF EXISTS(SELECT 1 FROM #errors)
BEGIN
IF ##TRANCOUNT > 0 ROLLBACK;
END
ELSE
BEGIN
IF ##TRANCOUNT > 0 COMMIT;
END;
GO
IF OBJECT_ID(N'tempdb..#errors', 'U') IS NOT NULL
DROP TABLE #errors;
GO
I suggest you to study more about this subject in Handling Transactions in Nested SQL Server Stored Procedures.
From the beginning, your syntax is wrong. You cannot begin a transaction and then create a procedure, you need to do just the opposite:
CREATE PROCEDURE [dbo].[SP_SP-1]
#id bigint
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION
SET NOCOUNT ON;
-- SP-2 Statments
Update Table set Value='1.0.0.5'
END TRY
BEGIN CATCH
--handle error and perform rollback
ROLLBACK
SELECT ERROR_NUMBER() AS ErrorNumber
SELECT ERROR_MESSAGE() AS ErrorMessage
END CATCH
END
It is best practice to use TRY and CATCH when attempting to perform update inside transaction scope.
Please read more and investigate using the link I provided to get a bigger picture.
To use Transaction, you need to know what is the meaning of transaction. It's meaning of 'Unit of work either in commit state or rollback state'.
So when you use transaction, you must know that where you declare and where you close. So you must start and end transaction in the parent procedure only than it will work as a unit of work i.e. whatever no of query execute of DML statement, it uses the same transaction.
I do not understand why your update statement outside of procedure and transaction portion too.
It should be (See my comments, you can use TRY Catch same as c sharp) :
Create PROCEDURE [dbo].[SP_SP-1]
#id bigint
AS
BEGIN
Begin Transaction
SET NOCOUNT ON;
-- SP Statments
Exec SP_SP-2 #id --here you can pass the parameter to another procedure, but do not use transaction in another procedure, other wise it will create another transaction
If ##Error > 0 than
Rollback
Else
Commit
End
END
GO
--Do not use transaction in another procedure, otherwise, it will create another transaction which has own rollback and commit and do not participate in the parent transaction
Create PROCEDURE [dbo].[SP_SP-2]
#id BIGINT
AS
BEGIN
SET NOCOUNT ON;
-- SP-2 Statments
END
GO
i find this solution to execute the procedure as string execution , it`s a workaround to execute what i want
Begin Try
Begin Transaction
EXEC ('
Create PROCEDURE [dbo].[SP_1]
#id bigint
AS
BEGIN
SET NOCOUNT ON;
SP-1
END
GO
Create PROCEDURE [dbo].[SP_Inc_Discovery_RunDoc]
#id bigint
AS
BEGIN
SET NOCOUNT ON;
Sp-2
END')
Update Table set Value='1.0.0.5'
Commit
End Try
Begin Catch
Rollback
Declare #Msg nvarchar(max)
Select #Msg=Error_Message();
RaisError('Error Occured: %s', 20, 101,#Msg) With Log;
End Catch

How to automatically rollback all “batches” in a (SSMS) SQL script that fails

I have SQL scripts that will be executed via the SQL Server Management Studio on a SQL Server 2012 database. The scripts are divided into a number of batches using the GO statement. If any update in any batch goes wrong I would like everything to be rolled backed.
I have tried to use XACT_ABORT ON, but it did not work as I expected:
begin transaction txn
go
set xact_abort on
go
insert into Table1 (Col1) values (1)
go
insert into Table1 (Col1) values (2/0)
go
insert into Table1 (Col1) values (3)
go
create procedure Proc1
as
begin
select * from Table1
end
go
commit transaction txn
go
When running this script, insert #2 fails and insert #1 is rolled back. However, insert #3 is successful and the stored procedure is created.
Is there a way to make it so that all inserts fails if one fails?
Please note that my actual script potentially could contain hundreds of batches with hundreds of different kinds of updates (insert, update, alter, drop etc.) within some. I would thus prefer not having to add any additional code to the batches, i.e. I would like to wrap them all in one big transaction.
Any suggestions appreciated.
Here is how I would do this using TRY/CATCH blocks. You can read more about that here. https://msdn.microsoft.com/en-us/library/ms175976.aspx
begin transaction
begin try
insert into Table1 (Col1) values (1);
insert into Table1 (Col1) values (2/0);
insert into Table1 (Col1) values (3);
commit transaction;
end try
begin catch
select ERROR_NUMBER() AS ErrorNumber
, ERROR_MESSAGE() AS ErrorMessage;
rollback transaction;
end catch;
This is how I do it, it's not going to be as simple as you think but it works for me.
One of the first things I do in my script is this:
IF (SELECT OBJECT_ID('tempdb..#tmpErrors')) IS NOT NULL DROP TABLE #tmpErrors
GO
CREATE TABLE #tmpErrors (Error int)
GO
SET XACT_ABORT ON
GO
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
GO
BEGIN TRANSACTION
GO
Then do your insert/updates. After every operation do this:
GO
IF ##ERROR <> 0 AND ##TRANCOUNT > 0 BEGIN ROLLBACK;END
IF ##TRANCOUNT = 0 BEGIN INSERT INTO #tmpErrors (Error) VALUES (1); BEGIN TRANSACTION;END
GO
And at the very end of your script add this:
GO
IF EXISTS (SELECT * FROM #tmpErrors) ROLLBACK TRANSACTION
GO
IF ##TRANCOUNT>0 BEGIN
PRINT N'The transacted portion of the database update succeeded.'
COMMIT TRANSACTION
END
ELSE PRINT N'The transacted portion of the database update failed.'
GO
DROP TABLE #tmpErrors
GO
Applying all this to the script you are trying to run will be something like this:
-- this on top
IF (SELECT OBJECT_ID('tempdb..#tmpErrors')) IS NOT NULL DROP TABLE #tmpErrors
GO
CREATE TABLE #tmpErrors (Error int)
GO
SET XACT_ABORT ON
GO
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
GO
BEGIN TRANSACTION
GO
insert into Table1 (Col1) values (1)
GO
IF ##ERROR <> 0 AND ##TRANCOUNT > 0 BEGIN ROLLBACK;END
IF ##TRANCOUNT = 0 BEGIN INSERT INTO #tmpErrors (Error) VALUES (1); BEGIN TRANSACTION;END
GO
insert into Table1 (Col1) values (2/0)
GO
IF ##ERROR <> 0 AND ##TRANCOUNT > 0 BEGIN ROLLBACK;END
IF ##TRANCOUNT = 0 BEGIN INSERT INTO #tmpErrors (Error) VALUES (1); BEGIN TRANSACTION;END
GO
insert into Table1 (Col1) values (3)
GO
IF ##ERROR <> 0 AND ##TRANCOUNT > 0 BEGIN ROLLBACK;END
IF ##TRANCOUNT = 0 BEGIN INSERT INTO #tmpErrors (Error) VALUES (1); BEGIN TRANSACTION;END
GO
-- this at the end
GO
IF EXISTS (SELECT * FROM #tmpErrors) ROLLBACK TRANSACTION
GO
IF ##TRANCOUNT>0 BEGIN
PRINT N'The transacted portion of the database update succeeded.'
COMMIT TRANSACTION
END
ELSE PRINT N'The transacted portion of the database update failed.'
GO
DROP TABLE #tmpErrors
GO

How to log errors even if the transaction is rolled back?

Lets say we have following commands:
SET XACT_ABORT OFF;
SET IMPLICIT_TRANSACTIONS OFF
DECLARE #index int
SET #index = 4;
DECLARE #errorCount int
SET #errorCount = 0;
BEGIN TRANSACTION
WHILE #index > 0
BEGIN
SAVE TRANSACTION Foo;
BEGIN TRY
-- commands to execute...
INSERT INTO AppDb.dbo.Customers VALUES('Jalal', '1990-03-02');
-- make a problem
IF #index = 3
INSERT INTO AppDb.dbo.Customers VALUES('Jalal', '9999-99-99');
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION Foo; -- I want to keep track of previous logs but not works! :(
INSERT INTO AppDb.dbo.LogScripts VALUES(NULL, 'error', 'Customers', suser_name());
SET #errorCount = #errorCount + 1;
END CATCH
SET #index = #index - 1;
END
IF #errorCount > 0
ROLLBACK TRANSACTION
ELSE
COMMIT TRANSACTION
I want to execute a batch, keep all errors in log and then, if no error was occurred, commit all changes. How can implement it in Sql Server?
The transaction is tied to the connection, and as such, all writes will be rolled back on the outer ROLLBACK TRANSACTION (irrespective of the nested savepoints).
What you can do is log the errors to an in-memory structure, like a Table Variable, and then, after committing / rolling back the outer transaction, you can then insert the logs collected.
I've simplified your Logs and Customers tables for the purpose of brevity:
CREATE TABLE [dbo].[Logs](
[Description] [nvarchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
CREATE TABLE [dbo].[Customers](
[ID] [int] NOT NULL,
[Name] [nvarchar](50) NULL
);
GO
And then you can track the logs in the table variable:
SET XACT_ABORT OFF;
SET IMPLICIT_TRANSACTIONS OFF
GO
DECLARE #index int;
SET #index = 4;
DECLARE #errorCount int
SET #errorCount = 0;
-- In memory storage to accumulate logs, outside of the transaction
DECLARE #TempLogs AS TABLE (Description NVARCHAR(MAX));
BEGIN TRANSACTION
WHILE #index > 0
BEGIN
-- SAVE TRANSACTION Foo; As per commentary below, savepoint is futile here
BEGIN TRY
-- commands to execute...
INSERT INTO Customers VALUES(1, 'Jalal');
-- make a problem
IF #index = 3
INSERT INTO Customers VALUES(NULL, 'Broken');
END TRY
BEGIN CATCH
-- ROLLBACK TRANSACTION Foo; -- Would roll back to the savepoint
INSERT INTO #TempLogs(Description)
VALUES ('Something bad happened on index ' + CAST(#index AS VARCHAR(50)));
SET #errorCount = #errorCount + 1;
END CATCH
SET #index = #index - 1;
END
IF #errorCount > 0
ROLLBACK TRANSACTION
ELSE
COMMIT TRANSACTION
-- Finally, do the actual insertion of logs, outside the boundaries of the transaction.
INSERT INTO dbo.Logs(Description)
SELECT Description FROM #TempLogs;
One thing to note is that this is quite an expensive way to process data (i.e. attempt to insert all data, and then roll back a batch if there were any problems encountered). An alternative here would be to validate all the data (and return and report errors) before attempting to insert any data.
Also, in the example above, the Savepoint serves no real purpose, as even 'successful' Customer inserts will be eventually rolled back if any errors were detected for the batch.
SqlFiddle here - The loop is completed, and despite 3 customers being inserted, the ROLLBACK TRANSACTION removes all successfully inserted customers. However, the log is still written, as the Table Variable is not subjected to the outer transaction.

MSSQL Prevent rollback when trigger fails

I have an after insert/update/delete trigger, which inserts a new record in an AuditTable every time an insert/update/delete is made to a specific table. If the insertion in the AuditTable fails I'd like the first record to be inserted anyway and the error logged in a further table "AuditErrors".
This is what I have so far and I tried many different things but I can't get this to work if the trigger insert into the AuditTable fails (I test this by misspelling the name of a column in the AuditTable insert). NB: #sql is the insert into the AuditTable.
DECLARE #TranCounter INT
SET #TranCounter = ##TRANCOUNT
IF #TranCounter > 0
SAVE TRANSACTION AuditInsert;
ELSE
BEGIN TRANSACTION;
BEGIN TRY
EXEC (#sql)
IF #TranCounter = 0
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- roll back
IF #TranCounter = 0
ROLLBACK TRANSACTION;
ELSE
IF XACT_STATE() <> -1
ROLLBACK TRANSACTION AuditInsert;
-- insert error into database
IF #TranCounter > 0
SAVE TRANSACTION AuditInsert;
ELSE
BEGIN TRANSACTION;
BEGIN TRY
INSERT INTO [dbo].[AuditErrors] ([AuditErrorCode], [AuditErrorMsg]) VALUES (ERROR_NUMBER(), ERROR_MESSAGE())
IF #TranCounter = 0
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
-- roll back
IF #TranCounter = 0
ROLLBACK TRANSACTION;
ELSE
IF XACT_STATE() <> -1
ROLLBACK TRANSACTION AuditInsert;
END CATCH
END CATCH
This is the only way I know of separating the original transaction from the trigger action. In this example the original insert completes even though the audit insert fails. Tested on 2008R2.
It's not pretty but it won't rollback the transaction!
It worked just fine with trusted authentication:
create table TestTable(
ID int identity(1,1) not null
,Info varchar(50) not null
)
GO
create table AuditTable(
AuditID int identity(1,1) not null
,TestTableID int not null
,Info varchar(10) -- The failure is the mismatch in length
)
GO
create procedure insertAudit #id int, #Info varchar(50)
as
set nocount on;
begin try
insert into AuditTable(TestTableID,Info)
values(#id,#Info);
end try
begin catch
select 0
end catch;
GO
create trigger trg_TestTable on TestTable
AFTER INSERT
as
begin
set nocount on;
declare #id int,
#info varchar(50),
#cmd varchar(500),
#rc int;
select #id=ID,#info=Info from inserted;
select #cmd = 'osql -S '+##SERVERNAME+' -E -d '+DB_NAME()+' -Q "exec insertAudit #id='+cast(#id as varchar(20))+',#Info='''+#info+'''"';
begin try
exec #rc=sys.xp_cmdshell #cmd
select #rc;
end try
begin catch
select 0;
end catch;
end
GO
Drop the Audit table and it still completes the original transaction.
Cheers!
Instead of using sqlcmd, you may consider playing with BEGIN TRAN/ROLLBACK a little bit.
Note that, even tho a rollback command will undo every change made since the start of the statement which caused the trigger to fire, any changes made by subsequent commands will not.
All you have to do is to repeat the execution of the code in #sql if the transaction in which data is inserted in the audit table gets rolled back:
TRIGGER BEGINS
<INSERT INSERTED AND DELETED TABLES INTO TABLE VARIABLES, U'LL NEED THEM>
BEGIN TRY
BEGIN TRAN
INSERT INTO AUDITTABLE SELECT * FROM #INSERTED
COMMIT
END TRY
BEGIN CATCH
ROLLBACK
REDO ORIGINAL INSERT/UPDATE/DELETE USING TRIGGER TABLE VARIABLES (#INSERTED AND #DELETED)
INSERT INTO AUDITERROS...
END CATCH
BEGIN TRAN -- THIS IS TO FOOL SQL INTO THINKING THERE'S STILL A TRANSACTION OPEN
TRIGGER ENDS