In this article, you will learn how to log SQL Server exceptions from stored procedures.
- create a table in which you want to save exceptions
SQL
CREATE TABLE [dbo].[ExceptionLog]( [id] [int] IDENTITY(1, 1) NOT NULL, [ErrorLine] [int] NULL, [ErrorMessage] [nvarchar](5000) NULL, [ErrorNumber] [int] NULL, [ErrorProcedure] [nvarchar](128) NULL, [ErrorSeverity] [int] NULL, [ErrorState] [int] NULL, [DateErrorRaised] [datetime] NULL ) - create a stored procedure that inserts the exception details into the ExceptionLog table
SQL
Create Proc [dbo].[spGetErrorInfo] as begin insert into ExceptionLog( ErrorLine, ErrorMessage, ErrorNumber, ErrorProcedure, ErrorSeverity, ErrorState, DateErrorRaised ) SELECT ERROR_LINE() as ErrorLine, Error_Message() as ErrorMessage, Error_Number() as ErrorNumber, Error_Procedure() as 'Proc', Error_Severity() as ErrorSeverity, Error_State() as ErrorState, GETDATE() as DateErrorRaised end - create a student table for testing purposes
SQL
CREATE TABLE [dbo].[student]( [Id] [int] IDENTITY(1, 1) NOT NULL, [Name] [nchar](10) NULL, [City] [nchar](10) NULL ) - create a procedure for inserting the data into the student table
SQL
create proc spStudentInsert @name varchar(10), @city varchar(10) AS BEGIN SET NOCOUNT ON; BEGIN TRY insert into student(Name, City) values(@name, @city) END TRY BEGIN CATCH EXEC dbo.spGetErrorInfo END CATCH END - Now execute the stored procedure
SQL
exec spStudentInsert 'Raj', 'Varanasi'Now see the inserted record
SQLselect * from student
-
Now create an exception in the insert procedure
SQLALTER PROCEDURE [dbo].[spStudentInsert] @name varchar(10), @city varchar(10) AS BEGIN SET NOCOUNT ON; BEGIN TRY Select 1 / 0; // here i am giving hard coded value only for testing purpose if any run time exception occure it will caught into catch block insert into student(Name, City) values(@name, @city) END TRY BEGIN CATCH EXEC dbo.spGetErrorInfo END CATCH END -
Now execute stored procedure exec spStudentInsert 'Raj', 'Varanasi'

-
Note. This exception was caught only on the database level. It will not catch in code behind and if you want this exception caught in code behind, then Raise() function like the following.
SQLRAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState);


Bhuvanesh MohankumarPosted May 10, 2016, 1:59 AM EDT
Nice Ravi,found useful
Sibeesh VenuTOP 100Posted Oct 31, 2015, 2:13 AM EDT
Nice Share
Ravi PatelPosted Oct 31, 2015, 12:25 AM EDT
Thanks Nilesh Sir
Nilesh JadavPosted Oct 30, 2015, 11:49 PM EDT
Thank you for Sharing !
Ravi PatelPosted Oct 30, 2015, 10:28 PM EDT
thanks all
Harshad PansuriyaPosted Oct 30, 2015, 8:04 PM EDT
Nice one
Upendra Pratap ShahiPosted Oct 30, 2015, 9:54 AM EDT
thanks for sharing..nice info..
Priyaranjan K STOP 100Posted Oct 30, 2015, 9:36 AM EDT
Thanks for the share