it:ad:sql_server:howto:sql:functions_try_catch_functions

IT:AD:SQL Server:HowTo:SQL:Functions/Try/Catch Functions

Summary

It's horribly verbose compared to some languages, but this is a simple example:

BEGIN TRY
BEGIN TRANSACTION

EXEC sp_SomeFaultCode


COMMIT TRANSACTION
END TRY
BEGIN CATCH
-- Execute error retrieval routine

-- Error_Message() : returns message typically sent to caller. 
-- Error_Number() : returns integer assigned to the error.
-- Error_Severity() : returns integer representing severity. 
-- Error_State() : returns the state. 
-- Error_Procedure() : returns procedure/function name (or null). 
-- Error_Line() : returns line number where the error occurred. 

SELECT 
@@ERROR,
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;

--OR: EXECUTE usp_GetErrorInfo;

ROLLBACK TRANSACTION

RAISERROR (N'This is message %s %d.', -- Message text.
10, -- Severity,
1, -- State,
N'number', -- First argument.
5); -- Second argument.

END CATCH;

  • /home/skysigal/public_html/data/pages/it/ad/sql_server/howto/sql/functions_try_catch_functions.txt
  • Last modified: 2023/11/04 02:28
  • by 127.0.0.1