SQL SERVER – Read Error Log Data using sp_readerrorlog – System Stored Procedure


sp_readerrorlog : this stored procedure is used to read the SQL Server logs and SQL Agent error log data.

In this blog post I am going to show you how to use the stored procedure sp_readerrorlog to read log details from SQL Server Logs and SQL Server Agent error log files.

Stored procedure usage

sp_readerrolog <error log number>, <log type>, <Search string>

<error log number>

0  = current
1 = Archive #1
2 =  Archive #2
….
N = Archive #N

<log type>

0 = SQL Server logs

1  = SQL Server Agent Error Logs

<Search String>

We have to give the string constant to search in the error text.

  • SQL Server Logs can be found as shown in the image.

pic1

  • SQL Server Agent Error Logs can be found as shown in the image.

pic2

Examples

1. Reading current SQL Server Log details

sp_readerrorlog 0, 1

2. Reading current SQL Server Agent Error Log details

sp_readerrorlog 0, 2

3. Searching a given string in the SQL Server log data and list the available log information

sp_readerrorlog 0, 1, ‘Starting up Database’

output

pic3I believe you have understood the use of the system stored procedure sp_readerrolog. The below given TSQL statement help you to use the stored procedure output in the SELECT statement. So, you can use this TSQL to store the error log data in a separate table for the future use.

TSQL

DECLARE @logs TABLE
(
LogDate DATETIME,
ProcessInfo VARCHAR(255),
Text VARCHAR(MAX)
)

INSERT INTO @logs
EXEC sp_readerrorlog

SELECT *
FROM @logs where text like ‘%database%’
GO

Output

pic4

3 thoughts on “SQL SERVER – Read Error Log Data using sp_readerrorlog – System Stored Procedure

Leave a comment