Md Mominul Islam | Software and Data Enginnering | SQL Server, .NET, Power BI, Azure Blog

while(!(succeed=try()));

LinkedIn Portfolio Banner

Latest

Home Top Ad

Responsive Ads Here

Tuesday, September 2, 2025

Fix SQL Server Error 824: Resolve Page-Level Corruption with DBCC CHECKDB

 

Introduction

SQL Server Error 824: SQL Server detected a logical consistency-based I/O error: incorrect pageid (expected 1:123; actual 0:0), incorrect checksum, torn page, or other page-level corruption indicates page-level corruption in a database, often due to hardware issues, disk errors, or I/O subsystem failures. Running DBCC CHECKDB is the primary tool to diagnose and repair corruption. This guide provides code-oriented solutions to resolve Error 824, including steps to run DBCC CHECKDB, repair corruption, and prevent future issues.


1. Run DBCC CHECKDB to Diagnose Corruption

Use DBCC CHECKDB to identify the extent and location of the corruption.

Code-Oriented Solution

Run DBCC CHECKDB to diagnose the database:

-- Run DBCC CHECKDB with informational messages
USE YourDatabaseName;
GO
DBCC CHECKDB WITH NO_INFOMSGS, ALL_ERRORMSGS;

Action:

  • Review the output for details about corrupted objects, pages, or tables.

  • Save the output to a file for analysis:

-- Save DBCC CHECKDB output to a file
DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS
INTO YourDatabaseName_CheckDB_Output;
  • If DBCC CHECKDB cannot run due to severe corruption, try checking specific tables:

-- Check a specific table
DBCC CHECKTABLE ('YourTableName') WITH NO_INFOMSGS, ALL_ERRORMSGS;

Why? Error 824 indicates page-level corruption, and DBCC CHECKDB identifies affected objects and the severity of the issue.


2. Backup the Database Before Repair

Create a full backup and a tail-log backup to preserve data before attempting repairs.

Code-Oriented Solution

Backup the database:

-- Full database backup
BACKUP DATABASE YourDatabaseName
TO DISK = 'C:\SQLBackups\YourDatabaseName_Full.bak'
WITH INIT;

-- Tail-log backup (if in FULL recovery model)
BACKUP LOG YourDatabaseName
TO DISK = 'C:\SQLBackups\YourDatabaseName_TailLog.trn'
WITH NO_TRUNCATE;

Action:

  • Verify the backup:

-- Verify backup
RESTORE VERIFYONLY
FROM DISK = 'C:\SQLBackups\YourDatabaseName_Full.bak';
  • Store backups in a secure location to avoid overwriting.

Why? Backups ensure data can be restored if repairs cause data loss.


3. Attempt Repair with DBCC CHECKDB

Use DBCC CHECKDB with repair options to fix corruption, but note that repairs may result in data loss.

Code-Oriented Solution

Set the database to single-user mode and attempt repair:

-- Set database to single-user mode
ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

-- Run repair with data loss (use cautiously)
DBCC CHECKDB ('YourDatabaseName', REPAIR_ALLOW_DATA_LOSS) WITH NO_INFOMSGS, ALL_ERRORMSGS;

-- Return to multi-user mode
ALTER DATABASE YourDatabaseName SET MULTI_USER;

Try a less aggressive repair option first:

-- Try repair without data loss
DBCC CHECKDB ('YourDatabaseName', REPAIR_REBUILD) WITH NO_INFOMSGS, ALL_ERRORMSGS;

Action:

  • Start with REPAIR_REBUILD (no data loss) if errors are limited to indexes.

  • Use REPAIR_ALLOW_DATA_LOSS only as a last resort, as it may delete corrupted pages or data.

  • After repair, re-run DBCC CHECKDB to confirm all issues are resolved:

DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS, ALL_ERRORMSGS;

Why? DBCC CHECKDB with repair options can fix corruption, but REPAIR_ALLOW_DATA_LOSS may remove data to restore consistency.


4. Restore from Backup

If repair is not feasible or causes significant data loss, restore the database from a backup.

Code-Oriented Solution

Restore the database and apply transaction logs:

-- Restore full backup
RESTORE DATABASE YourDatabaseName
FROM DISK = 'C:\SQLBackups\YourDatabaseName_Full.bak'
WITH NORECOVERY;

-- Restore tail-log backup
RESTORE LOG YourDatabaseName
FROM DISK = 'C:\SQLBackups\YourDatabaseName_TailLog.trn'
WITH RECOVERY;

Action:

  • If no recent backup exists, attempt to extract data from corrupted tables:

-- Export data from a corrupted table to a new table
SELECT * INTO NewTable
FROM YourCorruptedTable
WHERE 1 = 1; -- Use WHERE to filter out corrupted rows if possible
  • Verify the restored database:

DBCC CHECKDB ('YourDatabaseName') WITH NO_INFOMSGS;

Why? Restoring from a backup is the safest way to recover a database without risking data loss from repairs.


5. Investigate Hardware or I/O Issues

Check for underlying hardware or disk issues causing corruption.

Code-Oriented Solution

Check Windows Event Viewer for disk errors:

