Tuesday, April 16, 2019

Track error in sql server procedures


1. Create a ErrorLog Table

  CREATE TABLE [dbo].[ErrorLog](
[ErrorLogId] [int] IDENTITY(1,1) NOT NULL,
[CreatedDate] [datetime] NULL,
[ProcedureName] [varchar](100) NULL,
[ErrorLine] [int] NULL,
[ErrorNumber] [int] NULL,
[ErrorMessage] [varchar](max) NULL,
[ErrorSeverity] [varchar](max) NULL,
[ErrorState] [int] NULL,
[ErrorProcedure] [varchar](100) NULL


2. Implement  Try and Catch

   BEGIN TRY 

    --  Sql Statements

 END TRY
 BEGIN CATCH
  Insert into ErrorLog(CreatedDate,ProcedureName,ErrorLine,ErrorNumber,ErrorMessage,ErrorState,ErrorProcedure)
  Values(GetDate(),'ProcedureName',ERROR_LINE(),ERROR_NUMBER(),ERROR_MESSAGE(),ERROR_STATE(),ERROR_PROCEDURE())
 END CATCH