How To Do Exception Handling in SQL Server Stored Procedure with TRY CATCH in Asp.Net C#
To handle exceptions in SQL Server we can use TRY…… CATCH blocks. To use TRY…… CATCH blocks in stored procedure we need to write the query like as shown below
To handle exceptions in SQL Server we can use TRY…… CATCH blocks. To use TRY…… CATCH blocks in stored procedure we need to write the query like as shown below
BEGIN TRY ---Write Your Code END TRY BEGIN CATCH ---Write Code to handle errors END CATCH |
ERROR_LINE() - This function will return error line number of SQL query which cause to raise error.
ERROR_NUMBER() - This function will return error number which is unique and assigned to it.
ERROR_SEVERITY() - This function will return severity of error which indicates how serious the error is. The values are between 1 and 25.
ERROR_STATE() - This function will return state number of error message which cause to raise error.
ERROR_PROCEDURE() - This function will return name of the procedure where an error occurred.
ERROR_MESSAGE() - This function will return the complete text of the error message which cause to raise error.
Check below sample query to handle errors in stored procedure
BEGIN TRY SELECT 300/0 END TRY BEGIN CATCH SELECT ErrorNumber = ERROR_NUMBER(), ErrorSeverity = ERROR_SEVERITY(), ErrorState =ERROR_STATE(), ErrorProcedure = ERROR_PROCEDURE(), ErrorLine = ERROR_LINE(), ErrorMessage = ERROR_MESSAGE() END CATCH |
Demo:
|
No comments:
Post a Comment