Capture and Store SQL Server Database Integrity History using DBCC CHECKDB

By:   |   Updated: 2018-05-03   |   Comments (37)   |   Related: > Database Console Commands DBCCs


Problem

We've all used the command DBCC CHECKDB from time to time in our DBA careers to verify database integrity and repair corrupt databases. The latest version of this command checks the logical and physical integrity of all objects in the specified database by performing the following operations:

  • Runs DBCC CHECKALLOC on the database.
  • Runs DBCC CHECKTABLE on every table and view in the database.
  • Runs DBCC CHECKCATALOG on the database.
  • Validates the contents of every indexed view in the database.
  • Validates link-level consistency between table metadata and file system directories and files when storing varbinary(max) data in the file system using FILESTREAM.
  • Validates the Service Broker data in the database.

This means that the DBCC CHECKALLOC, DBCC CHECKTABLE, or DBCC CHECKCATALOG commands do not need to be run when you use DBCC CHECKDB.

This command is often run ad-hoc in the event of a corrupt database, but it is also recommended that you run it against your database(s) as part of your regular database maintenance routine. Although you can use the Maintenance Plan Wizard to Check Database Integrity, it does not give you the flexibility to store and query historical data.

The standard output can be quite extensive, not formatted for easy analysis, and often is not persisted in any useful way for historical analysis.

Solution

To insert the DBCC results into a readable and manageable format, you can use the 'WITH TABLERESULTS' option for DBCC CHECKDB to get an output that can be piped to a table for analysis. This option has been implemented for most of the DBCC statements in versions SQL 2000 and above. My script was created on a SQL Server 2008 instance. There are several diagnostic and repair options that you can use and you can read about them here: DBCC CHECKDB.

The purpose of this article is to enable you to capture and store database integrity history in a custom table that can be used for historical analysis on an on-going basis as part of your maintenance routine.

Collect The Data

A stored procedure will be created that can be scheduled as a SQL Agent job that writes to a history table where the DBCC CHECKDB output is stored and can later be queried.

First, you will want to run the following script to create the table 'dbcc_history' in some database used for DBA tasks and maintenance. If you do not have a database for this, then simply create one.

There are two versions of the collection table and code depending on version of SQL Server, so refer to the correct version you are using below.

Code to Collect DBCC CheckDB data for SQL Server 2005, 2008, and 2008 R2

All the columns here, except one, match the definition of the columns output in DBCC CHECKDB WITH TABLERESULTS. I added the [TimeStamp] column with a default constraint of getdate(). This will allow each run to be stored with the current time and date automatically upon insert of the rows.

-- table structure for SQL Server 2005, 2008 and 2008 R2
CREATE TABLE [dbo].[dbcc_history](
[Error] [int] NULL,
[Level] [int] NULL,
[State] [int] NULL,
[MessageText] [varchar](7000) NULL,
[RepairLevel] [int] NULL,
[Status] [int] NULL,
[DbId] [int] NULL,
[Id] [int] NULL,
[IndId] [int] NULL,
[PartitionID] [int] NULL,
[AllocUnitID] [int] NULL,
[File] [int] NULL,
[Page] [int] NULL,
[Slot] [int] NULL,
[RefFile] [int] NULL,
[RefPage] [int] NULL,
[RefSlot] [int] NULL,
[Allocation] [int] NULL,
[TimeStamp] [datetime] NULL CONSTRAINT [DF_dbcc_history_TimeStamp] DEFAULT (GETDATE())
) ON [PRIMARY]
GO	

Next, we will need to create our stored procedure called 'usp_CheckDBIntegrity'. In this example, the stored proc accepts one parameter - '@database_name'. If you specify a database name during execution, then the script will run DBCC CHECKDB against only that particular database. By simply executing the procedure as 'EXEC usp_CheckDBIntegrity', you can run the dbcc against ALL databases on the server.

In addition, this script excludes system databases, only runs against databases that are online, excludes snapshot databases, and excludes 'READ-ONLY' databases. You can modify the script's behavior by commenting out the appropriate line.

NOTE: It is important to test this in order to understand the time it takes to run against any one or all databases. DO NOT run this on your production environment during normal operating hours! This process should be run off-hours during an available maintenance window.

