Skip to main content

SQL Server query to produce a result set (LogDate, ProcessInfo, Text) from the error log.

------------------------------------------------------------
-- Drop temp tables if exists
------------------------------------------------------------

if OBJECT_ID(N'tempdb..##tbl_sql_error_log') is not null
begin
    drop table ##tbl_sql_error_log;
end;

if OBJECT_ID(N'tempdb..#ErrLogsDL') is not null
begin
    drop table #ErrLogsDL;
end;

declare @site_value int;
declare @NumberOfLogfiles int;

------------------------------------------------------------
-- Create temp table to hold results from xp_enumerrorlogs
------------------------------------------------------------

create table #ErrLogsDL (
    [Archive #] int,
    [Date] varchar(255),
    [Log File Size (Byte)] bigint
);

---------------------------------------------------------------
-- Populate the temp table with
-- the data returned by executing xp_enumerrorlogs
---------------------------------------------------------------

insert into #ErrLogsDL ([Archive #], [Date], [Log File Size (Byte)])
    exec master.dbo.xp_enumerrorlogs;

set @NumberOfLogfiles = (select COUNT(*) from #ErrLogsDL);

------------------------------------------------------------------
-- Create temp table to hold results from ##tbl_sql_error_log data
------------------------------------------------------------------

create table ##tbl_sql_error_log (
    LogDate datetime,
    Processinfo nvarchar(max),
    text nvarchar(max)
);

set @site_value = 0;
while @site_value < @NumberOfLogfiles
    begin
        insert into ##tbl_sql_error_log
        exec sp_readerrorlog @site_value;
        set @site_value = @site_value + 1;
    end;

select * from ##tbl_sql_error_log order by logdate;

drop table ##tbl_sql_error_log;
drop table #ErrLogsDL;