Is it possible to raise an error in a stored procedure manually to stop execution and jump to BEGIN CATCH
block? Some analog of throw new Exception()
in C#
.
Here is my stored procedure's body:
BEGIN TRY BEGIN TRAN -- do something IF @foobar IS NULL -- here i want to raise an error to rollback transaction -- do something next COMMIT TRAN END TRY BEGIN CATCH IF @@trancount > 0 ROLLBACK TRAN END CATCH
I know one way: SELECT 1/0
But it's awful!!
CATCH blocks can use RAISERROR to rethrow the error that invoked the CATCH block by using system functions such as ERROR_NUMBER and ERROR_MESSAGE to retrieve the original error information. @@ERROR is set to 0 by default for messages with a severity from 1 through 10.
The usual trick is to force a divide by 0. This will raise an error and interrupt the current statement that is evaluating the function.
When called in a CATCH block, ERROR_MESSAGE returns the complete text of the error message that caused the CATCH block to run. The text includes the values supplied for any substitutable parameters - for example, lengths, object names, or times. ERROR_MESSAGE returns NULL when called outside the scope of a CATCH block.
RAISERROR is a SQL Server error handling statement that generates an error message and initiates error processing. RAISERROR can either reference a user-defined message that is stored in the sys. messages catalog view or it can build a message dynamically.
you can use raiserror
. Read more details here
--from MSDN
BEGIN TRY -- RAISERROR with severity 11-19 will cause execution to -- jump to the CATCH block. RAISERROR ('Error raised in TRY block.', -- Message text. 16, -- Severity. 1 -- State. ); END TRY BEGIN CATCH DECLARE @ErrorMessage NVARCHAR(4000); DECLARE @ErrorSeverity INT; DECLARE @ErrorState INT; SELECT @ErrorMessage = ERROR_MESSAGE(), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE(); -- Use RAISERROR inside the CATCH block to return error -- information about the original error that caused -- execution to jump to the CATCH block. RAISERROR (@ErrorMessage, -- Message text. @ErrorSeverity, -- Severity. @ErrorState -- State. ); END CATCH;
EDIT If you are using SQL Server 2012+ you can use throw
clause. Here are the details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With