Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise an error manually in T-SQL to jump to BEGIN CATCH block

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!!

like image 691
abatishchev Avatar asked Oct 07 '09 12:10

abatishchev


People also ask

How can we increase error in catch block in SQL Server?

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.

How do you raise errors in SQL?

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.

How do I catch an error message in SQL Server?

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.

What does raise error do in SQL?

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.


1 Answers

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.

like image 85
TheVillageIdiot Avatar answered Sep 21 '22 22:09

TheVillageIdiot