/****** Object: StoredProcedure [dbo].[usp_CheckDBIntegrity] Created by Robert Pearl ******/
/****** for SQL Server 2005, 2008 and 2008 R2 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROC [dbo].[usp_CheckDBIntegrity]
@database_name SYSNAME=NULL
AS
IF @database_name IS NULL -- Run against all databases
BEGIN
   DECLARE database_cursor CURSOR FOR
   SELECT name 
   FROM sys.databases db
   WHERE name NOT IN ('master','model','msdb','tempdb') 
   AND db.state_desc = 'ONLINE'
   AND source_database_id IS NULL -- REAL DBS ONLY (Not Snapshots)
   AND is_read_only = 0

   OPEN database_cursor
   FETCH next FROM database_cursor INTO @database_name
   WHILE @@FETCH_STATUS=0
   BEGIN

      INSERT INTO dbcc_history ([Error], [Level], [State], MessageText, RepairLevel, [Status], 
      [DbId], Id, IndId, PartitionId, AllocUnitId, [File], Page, Slot, RefFile, RefPage, 
      RefSlot,Allocation)
      EXEC ('dbcc checkdb(''' + @database_name + ''') with tableresults')

      FETCH next FROM database_cursor INTO @database_name
   END

   CLOSE database_cursor
   DEALLOCATE database_cursor
END 

ELSE -- run against a specified database (ie: usp_CheckDBIntegrity 'DB Name Here'

   INSERT INTO dbcc_history ([Error], [Level], [State], MessageText, RepairLevel, [Status], 
   [DbId], Id, IndId, PartitionId, AllocUnitId, [File], Page, Slot, RefFile, RefPage, RefSlot,Allocation)
   EXEC ('dbcc checkdb(''' + @database_name + ''') with tableresults')
GO 

Code to Collect DBCC CheckDB data for SQL Server 2012, 2014, 2016 and 2017

Here is the table structure for later versions of SQL Server.

-- table structure for SQL Server 2012, 2014, 2016 and 2017
CREATE TABLE [dbo].[dbcc_history](
[Error] [int] NULL,
[Level] [int] NULL,
[State] [int] NULL,
[MessageText] [varchar](7000) NULL,
[RepairLevel] [int] NULL,
[Status] [int] NULL,
[DbId] [int] NULL,
[DbFragId] [int] NULL,
[ObjectId] [int] NULL,
[IndexId] [int] NULL,
[PartitionID] [int] NULL,
[AllocUnitID] [int] NULL,
[RidDbId] [int] NULL,
[RidPruId] [int] NULL,
[File] [int] NULL,
[Page] [int] NULL,
[Slot] [int] NULL,
[RefDbId] [int] NULL,
[RefPruId] [int] NULL,
[RefFile] [int] NULL,
[RefPage] [int] NULL,
[RefSlot] [int] NULL,
[Allocation] [int] NULL,
[TimeStamp] [datetime] NULL CONSTRAINT [DF_dbcc_history_TimeStamp] DEFAULT (GETDATE())
) ON [PRIMARY]
GO

Here is the code to collect the data.

/****** Object: StoredProcedure [dbo].[usp_CheckDBIntegrity] Created by Robert Pearl ******/
/****** for SQL Server 2012, 2014, 2016 and 2017 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROC [dbo].[usp_CheckDBIntegrity]
@database_name SYSNAME=NULL
AS
IF @database_name IS NULL -- Run against all databases
BEGIN
   DECLARE database_cursor CURSOR FOR
   SELECT name 
   FROM sys.databases db
   WHERE name NOT IN ('master','model','msdb','tempdb') 
   AND db.state_desc = 'ONLINE'
   AND source_database_id IS NULL -- REAL DBS ONLY (Not Snapshots)
   AND is_read_only = 0

   OPEN database_cursor
   FETCH next FROM database_cursor INTO @database_name
   WHILE @@FETCH_STATUS=0
   BEGIN

      INSERT INTO dbcc_history ([Error], [Level], [State], MessageText, RepairLevel, [Status], 
      [DbId], DbFragId, ObjectId, IndexId, PartitionId, AllocUnitId, RidDbId, RidPruId, [File], Page, Slot, 
      RefDbId, RefPruId, RefFile, RefPage, RefSlot,Allocation)
      EXEC ('dbcc checkdb(''' + @database_name + ''') with tableresults')

      FETCH next FROM database_cursor INTO @database_name
   END

   CLOSE database_cursor
   DEALLOCATE database_cursor
END 

ELSE -- run against a specified database (ie: usp_CheckDBIntegrity 'DB Name Here'

   INSERT INTO dbcc_history ([Error], [Level], [State], MessageText, RepairLevel, [Status], 
   [DbId], DbFragId, ObjectId, IndexId, PartitionId, AllocUnitId, RidDbId, RidPruId, [File], Page, Slot, 
   RefDbId, RefPruId, RefFile, RefPage, RefSlot,Allocation)
   EXEC ('dbcc checkdb(''' + @database_name + ''') with tableresults')
GO 

Collect the Data

Once the table and stored procedure are created, you can run the proc with the following code:

EXEC usp_CheckDBIntegrity 'MyDatabase' -- specifies particular database, otherwise ALL DBS
GO

Schedule a Job

For recommended on-going database maintenance, navigate SSMS to the 'Jobs' folder under SQL Server Agent, and right-click 'New Job'

navigate ssms to the jobs tab under sql server agent

Name the job appropriately, and select 'Steps' and then click NEW at the bottom-left hand corner. The 'New Job Step' window will open. Give the step a name. As shown below, select the database where you created the stored proc, and in the command box type "Exec usp_CheckDBIntegrity 'MyDatabase'", substituting this for the db you want to schedule the checkdb to run against. Click OK, and then goto 'Schedule' to schedule the job.

in the command box type exec usp_checkdbintegrity my database

Analyze Data

Once the job has completed, you should see data in your table 'dbcc_history'. You can query the table to show the pertinent info. I have included here, the error no, severity level, the database and object name, as well as the timestamp column.

-- for SQL 2005, 2008 and 2008 R2
SELECT Error, LEVEL, DB_NAME(dbid) AS DBName, OBJECT_NAME(id,dbid) AS ObjectName, Messagetext, TimeStamp
FROM dbcc_history

-- for SQL 2012, 2014, 2016 and 2017
SELECT Error, LEVEL, DB_NAME(dbid) AS DBName, OBJECT_NAME(objectid,dbid) AS ObjectName, Messagetext, TimeStamp
FROM dbcc_history

The output should look like this:

query the table dbcc_history to see your data

If there are no errors, it will return the number of rows and pages in each object otherwise you will see the error messages for that object.

You can refine your query and filter out data for a particular error, database, time range, object, etc. If you wanted to simply return the overall outcome of the dbcc checkdb, you can query 'where error=8989'

SELECT Error, LEVEL, DB_NAME(dbid) AS DBName, Messagetext, TimeStamp
FROM dbcc_history
WHERE Error = 8989
refine your query as needed
Next Steps
  • Read this previous tip, SQL Server Database Integrity Checks Checklist, which will address some of the items you should consider when putting your integrity check process in place.
  • SQL Server 2005 offers a new option called 'DATA_PURITY' to the DBCC CHECKDB and DBCC CHECKTABLE commands. Read about it here.
  • You can also refer to the Microsoft TechNet Reference on DBCC CHECKDB.
  • You can actually download sample corrupt databases by clicking on the highlighted link and run the Check Database Integrity process against them.


sql server categories

sql server webinars

subscribe to mssqltips

sql server tutorials

sql server white papers

next tip



About the author
MSSQLTips author Robert Pearl Robert Pearl is a SQL MVP, and President of Pearl Knowledge Solutions, Inc., offering SQLCentric monitoring and DBA services.

This author pledges the content of this article is based on professional experience and not AI generated.

View all my tips


Article Last Updated: 2018-05-03

Comments For This Article




Friday, November 10, 2023 - 11:36:27 AM - Alex Marler Back To Top (91747)
Many people have complained that databases are often skipped during the execution of this within a SQL Agent Job.

The cursor needs to be defined as a "static" cursor -- the default in this case is "updateable".

Just add this line after "Cursor....
LOCAL FORWARD_ONLY STATIC READ_ONLY
FOR..."

SQL Server MVP Paul White explains in detail why this is happening. It has to do with referencing sys.databases view.
https://dba.stackexchange.com/questions/261540/cursoring-over-sys-databases-skips-databases

Monday, April 13, 2020 - 12:20:53 PM - AmiW Back To Top (85353)

I set it up on MSSQL 2017. When I execute the job manually, it'll run the checks on all DBs on the instance. However, when it runs on a schedule, it just runs 1 or 2 databases and quits.

Any ideas what's the issue?


Friday, January 24, 2020 - 6:59:15 PM - Jeremy Mitts Back To Top (83983)

[PartitionID] [bigint] NULL,
[AllocUnitID] [bigint] NULL,

These are both big ints for all versions that support tableresults.

This vb.net code will show you the correct column types.

Sub Main()

Dim con As New SqlClient.SqlConnection
con.ConnectionString = "your connection string here."
con.Open()

Dim da As New SqlClient.SqlDataAdapter("DBCC checkdb (master) WITH TABLERESULTS", con)

Dim ds As New DataSet("DS")

da.Fill(ds, "output")

For Each table In ds.Tables
For Each column In table.columns
Console.WriteLine(column.ColumnName + ": " + column.datatype.name)
Next
Next

End Sub


Friday, December 6, 2019 - 5:10:10 PM - Tim Back To Top (83313)

I'm using SQL Server 2012 and the dbcc_history table definition works fine when there is no corruption. However, I had a database that was corrupt and got some errors:

Error converting data type nvarchar to int.

Error converting data type bigint to int.

RepairLevel is actually nvarchar (not int). I don't know how to tell the size.

Also, PartitionID and AllocUnitID are bigint.


Friday, January 11, 2019 - 4:01:14 PM - Miles Crowson Back To Top (78745)

 Thanks for this, it is great!!


Sunday, May 6, 2018 - 9:38:56 AM - Eliyahu Back To Top (75875)

 

Thanks, it worked nicely


Thursday, May 3, 2018 - 5:11:50 PM - Eliyahu Back To Top (75860)

 Great, looking forward to trying it, hopefuly on Sunday. Thank you!

 


Thursday, May 3, 2018 - 10:13:56 AM - Greg Robidoux Back To Top (75855)

Eliyahu,

the code has been updated.

-Greg


Thursday, May 3, 2018 - 9:49:56 AM - Greg Robidoux Back To Top (75854)

Eliyahu,

I will have a working version for 2016 out pretty soon.  

-Greg


Thursday, May 3, 2018 - 9:32:31 AM - Eliyahu Back To Top (75853)

 2016

 


Thursday, May 3, 2018 - 9:27:08 AM - Greg Robidoux Back To Top (75852)

Hi Eliyahu,

what version of SQL Server are you using?

-Greg


Thursday, May 3, 2018 - 9:23:01 AM - Eliyahu Back To Top (75851)

Thank you for the article but please update it. I just wasted a few valuable hours in the production environment just to receive the "Column name or number of supplied values does not match table definition" error. It is frustrating.

 


Monday, February 26, 2018 - 5:46:35 PM - Lora Back To Top (75302)

Thank you Robert Pearl and to those who have contributed to changes/fixes.

I have added one more column to my table, TimeStampStart, so that I can capture the begin time.  I would like to use this column to calculate the Duration of the DBCC CheckDB per Database.  I have some that run in a few minutes, and others that run for hours.

I've added a new column TimeStampStart to the table.  In the SP, I've SET @StartTime = GETDATE().  Now I need to get that value into the INSERT statement, but I'm stumped. 

 

Any ideas?


Tuesday, July 12, 2016 - 8:23:22 AM - Lavanya Back To Top (41869)

 

 

Hello Greg,

 

Thanks for the post!

But I am getting the below error:

 


Column name or number of supplied values does not match table definition.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.

 

I have replaced 'Mydatabase' with the actual database name!

 

Regards,

Lavanya

 


Monday, March 14, 2016 - 3:08:26 PM - Greg Robidoux Back To Top (40935)

Hi Bea,

I just ran this on SQL Server 2012 and noticed that the column output is different than what is in the above stored procedure.

You can run the command below to see the column differences and adjust the stored procedure to accomodate these columns.

dbcc checkdb('AdventureWorks2012') with tableresults

I will see if we can get the author to update this tip to work with later versions of SQL Server.

Thanks
Greg


Monday, March 14, 2016 - 3:04:56 PM - Bea Isabelle Back To Top (40934)

use DBA_ADMIN
GO
EXEC dbo.usp_CheckDBIntegrity 'AdventureWorks2012'

Msg 213, Level 16, State 7, Line 3
Column name or number of supplied values does not match table definition.
DBCC execution completed. If DBCC printed error messages, contact your system administrator.

 


Saturday, March 12, 2016 - 8:32:50 PM - Greg Robidoux Back To Top (40922)

Hi Bea,

when you run the command are you putting the name of your database in place of 'mydatabase'?

-Greg


Friday, March 11, 2016 - 7:28:37 PM - Bea Isabelle Back To Top (40919)

 Hi,

I have a SQL 2012 database and ran the script to create the table and stored procedure but when I try and run the command EXEC usp_CheckDBIntegrity 'mydatabase', I get the error: Msg. 213, Level 16, State 7, Line 1 Column name or number of supplied values does not match the table definition.  I see the TimeStamp column is a constraint with GetDate() as the default so I'm not sure why I'm getting this error.  All the columns of the table match the imput values in the stored procedure, minus the TimeStamp column.

This is a great idea and is exactly what I need to setup so I'm hoping I can get this work.  Any ideas?

 

 

 

 

 


Wednesday, June 10, 2015 - 2:31:27 AM - Muhammad Khalil Back To Top (37881)

Thanks for sharing it. It is the perfect solution i was looking for.

Thanks


Tuesday, March 31, 2015 - 3:47:54 PM - James Back To Top (36784)

How would I go about adding a per server email summary upon the beginning and completion of DBCC CHECKDB, failure notifications (both per database and then an overall job summary indicating errors) with DBMail? Have you considered adding TRY/CATCH blocks to this code?


Tuesday, February 24, 2015 - 1:21:34 PM - DMason Back To Top (36332)

Thanks for sharing, Robert.  The article helped me a lot.  Like some of the other commenters, I had to change column [RepairLevel] from an INT to a VARCHAR in the table.  Note: my enivronment is SQL 2008 R2 SP3.

 

BTW, there is a known issue when attempting to run DBCC CHECKDB within a TRY block.


Tuesday, November 26, 2013 - 10:44:52 AM - sqlep Back To Top (27609)

as would apply with checktable? I want to save the results in a table checktable


Wednesday, September 18, 2013 - 8:32:36 PM - Kurt Back To Top (26851)

Create the table as follows to clean up errors when corruption is detected:

 

CREATE TABLE [dbo].[dbcc_history](
[Error] [int] NULL,
[Level] [int] NULL,
[State] [int] NULL,
[MessageText] [varchar](7000) NULL,
[RepairLevel] [nvarchar] (25) NULL,
[Status] [int] NULL,
[DbId] [int] NULL,
[Id] [int] NULL,
[IndId] [int] NULL,
[PartitionID] [bigint] NULL,
[AllocUnitID] [bigint] NULL,
[File] [int] NULL,
[Page] [int] NULL,
[Slot] [int] NULL,
[RefFile] [int] NULL,
[RefPage] [int] NULL,
[RefSlot] [int] NULL,
[Allocation] [int] NULL,
[TimeStamp] [datetime] NULL CONSTRAINT [DF_dbcc_history_TimeStamp] DEFAULT (GETDATE())
) ON [PRIMARY]
GO


Sunday, January 27, 2013 - 6:24:58 AM - Imrane Back To Top (21732)

Hi there

Works fine on v2012 with extra column --> [ObjectId] [int] NULL,

v2012

CREATE TABLE [dbo].[dbcc_history](
[Error] [int] NULL,
[Level] [int] NULL,
[State] [int] NULL,
[MessageText] [varchar](7000) NULL,
[RepairLevel] [int] NULL,
[Status] [int] NULL,
[DbId] [int] NULL,
[DbFragId] [int] NULL,
[ObjectId] [int] NULL,
[IndexId] [int] NULL,
[PartitionID] [int] NULL,
[AllocUnitID] [int] NULL,
[RidDbid] [int] NULL,
[RidPruid] [int] NULL,
[File] [int] NULL,
[Page] [int] NULL,
[Slot] [int] NULL,
[RefDbId] [int] NULL,
[RefPruId] [int] NULL,
[RefFile] [int] NULL,
[RefPage] [int] NULL,
[RefSlot] [int] NULL,
[Allocation] [int] NULL,
[TimeStamp] [datetime] NULL CONSTRAINT [DF_dbcc_history_TimeStamp] DEFAULT (GETDATE())
) ON [PRIMARY]
GO

 

CREATE PROC [dbo].[usp_CheckDBIntegrity]
@database_name SYSNAME=NULL
AS
IF @database_name IS NULL -- Run against all databases
BEGIN
DECLARE database_cursor CURSOR FOR
SELECT name
FROM sys.databases db
WHERE name NOT IN ('master','model','msdb','tempdb')
AND db.state_desc = 'ONLINE'
AND source_database_id IS NULL -- REAL DBS ONLY (Not Snapshots)
AND is_read_only = 0

OPEN database_cursor
FETCH next FROM database_cursor INTO @database_name
WHILE @@FETCH_STATUS=0
BEGIN

INSERT INTO dbcc_history ([Error], [Level], [State], MessageText, RepairLevel, [Status],
[DbId], [DbFragId],[
ObjectId], [IndexId], PartitionId, AllocUnitId,[RidDbid], [RidPruid],[File], Page, Slot, [RefDbId], [RefPruId], RefFile, RefPage,
RefSlot,Allocation)
EXEC ('dbcc checkdb(''' + @database_name + ''') with tableresults')

FETCH next FROM database_cursor INTO @database_name
END

CLOSE database_cursor
DEALLOCATE database_cursor
END

ELSE -- run against a specified database (ie: usp_CheckDBIntegrity 'DB Name Here'

INSERT INTO dbcc_history ([Error], [Level], [State], MessageText, RepairLevel, [Status],
[DbId], [DbFragId], [
ObjectId],[IndexId], PartitionId, AllocUnitId,[RidDbid], [RidPruid],[File], Page, Slot, [RefDbId], [RefPruId], RefFile, RefPage,
RefSlot,Allocation)
EXEC ('dbcc checkdb(''' + @database_name + ''') with tableresults')
GO

 


Tuesday, January 15, 2013 - 12:06:34 PM - pjc Back To Top (21462)

Hello

The RepairLevel field in the DBCC_HISTORY table is created as an INT. When the DBCC CHECKDB command runs if there are no problems then this field remains as a NULL, so it doesn't really matter. However, if the DBCC CHECKDB finds any corruption in the database, it will try to insert a VARCHAR value into the RepairLevel field which will cause the insert to fail.

Values which go into the RepairLevel field are along the lines of...

repair_rebuild
repair_fast

A couple of the other fields have also been created as INT and should be BIGINT.

Great document though.

Thanks


Thursday, January 10, 2013 - 10:13:03 AM - Jim Back To Top (21372)

for Sql Server 2012

 

CREATE TABLE [dbo].[dbcc_history](
[Error] [int] NULL,
[Level] [int] NULL,
[State] [int] NULL,
[MessageText] [varchar](7000) NULL,
[RepairLevel] [int] NULL,
[Status] [int] NULL,
[DbId] [int] NULL,
[DbFragId] [int] NULL,
[IndexId] [int] NULL,
[PartitionID] [int] NULL,
[AllocUnitID] [int] NULL,
[RidDbid] [int] NULL,
[RidPruid] [int] NULL,
[File] [int] NULL,
[Page] [int] NULL,
[Slot] [int] NULL,
[RefDbId] [int] NULL,
[RefPruId] [int] NULL,
[RefFile] [int] NULL,
[RefPage] [int] NULL,
[RefSlot] [int] NULL,
[Allocation] [int] NULL,
[TimeStamp] [datetime] NULL CONSTRAINT [DF_dbcc_history_TimeStamp] DEFAULT (GETDATE())
) ON [PRIMARY]
GO

 

CREATE PROC [dbo].[usp_CheckDBIntegrity]
@database_name SYSNAME=NULL
AS
IF @database_name IS NULL -- Run against all databases
BEGIN
   DECLARE database_cursor CURSOR FOR
   SELECT name
   FROM sys.databases db
   WHERE name NOT IN ('master','model','msdb','tempdb')
   AND db.state_desc = 'ONLINE'
   AND source_database_id IS NULL -- REAL DBS ONLY (Not Snapshots)
   AND is_read_only = 0

   OPEN database_cursor
   FETCH next FROM database_cursor INTO @database_name
   WHILE @@FETCH_STATUS=0
   BEGIN
  
       INSERT INTO dbcc_history ([Error], [Level], [State], MessageText, RepairLevel, [Status],
       [DbId], [DbFragId], [IndexId], PartitionId, AllocUnitId,[RidDbid], [RidPruid],[File], Page, Slot, [RefDbId], [RefPruId], RefFile, RefPage,
       RefSlot,Allocation)
       EXEC ('dbcc checkdb(''' + @database_name + ''') with tableresults')

       FETCH next FROM database_cursor INTO @database_name
   END

   CLOSE database_cursor
   DEALLOCATE database_cursor
END

ELSE -- run against a specified database (ie: usp_CheckDBIntegrity 'DB Name Here'

    INSERT INTO dbcc_history ([Error], [Level], [State], MessageText, RepairLevel, [Status],
       [DbId], [DbFragId], [IndexId], PartitionId, AllocUnitId,[RidDbid], [RidPruid],[File], Page, Slot, [RefDbId], [RefPruId], RefFile, RefPage,
       RefSlot,Allocation)
   EXEC ('dbcc checkdb(''' + @database_name + ''') with tableresults')
GO

 


Friday, August 31, 2012 - 12:30:10 PM - Vijay Back To Top (19349)

hiiiiiiiiiiiiiiiiiiii

 

 I am sql dba beginer.  pls forward  frequntly using DBCC COMMANDS with syntax. 

 

Thank you


Wednesday, July 11, 2012 - 7:17:53 AM - Morne Back To Top (18439)

 

 

Hello,

 

New SQL and need to setup a maintenance task. Have tried to create that table but no luck, Please what am I doing wrong.

 

 

M

 

 


Thursday, July 5, 2012 - 2:54:46 PM - rick Back To Top (18364)

thanks much for this.  my only suggestion would be the bigint datatype fix (which I had to do because corrupt dbs were not writing to the history table) and variables/code for logging to a remote database rather than localhost.


Wednesday, July 4, 2012 - 8:50:27 AM - Sharon Smith Back To Top (18341)

 

Thank you for this.  I was struggling to find how to capture the output to a file.

Regards,

Sharon


Tuesday, March 20, 2012 - 7:42:58 PM - bpnchan Back To Top (16549)

 

HI there,

I am running SQL Server 2008 and implemented this stored procedure, and would like to share some experience. Overall, I love the solution that it record the results, if a few concerns is addressed, this is just prefect in my opinion.

I got the same issue here like JPG. Sometime, in random maner, a few of databases was skipped for the check. I am thinking if this is to do with the cursor and the timing when it was executed. I am still investigating it because it does not happen regaularly.

On the other hand, I have a rare issue returned over the runtime for some specific databases, where the stored procedure failed on the following error.

[SQLSTATE 01000] (Message 2528)  Error converting data type bigint to int. [SQLSTATE 42000] (Error 8114)  DBCC execution completed. If DBCC printed error messages, contact your system administrator. [SQLSTATE 01000] (Error 2528).  The step failed.

The difference on these databases are that they are at the compatability level for sql 2000 (80). Have a change request to increase them all to SQL 2008 (100), so will update here once this in place.

bpnchan

 


Sunday, February 12, 2012 - 9:04:27 PM - JPG Back To Top (15996)

Probably most people will say -  this guy is smoking pot.  Perfectly acceptable to me :-) 

 

But when I run this script -- why does the cursor skip some Databases.

We have large DBs and all DBs together take about 24 - 36 hours to complete (if it ever did).

But the script skips some DBs.  When I comment out the 'Execute DBCC' and do a Print DBName (variable) -- I get all DB names.  Funny isnt it?

But any reason anybody can think ?

 


Thursday, April 14, 2011 - 12:07:41 PM - Fabrizio Arrigucci Back To Top (13613)

Thank you is very helpful.

I ran into an error when i tried to run the SP. If you have a corrput Database the Column [RepairLevel] has an invalid Datatype. The Datatype should be varchar. The Output of DBCC for the mentioned Column is 'REPAIR_ALLOW_DATA_LOSS or REPAIR_FAST or REPAIR_REBUILD'

Thanks


Thursday, March 3, 2011 - 4:47:21 PM - admin Back To Top (13115)

The link has been fixed.

Thanks for pointing this out.


Thursday, March 3, 2011 - 4:44:27 PM - Martin Lundblad Back To Top (13114)

Thanks for the post.  This gives me a good place to start.  There is a broiken link at the bottom of the page. (SQL Server Database Integrity Checks Checklist)


Thursday, March 3, 2011 - 2:40:39 PM - Kay Back To Top (13113)

Nice post


Wednesday, March 2, 2011 - 2:17:16 PM - Dave Stokes Back To Top (13098)

Thanks for the great post.  I ran into an error when I tried to run the SP ("Failed to convert Bigint to int").  I changed the datatype for the PartionID and the AllocUnitID to bigint and it worked great.  Thanks again!















get free sql tips
agree to terms