Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Statement Termination using RAISERROR

(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?

like image 741
Bob Avatar asked Feb 28 '23 11:02

Bob


2 Answers

In a trigger, issue a ROLLBACK, RAISERROR and then RETURN.

see Error Handling in SQL Server - Trigger Context by Erland Sommarskog

like image 132
KM. Avatar answered Mar 07 '23 16:03

KM.


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.

like image 45
pjp Avatar answered Mar 07 '23 15:03

pjp