Quantcast
Viewing all articles
Browse latest Browse all 20

How to: Check the time of the last clean DBCC CHECKDB in SQL Server

DBCC CHECKDB is a common maintenance task executed to verify that the data stored in a SQL Server database is clean (i.e. not corrupt).  Generally speaking, it is good practice to run DBCC CHECKDB against any database that contains valuable data.  The one database where DBCC CHECKDB is not necessary is the tempdb database as the tempdb database is recreated from scratch every time that the SQL Server service is started.  All of the other system and user databases should be checked on a regular basis – if possible.

So, how do you know the last time DBCC CHECKDB was executed successfully against a given database?  Why with the following script of course!

use master
GO
 
DBCC TRACEON (3604)
GO
 
DECLARE @DBCCPage AS TABLE
(
    DatabaseName    SYSNAME NULL,
    ParentObject    SYSNAME,
    [Object]        SYSNAME,
    Field           SYSNAME,
    [Value]         SQL_VARIANT
)
 
DECLARE DatabaseCursor CURSOR LOCAL FAST_FORWARD
FOR SELECT name FROM sys.databases WHERE state_desc = ‘ONLINE’
 
OPEN DatabaseCursor
 
DECLARE @DatabaseName SYSNAME
 
FETCH NEXT FROM DatabaseCursor INTO @DatabaseName
 
WHILE @@FETCH_STATUS = 0
BEGIN
    –Insert the DBCC PAGE output into the @DBCCPage table
    INSERT INTO @DBCCPage (ParentObject, [Object], Field, Value)
    EXEC(‘DBCC PAGE ([' + @DatabaseName +'], 1, 9, 3) WITH TABLERESULTS’)
   
    –Set the database name
    UPDATE @DBCCPage SET DatabaseName = @DatabaseName WHERE DatabaseName IS NULL
   
    FETCH NEXT FROM DatabaseCursor INTO @DatabaseName
END
 
SELECT DISTINCT
    DatabaseName,
    CONVERT(DATETIME, Value) AS LastGoodDBCC,
    DATEDIFF(day, CONVERT(DATETIME, Value), GETDATE()) AS DaysSinceLastGoodDBCC
FROM
    @DBCCPage
WHERE
    Field IN (‘dbi_dbccLastKnownGood’)
ORDER BY
    DatabaseName
GO
 
DBCC TRACEOFF (3604)
GO

Some time ago, Paul Randal published a post entitled “CHECKDB From Every Angle: When did DBCC CHECKDB last run successfully?.”  This gave us the raw internals to identify the last good DBCC CHECKDB run.  The script above simply wraps that information into an easy to consume report.

This is a great script to have in your toolbox – especially if you are new to an environment and you are trying to get a feel for the condition of the databases on a particular system.

That’s it for this post.  Please check back tomorrow for some more SQL Server / .NET goodness!


Filed under: SQL Server, SQL Server 2008, SQL Server CLR, SQL Server Programming Tagged: DBCC, DBCC CHECKDB, SQL Server Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 20

Trending Articles