I wrote a very simple procedure. I am deliberately making a mistake in the procedure. but the error is not working. I want to return the error I want with raiserror. but it doesn't even go inside the "if".
ALTER PROCEDURE dene
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO bddksektor ([tcmbkodu], [aktif], [bddksektorkodu])
VALUES ('a', 1, 1)
-- I knowingly made a mistake. normally the 1st parameter is int.
-- I'm entering varchar so that it can enter "if" and return an error. but it doesn't
IF ##ERROR <> 0
BEGIN
RAISERROR('Hata', 16, 1, 61106)
RETURN 61106
END
ELSE
BEGIN
SELECT
[tcmbkodu], [aktif], [bddksektorkodu]
FROM
[dbfactoringtest].[dbo].[bddksektor]
ORDER BY
tcmbkodu ASC
END
SET NOCOUNT OFF
END
SQL Server returns its own error when I run the procedure. It does not return the error I wrote because it does not enter the "if"
Error:
Msg 245, Level 16, State 1, Procedure dene, Line 11 [Batch Start Line 1]
Conversion failed when converting the varchar value 'a' to data type int
As I mention in the comment, use a TRY...CATCH. For your SQL if the first INSERT fails the batch will be aborted, and so the IF won't be entered, because it won't be reached. I also recommend switching to THROW instead of RAISERROR as noted in the documentation:
Note
The RAISERROR statement does not honor SET XACT_ABORT. New applications should use THROW instead of RAISERROR.
This gives you something like this:
CREATE OR ALTER PROCEDURE dbo.dene AS --Always schema qualify
BEGIN
SET NOCOUNT ON;
SET XACT_ABORT ON;
BEGIN TRY
INSERT INTO dbo.bddksektor ([tcmbkodu],[aktif],[bddksektorkodu]) --Always schema qualify
VALUES ('a',1,1);
SELECT [tcmbkodu]
,[aktif]
,[bddksektorkodu]
FROM [dbfactoringtest].[dbo].[bddksektor] --Why is this using 3 part naming? Is this copy of bddksektor in a different database?
ORDER BY tcmbkodu ASC;
END TRY
BEGIN CATCH
THROW 61106, N'Hata', 16;
RETURN 61106;
END CATCH;
SET NOCOUNT OFF;
END
Related
I understand there is a regularly quoted answer that is meant to address this question, but I believe there is not enough explanation on that thread to really answer the question.
Why earlier answers are inadequate
The first (and accepted) answer simply says this is a common problem and talks about having only one active insert-exec at a time (which is only the first half of the question asked there and doesn't address the ROLLBACK error). The given workaround is to use a table-valued function - which does not help my scenario where my stored procedure needs to update data before returning a result set.
The second answer talks about using openrowset but notes you cannot dynamically specify argument values for the stored procedure - which does not help my scenario because different users need to call my procedure with different parameters.
The third answer provides something called "the old single hash table approach" but does not explain whether it is addressing part 1 or 2 of the question, nor how it works, nor why.
No answer explains why the database is giving this error in the first place.
My use case / requirements
To give specifics for my scenario (although simplified and generic), I have procedures something like below.
In a nutshell though - the first procedure will return a result set, but before it does so, it updates a status column. Effectively these records represent records that need to be synchronised somewhere, so when you call this procedure the procedure will flag the records as being "in progress" for sync.
The second stored procedure calls that first one. Of course the second stored procedure wants to take those records and perform inserts and updates on some tables - to keep those tables in sync with whatever data was returned from the first procedure. After performing all the updates, the second procedure then calls a third procedure - within a cursor (ie. row by row on all the rows in the result set that was received from the first procedure) - for the purpose of setting the status on the source data to "in sync". That is, one by one it goes back and says "update the sync status on record id 1, to 'in sync'" ... and then record 2, and then record 3, etc.
The issue I'm having is that calling the second procedure results in the error
Msg 50000, Level 16, State 1, Procedure getValuesOuterCall, Line 484 [Batch Start Line 24]
Cannot use the ROLLBACK statement within an INSERT-EXEC statement.
but calling the first procedure directly causes no error.
Procedure 1
-- Purpose here is to return a result set,
-- but for every record in the set we want to set a status flag
-- to another value as well.
alter procedure getValues #username, #password, #target
as
begin
set xact_abort on;
begin try
begin transaction;
declare #tableVariable table (
...
);
update someOtherTable
set something = somethingElse
output
someColumns
into #tableVariable
from someTable
join someOtherTable
join etc
where someCol = #username
and etc
;
select
someCols
from #tableVariable
;
commit;
end try
begin catch
if ##trancount > 0 rollback;
declare #msg nvarchar(2048) = error_message() + ' Error line: ' + CAST(ERROR_LINE() AS nvarchar(100));
raiserror (#msg, 16, 1);
return 55555
end catch
end
Procedure 2
-- Purpose here is to obtain the result set from earlier procedure
-- and then do a bunch of data updates based on the result set.
-- Lastly, for each row in the set, call another procedure which will
-- update that status flag to another value.
alter procedure getValuesOuterCall #username, #password, #target
as
begin
set xact_abort on;
begin try
begin transaction;
declare #anotherTableVariable
insert into #anotherTableVariable
exec getValues #username = 'blah', #password = #somePass, #target = ''
;
with CTE as (
select someCols
from #anotherTableVariable
join someOtherTables, etc;
)
merge anUnrelatedTable as target
using CTE as source
on target.someCol = source.someCol
when matched then update
target.yetAnotherCol = source.yetAnotherCol,
etc
when not matched then
insert (someCols, andMoreCols, etc)
values ((select someSubquery), source.aColumn, source.etc)
;
declare #myLocalVariable int;
declare #mySecondLocalVariable int;
declare lcur_myCursor cursor for
select keyColumn
from #anotherTableVariable
;
open lcur_muCursor;
fetch lcur_myCursor into #myLocalVariable;
while ##fetch_status = 0
begin
select #mySecondLocalVariable = someCol
from someTable
where someOtherCol = #myLocalVariable;
exec thirdStoredProcForSettingStatusValues #id = #mySecondLocalVariable, etc
end
deallocate lcur_myCursor;
commit;
end try
begin catch
if ##trancount > 0 rollback;
declare #msg nvarchar(2048) = error_message() + ' Error line: ' + CAST(ERROR_LINE() AS nvarchar(100));
raiserror (#msg, 16, 1);
return 55555
end catch
end
The parts I don't understand
Firstly, I have no explicit 'rollback' (well, except in the catch block) - so I have to presume that an implicit rollback is causing the issue - but it is difficult to understand where the root of this problem is; I am not even entirely sure which stored procedure is causing the issue.
Secondly, I believe the statements to set xact_abort and begin transaction are required - because in procedure 1 I am updating data before returning the result set. In procedure 2 I am updating data before I call a third procedure to update further data.
Thirdly, I don't think procedure 1 can be converted to a table-valued function because the procedure performs a data update (which would not be allowed in a function?)
Things I have tried
I removed the table variable from procedure 2 and actually created a permanent table to store the results coming back from procedure 1. Before calling procedure 1, procedure 2 would truncate the table. I still got the rollback error.
I replaced the table variable in procedure 1 with a temporary table (ie. single #). I read the articles about how such a table persists for the lifetime of the connection, so within procedure 1 I had drop table if exists... and then create table #.... I still got the rollback error.
Lastly
I still don't understand exactly what is the problem - what is Microsoft struggling to accomplish here? Or what is the scenario that SQL Server cannot accommodate for a requirement that appears to be fairly straightforward: One procedure returns a result set. The calling procedure wants to perform actions based on what's in that result set. If the result set is scoped to the first procedure, then why can't SQL Server just create a temporary copy of the result set within the scope of the second procedure so that it can be acted upon?
Or have I missed it completely and the issue has something to do with the final call to a third procedure, or maybe to do with using try ... catch - for example, perhaps the logic is totally fine but for some reason it is hitting the catch block and the rollback there is the problem (ie. so if I fix the underlying reason leading us to the catch block, all will resolve)?
Question
The documentation of SET XACT_ABORT says little more than this about the effect of enabling this option.
When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.
I do not believe this is the full truth. After reading this, I was worried that if a stored procedure which enables this option is executed in a transaction created by an external process, it may end up rolling back the outer transaction. Luckily, my fears turned out to be unfounded. However, this means now that I do no truly understand how XACT_ABORT works. What are the conditions SQL Server checks for whether a transaction should be rolled back or not?
Prior investigation
I have carried out the following experiment: (a summary of this code is below, as having a numbered list before a code block breaks StackOverflow's formatting, duh)
CREATE TABLE Dummy
(
ID INT NOT NULL IDENTITY CONSTRAINT PK_Dummy PRIMARY KEY,
Text NVARCHAR(128) NOT NULL
)
CREATE UNIQUE NONCLUSTERED INDEX IX_Dummy_Text ON dbo.Dummy(Text)
GO
CREATE OR ALTER PROCEDURE InsertDummy
#Text NVARCHAR(128)
AS
BEGIN
SET NOCOUNT OFF
SET XACT_ABORT ON
INSERT dbo.Dummy (Text) VALUES (#Text)
END
GO
SET XACT_ABORT ON
BEGIN TRANSACTION
BEGIN TRY
EXEC dbo.InsertDummy #Text = N'Dummy'
EXEC dbo.InsertDummy #Text = N'Dummy' --DUPLICATE!
END TRY
BEGIN CATCH
PRINT 'ERROR! ##TRANCOUNT is ' + CONVERT(NVARCHAR, ##TRANCOUNT)
-- Echo the error
DECLARE #ErrorMessage NVARCHAR(4000);
DECLARE #ErrorSeverity INT;
DECLARE #ErrorState INT;
SELECT #ErrorMessage = ERROR_MESSAGE();
SELECT #ErrorSeverity = ERROR_SEVERITY();
SELECT #ErrorState = ERROR_STATE();
RAISERROR (#ErrorMessage, -- Message text.
#ErrorSeverity, -- Severity.
#ErrorState -- State.
);
END CATCH
PRINT 'At the end ##TRANCOUNT is ' + CONVERT(NVARCHAR, ##TRANCOUNT)
IF ##TRANCOUNT>0
ROLLBACK
Create a Dummy table with a UNIQUE index
A stored procedure which inserts into Dummy. The procedures enables XACT_ABORT.
Code which executes this procedure twice, in a transaction. The second call fails, as it attempts to insert a duplicate value into Dummy.
The same code prints out the ##TRANCOUNT value to show if we are still in a transaction or not. It also enables XACT_ABORT.
The output of this test is:
(1 row affected)
(0 rows affected)
ERROR! ##TRANCOUNT is 1
Msg 50000, Level 14, State 1, Line 74
Cannot insert duplicate key row in object 'dbo.Dummy' with unique index 'IX_Dummy_Text'. The duplicate key value is (Dummy).
At the end ##TRANCOUNT is 1
An error was raised yet the the transaction not rolled back. The way this setting works is clearly not as simplistic as the documentation would have me believe. Why was the transaction not rolled back?
This answer mentions that XACT_ABORT only rolls back the transaction if the severity of the error is at least 16. The error in this example is only level 14. However, even if I replace the INSERT in the procedure with RAISERROR (N'Custom error', 16, 0), the transaction is still not rolled back.
UPDATE: What I found that although the transaction is not rolled back in my test, it is doomed! ##TRANCOUNT is 1 when I execute this sample regardless of the XACT_ABORT setting: but if the setting is ON, XACT_STATE() is -1, indicating an uncomittable transaction. When XACT_ABORT is OFF, XACT_STATE() is 1.
Question
"An error was raised yet the transaction not rolled back. The way these setting works is clearly not as simplistic as the documentation would have me believe. Why was the transaction not rolled back"
The answer to that is that RAISERROR will not cause XACT_ABORT to
trigger! This means we can be in a very messed up state transaction
wise
Abort, Abort, We Are XACT_ABORT:ing, Or Are We?!
According to MSDN ,
The THROW statement honors SET XACT_ABORT. RAISERROR does not. New
applications should use THROW instead of RAISERROR.
We can use the THROW statement instead of the RAISERROR.
So we can use the following statement in order to trigger the XACT_ABORT
TRUNCATE TABLE Dummy
GO
SET XACT_ABORT ON
BEGIN TRANSACTION
BEGIN TRY
EXEC dbo.InsertDummy #Text = N'Dummy'
EXEC dbo.InsertDummy #Text = N'Dummy' --DUPLICATE!
END TRY
BEGIN CATCH
THROW
END CATCH
PRINT 'At the end ##TRANCOUNT is ' + CONVERT(NVARCHAR, ##TRANCOUNT)
IF ##TRANCOUNT>0
ROLLBACK
The output will be;
(1 row affected)
(0 rows affected)
Msg 2601, Level 14, State 1, Procedure dbo.InsertDummy, Line 7 [Batch Start Line 5]
Cannot insert duplicate key row in object 'dbo.Dummy' with unique index 'IX_Dummy_Text'. The duplicate key value is (Dummy).
For the updated issue you can see set xact_abort on and try-catch together
We are handling Exceptions in our stored procedures using Try/Catch block. In a stored procedure I have intentionally made an error to check how the exceptions being handled. I wrote a stored procedure like as below,
CREATE PROCEDURE TEST
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRAN
;WITH CTE
AS
(SELECT TOP 10 *
FROM student)
SELECT * FROM CTE
SELECT * INTO #VAL
FROM CTE
IF ##ERROR = 0
BEGIN
COMMIT TRAN;
END
END TRY
BEGIN CATCH
SELECT ##ERROR AS ERROR, ERROR_LINE() AS [Error Line], ERROR_MESSAGE() AS [Error Message]
ROLLBACK TRAN;
END CATCH
SET NOCOUNT OFF;
END
In the Above Stored procedure I have used a CTE multiple Times. I expected that SQL-SERVER will handle the exception but it didn't. While Executing the Above stored Procedure I got below error
Msg 208, Level 16, State 1, Procedure TEST, Line 16
Invalid object name 'CTE'.
Msg 266, Level 16, State 2, Procedure TEST, Line 16
Transaction count after EXECUTE indicates a mismatching number of
BEGIN and COMMIT statements. Previous count = 1, current count = 2.
Why the Exception is not handled ? Could someone give idea on this?
Thanks for the help.
stored procedures follow deferred object name resolution while executing.So in this case cte is a non existent object to it .
Further try catch cannot handle this type of errors
The following types of errors are not handled by a CATCH block when they occur at the same level of execution as the TRY…CATCH construct:
Compile errors, such as syntax errors, that prevent a batch from running.
Errors that occur during statement-level recompilation, such as **object name resolution errors** that occur after compilation because of deferred name resolution
Please see MSDN for more info(see errors unaffected by try catch )
I'm using the SimpleMembershipProvider that you get out of the box when you create an new .NET MVC application and I wanted to allow an admin user the ability to add roles. For learning purposes, (and I don't know if this is the correct way to do it) I wanted to limit the length of the description of the RoleName column to 15 characters, so I wrote the transaction:
create proc spInsertRole
(
#roleName varchar(50)
--really shouldn't be 50, but that's
--how I originally wrote my code
)
as
begin
set nocount on
begin try
begin tran
insert into dbo.webpages_Roles(RoleName)
values (#roleName)
commit transaction
end try
begin catch
select ERROR_MESSAGE() as ErrorMessage
if len(#roleName) > 15
rollback transaction
end catch
end
There is not a check constraint on the table for length of RoleName. This proc will compile but it will also let me add a RoleName of greater than 15 characters. What am I missing and what is the best way to do this?
You should check the length before you run the insert statement. By putting the length check in the catch block, you are telling the program to only check the length and roll back if there is some other error condition.
(My T-SQL is rusty and I don't have a database to test on so please verify before accepting. Also, given these changes, you probably don't need transactions anymore.)
create proc spInsertRole
(
#roleName varchar(50)
--really shouldn't be 50, but that's
--how I originally wrote my code
)
as
begin
set nocount on
begin try
begin tran
-- length check moved here. Raise error when > 15.
-- Severity (argument 2) needs to be higher than 10
-- to stop execution and trigger the catch block.
-- State (argument 3) is an arbitrary value between 0 and 255.
if len(#roleName) > 15
raiserror('Role name is too long.', 11, 5)
insert into dbo.webpages_Roles(RoleName)
values (#roleName)
commit transaction
end try
begin catch
select ERROR_MESSAGE() as ErrorMessage
-- length check was here. program will always roll back now.
rollback transaction
end catch
end
See RAISERROR for more information about how that works.
Below is my procedure in SQL Server 2005
PROCEDURE [dbo].[sp_ProjectBackup_Insert]
#prj_id bigint
AS
BEGIN
DECLARE #MSG varchar(200)
DECLARE #TranName varchar(200)
DECLARE #return_value int
-- 1. Starting the transaction
begin transaction #TranName
-- 2. Insert the records
SET IDENTITY_INSERT [PMS_BACKUP].[Common].[PROJECT] ON INSERT INTO [PMS_BACKUP].[Common].[PROJECT] ([PRJ_ID],[PRJ_NO1],[PRJ_NO2],[PRJ_NO3],[PRJ_DESC],[IS_TASKFORCE],[DATE_CREATED],[IS_APPROVED],[DATE_APPROVED],[IS_HANDEDOVER],[DATE_HANDEDOVER],[DATE_START],[DATE_FINISH],[YEAR_OF_ORDER],[CLIENT_DETAILS],[SCOPE_OF_WORK],[IS_PROPOSAL],[PRJ_MANAGER],[PRJ_NAME],[MANAGER_VALDEL],[MANAGER_CLIENT],[DEPT_ID],[locationid],[cut_off_date]) SELECT * FROM [pms].[Common].[PROJECT] T WHERE T.PRJ_ID = (#prj_id) SET IDENTITY_INSERT [PMS_BACKUP].[Common].[PROJECT] OFF IF ##ERROR <> 0 GOTO HANDLE_ERROR
SET IDENTITY_INSERT [PMS_BACKUP].[Common].[DEPARTMENT_CAP] ON INSERT INTO [PMS_BACKUP].[Common].[DEPARTMENT_CAP] ([CAP_ID],[DEPT_ID],[PRJ_ID],[IS_CAPPED],[DATE_CAPPED],[CAPPED_BY],[CAP_APPROVED_BY],[STATUS],[UNCAPPED_BY],[DATE_UNCAPPED],[DESCRIPTION],[UNCAP_APPROVED_BY],[LOCATIONID]) SELECT * FROM [pms].[Common].[DEPARTMENT_CAP] T WHERE T.PRJ_ID = (#prj_id) SET IDENTITY_INSERT [PMS_BACKUP].[Common].[DEPARTMENT_CAP] OFF IF ##ERROR <> 0 GOTO HANDLE_ERROR
INSERT INTO [PMS_BACKUP].[Common].[DOC_REG] SELECT * FROM [pms].[Common].[DOC_REG] T WHERE T.PRJ_ID = (#prj_id) IF ##ERROR <> 0 GOTO HANDLE_ERROR
-- 3. Commit transaction
COMMIT TRANSACTION #TranName;
return ##trancount;
HANDLE_ERROR:
rollback transaction #TranName
RETURN 1
END
and the issue is even if the first insert query fails, its not stopping the processing and resume the rest of the insert queries. The return value I am getting is 1, but in the results window I can see the log like this
(0 row(s) affected) Msg 2627, Level
14, State 1, Procedure
sp_ProjectBackup_Insert, Line 35
Violation of PRIMARY KEY constraint
'PK_PROJECT'. Cannot insert duplicate
key in object 'Common.PROJECT'. The
statement has been terminated.
(0 row(s) affected)
(0 row(s) affected)
I thought the return 1 will make the exit from error handling code but not happening. Any problem with my error handling?
There are so many things wrong with this I don't know where to start.
As far as your error call, you are trapping whether there is an error on the last step run before the error, not if any error has occurred so far. Since the last step is not the insert but the set_identity_insert statement, there is no error to trap.
Now, on to what needs fixing besides that.
If this is a backup table and is only used as a backup table, get rid of the identity property all together. No need to keep turning the insert on and off, just fix the table, it is not being directly written to by users data is alawys coming from another table, so why does it need an identity at all?
Next, the error you got indicates to me that what you need to be doing is inserting only records that don't already exist in the backup table not all records. You may also need to update existing records. Or you need to truncate the table first before doing the insert if you only need the most current data period and the data table being copied is not that large (you don't want to re-enter a million records when only 100 were new and 10 were changed).
In SQL Server 2005 you have TRY CATCH blocks available, you should start using those instead of goto.
Never, ever, ever use SELECT * in an insert. Or any time the code will go to production. Select * is a very poor programming technique. In the insert for instance it will cause problems when the initial table is changed as you define the columns to insert into but not those in the select.
Finally, you should not name stored procedures with sp at the start. System procs start with sp and SQL Server will look there first for the proc before looking at user procs. It's a little wasted time every time you call a proc. Overall it's bad for the system and if they happen to have a system proc with the same name yours will never be called.
You need to put proper error handling around your statements. With SQL 2005 and up, that means try/catch:
PROCEDURE [dbo].[sp_ProjectBackup_Insert]
#prj_id bigint
AS
BEGIN
DECLARE #MSG varchar(200)
DECLARE #TranName varchar(200)
DECLARE #return_value int
-- 1. Starting the transaction
BEGIN TRANSACTION #TranName
-- 2. Insert the records
BEGIN TRY
SET IDENTITY_INSERT [PMS_BACKUP].[Common].[PROJECT] ON INSERT INTO [PMS_BACKUP].[Common].[PROJECT] ([PRJ_ID],[PRJ_NO1],[PRJ_NO2],[PRJ_NO3],[PRJ_DESC],[IS_TASKFORCE],[DATE_CREATED],[IS_APPROVED],[DATE_APPROVED],[IS_HANDEDOVER],[DATE_HANDEDOVER],[DATE_START],[DATE_FINISH],[YEAR_OF_ORDER],[CLIENT_DETAILS],[SCOPE_OF_WORK],[IS_PROPOSAL],[PRJ_MANAGER],[PRJ_NAME],[MANAGER_VALDEL],[MANAGER_CLIENT],[DEPT_ID],[locationid],[cut_off_date]) SELECT * FROM [pms].[Common].[PROJECT] T WHERE T.PRJ_ID = (#prj_id) SET IDENTITY_INSERT [PMS_BACKUP].[Common].[PROJECT] OFF IF ##ERROR <> 0 GOTO HANDLE_ERROR
SET IDENTITY_INSERT [PMS_BACKUP].[Common].[DEPARTMENT_CAP] ON INSERT INTO [PMS_BACKUP].[Common].[DEPARTMENT_CAP] ([CAP_ID],[DEPT_ID],[PRJ_ID],[IS_CAPPED],[DATE_CAPPED],[CAPPED_BY],[CAP_APPROVED_BY],[STATUS],[UNCAPPED_BY],[DATE_UNCAPPED],[DESCRIPTION],[UNCAP_APPROVED_BY],[LOCATIONID]) SELECT * FROM [pms].[Common].[DEPARTMENT_CAP] T WHERE T.PRJ_ID = (#prj_id) SET IDENTITY_INSERT [PMS_BACKUP].[Common].[DEPARTMENT_CAP] OFF IF ##ERROR <> 0 GOTO HANDLE_ERROR
INSERT INTO [PMS_BACKUP].[Common].[DOC_REG] SELECT * FROM [pms].[Common].[DOC_REG] T WHERE T.PRJ_ID = (#prj_id) IF ##ERROR <> 0 GOTO HANDLE_ERROR
-- 3. Commit transaction
COMMIT TRANSACTION #TranName;
RETURN 0
END TRY
BEGIN CATCH
--HANDLE_ERROR
ROLLBACK TRANSACTION #TranName
RETURN 1
END CATCH
END
(Be sure to test and debug this -- should be good, but you never know.)
The RETURN value is only relevant to whatever called the procedure -- if it's not checking for success or failure, then you may have a problem.