# View disk-related errors
Get-WinEvent -LogName System | Where-Object { $_.Id -eq 7 -or $_.Id -eq 51 } | Select-Object TimeCreated, Message

Check SQL Server error log for I/O errors:

-- Read error log for I/O or corruption issues
EXEC xp_readerrorlog 0, 1, N'824', NULL, NULL, NULL, N'asc';

Action:

  • Run disk diagnostics (e.g., chkdsk):

# Check disk for errors
chkdsk C: /f
  • Contact your system administrator to check RAID controllers, disk health, or storage systems.

  • Move database files to a different, reliable disk:

-- Detach database
EXEC sp_detach_db 'YourDatabaseName';

-- Move files to new disk (manually via file system)

-- Re-attach database
EXEC sp_attach_db 
    @dbname = 'YourDatabaseName',
    @filename1 = 'D:\NewSQLData\YourDatabase.mdf',
    @filename2 = 'D:\NewSQLData\YourDatabase.ldf';

Why? Error 824 is often caused by hardware failures, disk errors, or I/O subsystem issues.


6. Rebuild Corrupted Indexes

If corruption is limited to indexes, rebuild them to avoid data loss.

Code-Oriented Solution

Identify corrupted indexes:

-- Check specific table for corruption
DBCC CHECKTABLE ('YourTableName') WITH NO_INFOMSGS, ALL_ERRORMSGS;

Rebuild indexes:

-- Rebuild all indexes on a table
ALTER INDEX ALL ON YourTableName REBUILD;

Action:

  • If DBCC CHECKDB reports index corruption, rebuild only the affected indexes:

-- Rebuild specific index
ALTER INDEX IX_YourIndexName ON YourTableName REBUILD;
  • Verify after rebuilding:

DBCC CHECKTABLE ('YourTableName') WITH NO_INFOMSGS;

Why? Rebuilding indexes fixes non-clustered index corruption without affecting data.


7. Implement Corruption Prevention Strategies

Set up monitoring and maintenance to prevent future corruption.

Code-Oriented Solution

Schedule regular DBCC CHECKDB checks:

-- Create SQL Server Agent job for DBCC CHECKDB
USE msdb;
GO
EXEC sp_add_job @job_name = 'DBCC_CheckDB_Weekly';
EXEC sp_add_jobstep 
    @job_name = 'DBCC_CheckDB_Weekly',
    @step_name = 'Run_DBCC_CHECKDB',
    @subsystem = 'TSQL',
    @command = 'DBCC CHECKDB (YourDatabaseName) WITH NO_INFOMSGS, ALL_ERRORMSGS;';
EXEC sp_add_jobschedule 
    @job_name = 'DBCC_CheckDB_Weekly',
    @name = 'WeeklyCheck',
    @freq_type = 8, -- Weekly
    @freq_interval = 1, -- Sunday
    @active_start_time = 20000; -- 2:00 AM

Enable page checksums:

-- Ensure page checksums are enabled
ALTER DATABASE YourDatabaseName
SET PAGE_VERIFY CHECKSUM;

Action:

  • Schedule weekly DBCC CHECKDB runs to detect corruption early.

  • Ensure regular full and transaction log backups:

-- Schedule full backup
BACKUP DATABASE YourDatabaseName
TO DISK = 'C:\SQLBackups\YourDatabaseName_Full.bak'
WITH INIT;
  • Monitor disk health using server tools or third-party monitoring software.

Why? Proactive checks and backups minimize the risk and impact of corruption.


8. Test with SQLCMD or SSMS

Test database operations to confirm resolution.

Code-Oriented Solution

Test with sqlcmd:

# Test database access
sqlcmd -S sqlserverhostname -U YourLoginName -P YourPassword -d YourDatabaseName -Q "SELECT TOP 1 * FROM YourTableName"

In SSMS, run a test query:

-- Test table access
SELECT TOP 1 * FROM YourTableName;

Action:

  • If errors persist, recheck DBCC CHECKDB output or restore from a backup.

  • Update application code to handle corruption errors:

using System.Data.SqlClient;

string connString = "Server=sqlserverhostname;Database=YourDatabaseName;Integrated Security=True;";
try {
    using (SqlConnection conn = new SqlConnection(connString)) {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand("SELECT TOP 1 * FROM YourTableName", conn)) {
            using (SqlDataReader reader = cmd.ExecuteReader()) {
                while (reader.Read()) {
                    Console.WriteLine("Data retrieved successfully!");
                }
            }
        }
    }
} catch (SqlException ex) when (ex.Number == 824) {
    Console.WriteLine("Error 824: Page-level corruption detected. Run DBCC CHECKDB.");
} catch (Exception ex) {
    Console.WriteLine($"Error: {ex.Message}");
}

Why? Testing confirms the database is accessible and corruption is resolved.


Conclusion

SQL Server Error 824 (page-level corruption) can be resolved by running DBCC CHECKDB to diagnose and repair corruption, restoring from backups, or rebuilding indexes. Address underlying hardware issues and implement regular maintenance to prevent recurrence. Use the provided T-SQL, PowerShell, and C# examples to diagnose and fix the issue systematically. 

No comments:

Post a Comment

Thanks for your valuable comment...........
Md. Mominul Islam