Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I raise a custom exception in SQL Server

I have a stored procedure spMyProc. The procedure is passed a table name as a parameter @TableName. It is important to verify that the table exists before proceeding to the body of the procedure.

How can I create a custom exception to raise an error if the table name is invalid?

I am aware of TRY and CATCH but I'm unsure how to put this together with custom exceptions.

Regards.

like image 946
Danny Rancher Avatar asked Sep 29 '14 15:09

Danny Rancher


People also ask

How do I create a custom exception in SQL?

PL/SQL allows you to define your own exceptions according to the need of your program. A user-defined exception must be declared and then raised explicitly, using either a RAISE statement or the procedure DBMS_STANDARD. RAISE_APPLICATION_ERROR.

How do I raise an exception in SQL Server?

The following example shows how to use the THROW statement to raise the last thrown exception again. USE tempdb; GO CREATE TABLE dbo. TestRethrow ( ID INT PRIMARY KEY ); BEGIN TRY INSERT dbo. TestRethrow(ID) VALUES(1); -- Force error 2627, Violation of PRIMARY KEY constraint to be raised.

Which is the function used to raise custom errors in SQL?

The errors generated by RAISERROR operate the same as errors generated by the Database Engine code. The values specified by RAISERROR are reported by the ERROR_LINE , ERROR_MESSAGE , ERROR_NUMBER , ERROR_PROCEDURE , ERROR_SEVERITY , ERROR_STATE , and @@ERROR system functions.

Can we throw SQL exception?

The following subclasses of SQLException can also be thrown: BatchUpdateException is thrown when an error occurs during a batch update operation. In addition to the information provided by SQLException , BatchUpdateException provides the update counts for all statements that were executed before the error occurred.


2 Answers

Look into RAISERROR() funiction.

TRY.. CATCH works pretty same as it would work in any other programming language

BEGIN TRY

  -- do your checks 
      IF NOT EXISTS(SELECT 1 FROM sys.tables WHERE NAME = @TableName)
       BEGIN
           RAISERROR('Table does not exist', 16,1)
       END

  -- rest of the code if  checks are passed 
  -- if above checks are not passed and you riase an error 
  -- control will skip any code in TRY Block after the error has been 
  -- Raised and staright jump to Catch block.

END TRY

BEGIN CATCH 
  -- Do your error logging 
  -- Other stuff 
  -- you have access to ERROR_ functions here to get detailed info about errors
END CATCH 
like image 157
M.Ali Avatar answered Sep 24 '22 05:09

M.Ali


I think one of examples supplied here RAISERROR should match your problem. New versions of SQL Server will use THROW instead of RAISERROR.

like image 37
maciek Avatar answered Sep 24 '22 05:09

maciek