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.
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.
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.
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.
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.
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
I think one of examples supplied here RAISERROR should match your problem. New versions of SQL Server will use THROW instead of RAISERROR.
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