/* ------------------------ My Meta Content Here SEO ------------------------ */

Pages

Main Menu

Sunday, September 29, 2019

Using SQL Server Logging Exception in SQL table

Writing logs in SQL Server:

First create a table to log the system exceptions occurred:

CREATE TABLE [dbo].[tblExceptionLog]( 
[Id] [int] IDENTITY(1, 1) NOT NULL, 
[ErrorLine] [int] NULL, 
[ErrorMessage] [nvarchar](4000) NULL, 
[ErrorNumber] [int] NULL, 
[ErrorProcedure] [nvarchar](128) NULL, 
[ErrorSeverity] [int] NULL, 
[ErrorState] [int] NULL, 
[DateErrorRaised] [datetime] NULL 


Create a stored procedure: This procedure will insert the exception log in case of error will come

Create PROC [dbo].[uspGetErrorInfo]
AS
BEGIN
INSERT INTO tblExceptionLog( 
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 
GO

Use the following approach to log the exception:

BEGIN TRY
BEGIN TRAN
--SQL Statements
COMMIT TRAN
END TRY
BEGIN CATCH
--Print 'Catching Exceptio Here'
IF @@TRANCOUNT > 0
ROLLBACK TRAN

EXEC dbo.uspGetErrorInfo  
END CATCH

No comments:

Post a Comment

My Blog List

  • काश - काश मुझे भी पीने की आदत होती,मैं कब का मुर्दा हो गया होता। छुटकारा मिलता आज के आतंकवाद से, किसी संतान भूमि में सो गया होता। मेरा एतबार कौन करेगा, मैंने मुर...
    3 months ago
  • काश - काश मुझे भी पीने की आदत होती,मैं कब का मुर्दा हो गया होता। छुटकारा मिलता आज के आतंकवाद से, किसी शमशान भूमि में सो गया होता। मेरा एतबार कौन करेगा, मैंने मुर...
    3 months ago
  • Kumaon University Nainital B.Ed entrance exam test result 2012 - कुमाऊँ विश्वविधालय, नैनीताल (उत्तराखण्ड)
    10 years ago