(SQL 2005)
Is it possible for a raiserror to terminate a stored proc.
For example, in a large system we've got a value that wasn't expected being entered into a specific column. In an update trigger if you write:
if exists (select * from inserted where testcol = 7)
begin
raiseerror('My Custom Error', 16, 1)
end
the update information is still applied.
however if you run
if exists (select * from inserted where testcol = 7)
begin
select 1/0
end
a divide by 0 error is thrown that actually terminates the update.
is there any way i can do this with a raiseerror so i can get custom error messages back?
In a trigger, issue a ROLLBACK, RAISERROR and then RETURN.
see Error Handling in SQL Server - Trigger Context by Erland Sommarskog
Can you not just add a CHECK constraint to the column to prevent it from being inserted in the first place?
ALTER TABLE YourTable ADD CONSTRAINT CK_No_Nasties
CHECK (testcol <> 7)
Alternatively you could start a transaction in your insert sproc (if you have one) and roll it back if an error occurs. This can be implemented with TRY, CATCH in SQL Server 2005 and avoids having to use a trigger.
Begin try
#temp number
#temp=1/0
End try
Begin catch
#errormsg varchar(100)
#errormsg=error_massage()
Raiseerror(#errormsg,16,1)
End catch
You should check for valid data prior to performing the update.
IF (#testvalue = 7)
RAISERROR("Invalid value.", 16, 1);
ELSE
UPDATE...
Related
I'm trying to automate a sql script to add a column to existing databases on a given system. The script will be run on a system with one database or a different one. The script should not cause error in any of the cases:
1. One of the two databases exists
2. Both databases exist
3. Neither database exists.
I tried this but I keep getting error when the database 'DatabaseName' does not exist. I want the script to be ignored in that case.
IF DB_ID('DatabaseName') IS NOT NULL
BEGIN
PRINT 'DatabaseName Exists'
IF COL_LENGTH('[DatabaseName].[dbo].[Table]', 'NewColumn') IS NULL
BEGIN
ALTER TABLE [DatabaseName].[dbo].[Table]
ADD [NewColumn] bit NOT NULL DEFAULT 0;
PRINT 'Modified DatabaseName.Table'
END
END
ELSE
BEGIN
PRINT 'DatabaseName Does Not Exist'
-- therefore do nothing
END
This gives me the error:
Msg 2702, Level 16, State 2, Line 6
Database 'DatabaseName' does not exist.
I had also tried different variations of
Use 'DatabaseName'
with the same or similar errors because they are not existent.
To clarify: it is okay if it does not exist. I am just trying to handle the error gracefully so an installation continues
Use dynamic SQL. The problem is occurring during the compilation phase of the code. Dynamic SQL will "hide" the reference to the database from the initial compilation phase.
For instance, in SQL Server, this looks like:
IF COL_LENGTH('[DatabaseName].[dbo].[Table]', 'NewColumn') IS NULL
BEGIN
exec sp_executesql N'
ALTER TABLE [DatabaseName].[dbo].[Table]
ADD [NewColumn] bit NOT NULL DEFAULT 0';
PRINT 'Modified DatabaseName.Table'
END
You can use a try catch block:
BEGIN TRY
-- Generate divide-by-zero error.
SELECT 1/0;
END TRY
BEGIN CATCH
-- Execute code if error
END CATCH;
I have an OLE DB Command that originally contained a simple three line update:
update raw_CommissionPaid set PolicyNumber = ? where PolicyNumber = ?
and this worked fine, did exactly as expected and all was good.
I recently decided though that this has the potential to go wrong and do a lot of damage so i decided i would put it all in a transaction, monitor the rows affected and roll back if it changed more than what i was expecting, so i changed my update to this:
BEGIN TRY BEGIN TRAN UpdateCommissionsPaidPolNo
update raw_CommissionPaid set PolicyNumber = ? where PolicyNumber = ?
IF ##ROWCOUNT <> 1 RAISERROR('Row count <> 1', 11, 1)
COMMIT TRAN END TRY BEGIN CATCH
ROLLBACK TRAN UpdateCommissionsPaidPolNo
PRINT 'UpdateCommissionsPaidPolicyNumber script failed'
SELECT
ERROR_MESSAGE() as ErrorMessage END CATCH
However this gave me the "Syntax error or general error" message that it usually gives. I remembered from a previous issue that sometimes it cant map parameters to the ?'s if they are embedded within other SQL, i thought that might be the issue so changed it to this just incase:
Declare #FNumber varchar(20) declare #LNumber varchar(20)
set #FNumber = ? set #LNumber = ?
BEGIN TRY BEGIN TRAN UpdateCommissionsPaidPolNo
update raw_CommissionPaid set PolicyNumber = #FNumber where
PolicyNumber = #LNumber
IF ##ROWCOUNT <> 1 RAISERROR('Row count <> 1', 11, 1)
COMMIT TRAN END TRY BEGIN CATCH
ROLLBACK TRAN UpdateCommissionsPaidPolNo
PRINT 'UpdateCommissionsPaidPolicyNumber script failed'
SELECT
ERROR_MESSAGE() as ErrorMessage END CATCH
but from this i still get :
Syntax Error, permission violation or other non specific error
i realised it might be because of the print, or the returning of the error message, but removing them doesnt change anything, it still fails
im sure the sql is valid as i tested it in SQL server management studio.
Anyone faced this? Is there a setting im supposed to change to allow this kind of change?
Thanks in advance
After reading This site i learned that if i set the data flow tasks TransactionOption property to supported then if it fails it supposedly rolls the failing section back itself.
Armed with this knowledge i figured then the only thing i needed to do was make it realise that multiple rows being updated counted as an error. So changing it to just this:
update raw_CommissionPaid set PolicyNumber = ? where PolicyNumber = ?
IF ##ROWCOUNT <> 1 RAISERROR('Row count <> 1', 11, 1)
should make it roll itself back.
Assuming that the table MyTable already exists, Why does the "In catch" is printed on the first statement, but not on the second?
It seems to be catching errors on duplicate table names but not on duplicate column names
First:
BEGIN TRY
BEGIN TRANSACTION
CREATE TABLE MyTable (id INT)
COMMIT TRANSACTION
END TRY
BEGIN CATCH
PRINT 'in Catch'
ROLLBACK TRANSACTION
END CATCH
Second:
BEGIN TRY
BEGIN TRANSACTION
ALTER TABLE MyTable ADD id INT
COMMIT TRANSACTION
END TRY
BEGIN CATCH
PRINT 'in Catch'
ROLLBACK TRANSACTION
END CATCH
The difference is that the alter table statement generates a compile time error, not a runtime error, so the catch block is never executed as the batch itself is not executed.
You can check this by using the display estimated execution plan button in SQL server management studio, you will see for the CREATE TABLE statement, an estimated plan is displayed, whereas for the ALTER TABLE statement, the error is thrown before SQL server can even generate a plan as it cannot compile the batch.
EDIT - EXPLANATION:
This is to do with the way deferred name resolution works in SQL server, if you are creating an object, SQL server does not check that the object already exists until runtime. However if you reference columns in an object that does exist, the columns etc that you reference must be correct or the statement will fail to compile.
An example of this is with stored procedures, say you have the following table:
create table t1
(
id int
)
then you create a stored procedure like this:
create procedure p1
as
begin
select * from t2
end
It will work as deferred name resolution does not require the object to exist when the procedure is created, but it will fail if it is executed
If, however, you create the procedure like this:
create procedure p2
as
begin
select id2 from t1
end
The procedure will fail to be created as you have referenced an object that does exist, so deferred name resolution rules no longer apply.
I encountered a stored procedure that had the following error handling block immediately after an update attempt. The following were the last lines of the SP.
Is there any benefit of doing this? It appears to me as though this code is just rethrowing the same error that it caught without any value added and that the code would presumably behave 100% the same if the Try Block were ommited entirely.
Would there be ANY difference in the behavior of the resulting SP if the TRY block were ommitted?
BEGIN CATCH
SELECT #ErrMsg = ERROR_MESSAGE(), #ErrSev = ERROR_SEVERITY(), #ErrState = ERROR_STATE()
RAISERROR (#ErrMsg, #ErrSev, #ErrState)
END CATCH
Barring the fact that the "line error occured on" part of any message returned would reference the RAISERROR line and not the line the error actually occured on, there will be no difference. The main reason to do this is as #Chris says, to allow you to programmatically use/manipulate the error data.
What we usually do in our stored procedure is to write the catch block like this
BEGIN CATCH
DECLARE #i_intErrorNo int
DECLARE #i_strErrorMsg nvarchar(1000)
DECLARE #i_strErrorProc nvarchar(1000)
DECLARE #i_intErrorLine int
SELECT #i_intErrorNo=Error_Number()
SELECT #i_strErrorMsg=Error_Message()
SELECT #i_strErrorProc=Error_Procedure()
SELECT #i_intErrorLine=Error_Line()
INSERT INTO error table ////// Insert statement.
END CATCH
This is something we use to do to store error. For proper message to user, I always use the output parameter to the stored procedure to show the detailed/required reason of the error.
if you look on the msdn page for RAISERROR then you see this general description:
Generates an error message and
initiates error processing for the
session. RAISERROR can either
reference a user-defined message
stored in the sys.messages catalog
view or build a message dynamically.
The message is returned as a server
error message to the calling
application or to an associated CATCH
block of a TRY…CATCH construct.
It appears that the "calling application" will get the error message. It may be that the creator of the stored procedure wanted only the error message, severity, and state to be reported and no other options that can be added. This may be because of security concerns or just that the calling application did not need to know the extra information (which could have been verbose or overly detailed, perhaps).
There is a subtle difference, as demonstrated below.
First setup the following:
CREATE TABLE TMP
( ROW_ID int NOT NULL,
ALTER TABLE TMP ADD CONSTRAINT PK_TMP PRIMARY KEY CLUSTERED (ROW_ID)
)
GO
CREATE PROC pTMP1
AS
BEGIN TRY
INSERT INTO TMP VALUES(1)
INSERT INTO TMP VALUES(1)
INSERT INTO TMP VALUES(2)
END TRY
BEGIN CATCH
DECLARE #ErrMsg varchar(max)= ERROR_MESSAGE(),
#ErrSev int = ERROR_SEVERITY(),
#ErrState int = ERROR_STATE()
RAISERROR (#ErrMsg, #ErrSev, #ErrState)
END CATCH
GO
CREATE PROC pTMP2
AS
INSERT INTO TMP VALUES(1)
INSERT INTO TMP VALUES(1)
INSERT INTO TMP VALUES(2)
GO
Now run the following:
SET NOCOUNT ON
DELETE TMP
exec pTMP1
SELECT * FROM TMP
DELETE TMP
exec pTMP2
SELECT * FROM TMP
SET NOCOUNT OFF
--Cleanup
DROP PROCEDURE pTMP1
DROP PROCEDURE pTMP2
DROP TABLE TMP
You should get the following results:
Msg 50000, Level 14, State 1, Procedure pTMP1, Line 12
Violation of PRIMARY KEY constraint 'PK_TMP'. Cannot insert duplicate key in object 'dbo.TMP'. The duplicate key value is (1).
ROW_ID
-----------
1
Msg 2627, Level 14, State 1, Procedure pTMP2, Line 4
Violation of PRIMARY KEY constraint 'PK_TMP'. Cannot insert duplicate key in object 'dbo.TMP'. The duplicate key value is (1).
The statement has been terminated.
ROW_ID
-----------
1
2
Notice that the TRY..CATCH version did not execute the third INSERT statement, whereas the pTMP2 proc did. This is because control jumps to CATCH as soon as the error occurs.
NOTE: The behaviour of pTMP2 is affected by the XACT_ABORT setting.
Conclusion
The benefit of using TRY..CATCH as demonstrated depends on how you manage your transaction boundaries.
If you roll-back on any error, then the changes will be undone. But this doesn't eliminate side-effects such as addtional processing. NOTE: If a different session simultaneously queries TMP using WITH(NOLOCK) it may even be able to observe the temporary change.
However, if you don't intend rolling back a transaction, you may find the technique is quite important to prevent certain data changes being applied in spite of an earlier error.
I am coding SQL Server 2005 trigger. I want to make some logging during trigger execution, using INSERT statement into my log table. When there occurs error during execution, I want to raise error and cancel action that cause trigger execution, but not to lose log records. What is the best way to achieve this?
Now my trigger logs everything except situation when there is error - because of ROLLBACK. RAISERROR statement is needed in order to inform calling program about error.
Now, my error handling code looks like:
if (#err = 1)
begin
INSERT INTO dbo.log(date, entry) SELECT getdate(), 'ERROR: ' + out from #output
RAISERROR (#msg, 16, 1)
rollback transaction
return
end
Another possible option is to use a table variable to capture the info you want to store in your permanent log table. Table variables are not rolled back if a ROLLBACK TRANSACTION command is given. Sample code is below...
--- Declare table variable
DECLARE #ErrorTable TABLE
( [DATE] smalldatetime,
[ENTRY] varchar(64) )
DECLARE #nErrorVar int
--- Open Transaction
BEGIN TRANSACTION
--- Pretend to cause an error and catch the error code
SET #nErrorVar = 1 --- ##ERROR
IF (#nErrorVar = 1)
BEGIN
--- Insert error info table variable
INSERT INTO #ErrorTable
( [Date], [Entry] )
SELECT
getdate(), 'Error Message Goes Here'
RAISERROR('Error Message Goes Here', 16, 1)
ROLLBACK TRANSACTION
--- Change this to actually insert into your permanent log table
SELECT *
FROM #ErrorTable
END
IF ##TRANCOUNT 0
PRINT 'Open Transactions Exist'
ELSE
PRINT 'No Open Transactions'
The problem here is that logging is part of transaction that modifies your data. Nested transactions will not help here. What you need is to put you logging actions into a separate context (connection), i.e. make it independent from you current transaction.
Two options come to my mind:
use Service Broker for logging - put log data to queue, receive and save the data 'on the other side of the pipe' (i.e. in another process/connection/transaction)
use OPENQUERY - you will need to register you own server as a 'linked server' and execute queries 'remotely' (I know, this looks a little bit strange, but an option anyway ...)
HTH
Don't know if I'm thinking too simple, but why not just change the order of the error handler to insert AFTER the rollback??
if (#err = 1)
begin
RAISERROR (#msg, 16, 1)
rollback transaction
INSERT INTO dbo.log(date, entry) SELECT getdate(), 'ERROR: ' + out from #output
return
end
Checkout error handling in triggers.