Sql server detected a logical consistency based i o error incorrect checksum

Поврежденная база данных — это, наверное, один из худших ночных кошмаров большинства администраторов баз данных. Результатом повреждения являются простои, вопли...

Поврежденная база данных — это, наверное, один из худших ночных кошмаров большинства администраторов баз данных. Результатом повреждения являются простои, вопли менеджеров и всякие другие неприятные штуки.
В этой статье я объясню что нельзя делать с поврежденной базой данных и опишу кое-что из того, что должно быть сделано, некоторые виды повреждений и как их можно исправить.

Как обнаружить, что база данных повреждена

Обычно повреждения превосходно обнаруживаются при попытке доступа к поврежденной странице. Запросы, бэкапы или процедуры реиндексации завершаются ошибками с высокими уровнями серьезности.
Вот пара примеров системных сообщений при обнаружении повреждения БД:

SQL Server detected a logical consistency-based I/O error: incorrect checksum (expected: 0xfdff74c9; actual: 0xfdff74cb). It occurred during a read of page (1:69965) in database ID 13 at offset 0x0000002229a000 in file ‘D:DevelopDatabasesBroken1.mdf’.

Attempt to fetch logical page 1:69965 in database 13 failed. It belongs to allocation unit 72057594049069056 not to 281474980642816.

Основная проблема заключается в том, что если проверки целостности базы данных не производятся на постоянной основе, то повреждение может быть обнаружено спустя часы, дни и даже месяцы, после того, как оно образовалось, в тот момент, когда уже сложно будет что-то исправить.
Я не буду описывать ситуацию когда база данных перешла в состояние «suspect» («подозрительная» в русской редакции SQL Server — прим. переводчика). Описание всевозможных причин почему база данных может перейти в «suspect» и множества вариантов исправления этого — тема отдельной статьи, если не книги.

Что делать если база данных все-таки повреждена

  1. Не паниковать
  2. Не отсоединять (detach) ее
  3. Не перезапускать SQL Server
  4. Не начинать восстановление сразу
  5. Запустить проверку целостности
  6. Найти причину
Не паниковать

Самое важное, при обнаружении повреждения БД — это не паниковать. Любые принимаемые решения должны быть тщательно взвешаны, во внимание должны быть приняты все возможные факторы. Чертовски просто ухудшить ситуацию приняв не до конца обдуманное решение.

Не отсоединять базу данных

В большинстве случаев, когда SQL Server обнарживает повреждение базы данных, это означает, что в БД на самом деле есть поврежденные страницы. Попытка убедить SQL Server что это не так, путем отсоединения (detach) и повторного присоединения (attach) БД, бэкапа и последующего восстановления, перезапуска службы SQL Server, либо перезагрузки сервера, не приведет к тому, что ошибка исчезнет.
Если база данных повреждена и SQL Server обнаружит это при присоединении, он не сможет присоединить ее. Есть несколько способов заставить его увидеть эту БД, но намного лучше просто не отсоединять ее.

Не перезапускать SQL Server

Точно так же, как при отсоединении-присоединении, перезапуск службы SQL Server не сможет исправить обнаруженные ошибки (если они есть).
Перезапуск службы может сделать ситуацию хуже. Если SQL Server обнаружит ошибки во время выполнения фазы восстановления (recovery) БД после перезапуска, он пометит ее как «suspect», что сильно усложнит процесс восстановления БД.

Не начинать восстановление сразу

У вас может возникнуть соблазн просто запустить DBCC CHECKDB с одним из «восстановительных» параметров (обычно допускающими потерю данных) и надеяться, что все станет лучше (по моему опыту — первое что рекомендуют на «непрофильных» форумах по SQL Server — запустить DBCC CHECKDB REPAIR_ALLOW_DATA_LOSS — прим. переводчика). Во многих случаях запуск такого восстановления не рекомендуется. Он не гарантирует исправления всех ошибок и может привести к недопустимой потере данных.
Такое восстановление — это последний шаг при исправлении ошибок. Оно должно быть запущено только если у вас уже нет другого выбора, но никак не в первую очередь.

Запустить проверку целостности

Для того чтобы решить как исправить базу данных, мы точно должны знать что именно повреждено. Единственный способ, которым мы можем это выяснить — запустить DBCC CHECKDB с параметром All_ErrorMsgs (в SQL Server 2005 SP3, SQL Server 2008 SP1 и в более старших версиях, этот параметр включен по умолчанию, указывать его не обязательно). Помните, что если вы запустите DBCC CHECKDB без параметра No_InfoMsgs, в выводе этой процедуры будет информация о количестве строк и страниц в каждой таблице, что вряд ли будет вас интересовать при анализе ошибок.
DBCC CHECKDB может долго выполняться на больших БД, но необходимо дождаться пока эта процедура не закончит работу. Грамотная стратегия восстановления может быть построена только при наличии информации обо всех проблемах в БД.

Найти причину

После того как ошибки исправлены, работу нельзя считать законченной. Если причина этих ошибок не установлена, они могут возникнуть снова. Обычно, основной причиной ошибок являются проблемы с подсистемой ввода-вывода, но они также могут быть вызваны неправильной работой «низкоуровнего ПО» (вроде антивируса), действиями человека, либо багами самого SQL Server.

Что дальше

Дальнейшие действия по исправлению ошибок целиком и полностью зависят от результатов выполнения CheckDB. Чуть дальше я покажу несколько наиболее часто возникающих ошибок (учтите, что эта статья не претендует на звание полного описания всевозможных ошибок).
Описанные ошибки располагаются по возрастанию уровня серьезности — от наименее серьезных к наиболее серьезным. В общем-то, для наиболее серьезных ошибок, находимых CheckDB, есть описание доступных методов их резрешения.
Если у вас вдруг обнаружится ошибка не описанная в статье, обратите внимание на последний раздел — «Поиск помощи».

Неверная информация о свободном месте на странице

Msg 2508, Level 16, State 3, Line 1
The In-row data RSVD page count for object «Broken1», index ID 0, partition ID 76911687695381, alloc unit ID 76911687695381 (type In-row data) is incorrect. Run DBCC UPDATEUSAGE.

В SQL Server 2000, количество строк и страниц в таблице или индексе, хранящееся в метаданных, могло не соответствовать действительности (и даже быть отрицательным) и DBCC CHECKDB не видел в этом ничего плохого. В SQL Server 2005, это количество должно быть правильным и CheckDB выдаст предупреждение, если вдруг найдет несоответствие.
Это несерьезная прблема и очень легко разрешается. Как говорится в сообщении, нужно всего лишь запустить DBCC UPDATEUSAGE в контексте нужной БД и предупреждение исчезнет. Эта ошибка часто встречается в базах данных обновленных с SQL Server 2000 и не должна появляться в базах данных, созданных в SQL Server 2005/2008.

Msg 8914, Level 16, State 1, Line 1
Incorrect PFS free space information for page (1:26839) in object ID 181575685, index ID 1, partition ID 293374720802816, alloc unit ID 76911687695381 (type LOB data). Expected value 0_PCT_FULL, actual value 100_PCT_FULL.

Эта ошибка появляется, когда PFS-страница (Page Free Space), которая учитывает насколько заполнены страницы в БД, содержит некорректные значения. Эта ошибка, как и упомянутая ранее, не является серьезной. Алгоритм, по которому определялось насколько заполнены страницы, в SQL Server 2000 не всегда отрабатывал правильно. Для решения этой проблемы нужно запустить DBCC CHECKDB с параметром REPAIR_ALLOW_DATA_LOSS и, если это единственная ошибка в БД, никакие данные, на самом деле, не пострадают.

Повреждение только некластерных индексов

Если все ошибки, найденные CheckDB, относятся к индексам с ID = 2 и больше, это означет, что были повреждены только некластерные индексы. Поскольку информация, содержащаяся в некластерных индексах, является «избыточной» (те же самые данные хранятся в куче, либо в кластерном индексе — прим. переводчика), эти повреждения могут быть исправлены без потери каких-либо данных.
Если все ошибки, найденные CheckDB, относятся к некластерным индексам, рекомендуемый «уровень восстановления» для DBCC CHECKDB — REPAIR_REBUILD. Примеры таких ошибок (на самом деле ошибок такого типа намного больше):

Msg 8941, Level 16, State 1, Line 1
Table error: Object ID 181575685, index ID 4, page (3:224866). Test (sorted [i].offset >= PAGEHEADSIZE) failed. Slot 159, offset 0x1 is invalid.

Msg 8942, Level 16, State 1, Line 1
Table error: Object ID 181575685, index ID 4, page (3:224866). Test (sorted[i].offset >= max) failed. Slot 0, offset 0x9f overlaps with the prior row.

В этом случае, повреждение может быть полностью исправлено удалением поврежденных некластерных индексов и повторным их созданием. Перестроение индекса (ALTER INDEX REBUILD) в режиме on-line (и иногда в off-line) читает страницы старого индекса для создания нового и, следовательно, завершится с ошибкой. Поэтому, необходимо удалить старые индексы и создать их заново.
Именно это сделает DBCC CHECKDB с параметром REPAIR_REBUILD, но база данных при этом должна быть в однопользовательском режиме. Вот почему обычно лучше вручную выполнить эти операции, чтобы с базой данных можно было продолжать работать, пока индексы будут пересоздаваться.
Если у вас недостаточно времени на то, чтобы пересоздать нужные индексы и в наличии есть «чистый» (не содержащий в себе ошибок) полный бэкап и бэкапы журнала транзакций с неразорванной цепочкой журналов, вы можете восстановить поврежденные страницы из них.

Повреждение LOB-страниц

Msg 8964, Level 16, State 1, Line 1
Table error: Object ID 181575685, index ID 1, partition ID 72057594145669120, alloc unit ID 72057594087800832 (type LOB data). The off-row data node at page (1:2444050), slot 0, text ID 901891555328 is not referenced.

Ошибка говорит о том, что существуют LOB-страницы (Large OBject), на которые не ссылается ни одна страница с данными. Такое может произойти, если ранее был поврежден кластерный индекс (или куча) и его поврежденные страницы были удалены.
Если CheckDB говорит только о таких ошибках, то можно запускать DBCC CHECKDB с параметром REPAIR_ALLOW_DATA_LOSS — эти страницы будут уничтожены. Поскольку у вас все равно нет страниц с данными, которые ссылаются на эти страницы, бОльшей потери данных уже не будет.

Ошибки, связанные с выходом за пределы допустимого диапазона

Msg 2570, Sev 16, State 3, Line 17
Page (1:1103587), slot 24 in object ID 34, index ID 1, partition ID 281474978938880, alloc unit ID 281474978938880 (type «In-row data»). Column «modified» value is out of range for data type «datetime». Update column to a legal value.

Эти ошибки показывают, что в столбце есть значения выходящие за пределы допустимого диапазона. Это может быть значение типа datetime, предполагающее, что с полуночи прошло больше 1440 минут, строка-Unicode, в которой количество байт не делится на 2, или float/real с неверным значением точности.
Проверка на эти ошибки не выполняется по умолчанию, для баз данных обновленных с версии SQL Server 2000 или более ранних, если перед этим ни разу не выполнялась команда DBCC CHECKDB со включенным параметром DATA_PURITY.
CheckDB не сможет исправить эти ошибки, поскольку неизвестно какие значения поставить взамен неправильных. Исправление таких ошибок не требует особых усилий, но выполняется вручную. Неправильные значения должны быть заменены на что-нибудь приемлимое. Основная проблема — это поиск неверных значений. В этой статье базы знаний есть пошаговая инструкция.

Повреждение кластерного индекса или кучи

Если обнаруживается, что повреждены страницы кучи или листового уровня (leaf pages) кластерного индекса — это означает, что данные на них потеряны. Страницы листового уровня кластерного индекса содержат непосредственно страницы данных и для них избыточность никак не обеспечивается.
Если CheckDB сообщает о повреждении страниц листового уровня кластерного индекса, необходимый «уровень восстановления» для DBCC CHECKDB — REPAIR_ALLOW_DATA_LOSS.
Примеры таких ошибок:

Server: Msg 8976, Level 16, State 1, Line 2
Table error: Object ID 181575685, index ID 1, partition ID 76911687695381, alloc unit ID 76911687695381 (type In-row data). Page (1:22417) was not seen in the scan although its parent (1:479) and previous (1:715544) refer to it.

Server: Msg 8939, Level 16, State 1, Line 2
Table error: Object ID 181575685, index ID 0, page (1:168576). Test (m_freeData >= PAGEHEADSIZE && m_freeData <= (UINT)PAGESIZE — m_slotCnt * sizeof (Slot)) failed. Values are 44 and 8028.

Следует помнить, что если ошибки, возвращаемые CheckDB, относятся к index id = 0 или 1, это значит, что повреждены непосредственно данные.
Такой тип ошибок исправляется, но исправление заключается в уничтожении строк или целых страниц. Когда CheckDB удаляет данные для исправления ошибки, ограничения, налагаемые внешними ключами, не проверяются и никакие триггеры не срабатывают. Строки или страницы просто удаляются. В результате данные могут оказаться не согласованными, либо может быть нарушена логическая целостность (на LOB-страницы может больше не ссылаться ни одна строка, либо строки некластерного индекса могут указывать «в никуда»). Из-за таких последствий, подобное восстановление, не рекомендуется использовать.
Если у вас есть «чистый» бэкап, восстановление из него обычно является более предпочительным, для исправления таких ошибок. Если база данных находится в полной модели восстановления и у вас есть бэкапы журнала транзакций с неразорванной цепочкой журналов (начиная с последнего «чистого» полного бэкапа), вы можете сделать бэкап активной части лога и восстановить базу данных целиком (или только поврежденные страницы), в результате чего данные вообще не будут потеряны.
Если бэкапа с неповрежденными данными нет, у вас остается только один вариант — запуск DBCC CHECKDB с параметром REPAIR_ALLOW_DATA_LOSS. Это потребует перевода базы данных в однопользовательский режим на все время выполнения этой процедуры.
И хотя у вас нет возможности избежать потери данных, вы можете посмотреть какие данные будут удалены из кластерного индекса. Для этого, посмотрите этот пост Пола Рэнадала.

Повреждение метаданных

Msg 3853, Level 16, State 1, Line 1
Attribute (object_id=181575685) of row (object_id=181575685,column_id=1) in sys.columns does not have a matching row (object_id=181575685) in sys.objects.

Подобные ошибки, обычно, возникают в базах данных, обновленных с SQL Server 2000, когда кто-то ковырялся напрямую в системных таблицах.
В системных таблицах любой версии SQL Server внешние ключи не используются, поэтому в SQL Server 2000 была возможность удалить строку из sysobjects (например, таблицу) и оставить в таблицах syscolumns и sysindexes строки, ссылающиеся на удаленную строку.
В SQL Server 2000 CheckDB не проверял целостность системного каталога и такие проблемы зачастую висели незамеченными. В SQL Server 2005, CheckDB проверяет целостность системного каталога и такие ошибки могут проявиться.
Исправление этих ошибок дело не самое легкое. CheckDB не может их исправить, поскольку единственное что можно сделать — это удалить записи из системных таблиц, что, в свою очередь, может вызвать потерю большого количества данных. Если у вас есть бэкап этой БД, сделанный до обновления на SQL Server 2005 и обновление было совсем недавно, вы можете развернуть его на SQL Server 2000, на нем вручную подправить системные таблицы и снова перенести БД на SQL Server 2005.
Если у вас нет бэкапа БД на SQL Server 2000 или обновление прошло слишком давно и потеря данных неприемлима, есть два пути. Первый — отредактировать системные таблицы в SQL Server 2005, но следует учитывать, что это довольно сложный и рискованный процесс, поскольку системные таблицы не документированы и гораздо более сложны, чем в ранних версиях. В этом посте можно найти дополнительную информацию.
Второй путь — это заскриптовать все объекты БД и экспортировать все данные, после чего создать новую базу данных, восстановить объекты и залить данные. Этот вариант более предпочтителен.

Неисправимые повреждения

CheckDB не может исправить все. Любые ошибки вроде приведенных ниже неисправимы и единственный вариант — это восстановление базы данных из бэкапа, в котором нет этих повреждений. Если у вас есть полный бэкап и цепочка журналов не нарушена до текущего времени, вы можете забэкапить заключительный фрагмент журнала транзакций и база данных может быть восстановлена без потери каких-либо данных.
Если таких бэкапов нет, единственное что вы можете сделать — заскриптовать те объекты и выгрузить те данные, которые еще доступны. Вполне вероятно, что из-за повреждений не все данные будут доступны, и, скорее всего, не все объекты смогут быть заскриптованы без ошибок.

Повреждение системных таблиц

Msg 7985, Level 16, State 2, Line 1
System table pre-checks: Object ID 4. Could not read and latch page (1:358) with latch type SH.
Check statement terminated due to unrepairable error.

Msg 8921, Level 16, State 1, Line 1
Check terminated. A failure was detected while collecting facts. Possibly tempdb out of space or a system table is inconsistent.

CheckDB зависит от нескольких критически важных системных таблиц, для того чтобы получить представление о том, что должно быть в базе данных. Если сами эти таблицы повреждены, то CheckDB не может даже предположить что должно быть в базе данных и с чем сравнить текущее положение дел, не говоря уже о том, чтобы что-то исправить.

Повреждение «карт распределения»

Msg 8946, Level 16, State 12, Line 1
Table error: Allocation page (1:2264640) has invalid PFS_PAGE page header values. Type is 0. Check type, alloc unit ID and page ID on the page.

Msg 8998, Level 16, State 2, Line 1
Page errors on the GAM, SGAM, or PFS pages prevent allocation integrity checks in database ID 13 pages from (1:2264640) to (1:2272727)

В этом случае, одна или несколько страниц определяющих размещение данных в БД (карты распределения — прим. переводчика) повреждены. Эти страницы используются для того чтобы определять какие страницы и экстенты в БД используются, а какие свободны. CheckDB не может исправить такие ошибки, поскольку практически невозможно определить (без этих страниц) какие экстенты используются для размещения данных, а какие нет. Простое удаление такой «карты распределения» невозможно, поскольку удаление любой из них повлечет за собой удаление 4 GB данных.

Поиск помощи

Если вы не уверены в том что вам нужно сделать — обратитесь за помощью. Если вдруг вы получаете сообщение о повреждении БД, которое вам непонятно и которое не описано выше — обратитесь за помощью. Если вы не уверены в том, что выбрали наилучший метод восстановления — обратитесь за помощью.
Если у вас есть Senior DBA, обратитесь к нему. Если у вас есть «наставник» — спросите у него. Спросите совета на форумах, но помните, что не все советы полученные на форумах полезны. На самом деле, именно там время от времени публикуются абсолютно неправильные и даже опасные решения.
Обратитесь в службу поддержки Microsoft, наконец. Это будет небесплатно, но они действительно знают что можно сделать с поврежденной базой данных и вполне вероятно, что если ваша база данных критична для предприятия, то стоимость простоя во время самостоятельного поиска решения будет намного выше чем стоимость обращения в саппорт.

Заключение

В этой статье я дал несколько примеров того, что можно сделать при обнаружении поврежденной БД и, что даже важнее, того, что делать не надо. Надеюсь, что теперь вы лучше понимаете какие методы можно применять для решения описанных проблем и насколько важно иметь хорошие бэкапы (и правильно выбрать модель восстановления — прим. переводчика).

Примечание: это мой первый перевод, который, к тому же делался не за раз, а в несколько подходов, вечерами, когда появлялось свободное время, поэтому текст целиком, возможно, кому-то покажется несколько несогласованым. Если где-то я был излишне косноязычен и какая-то часть текста вдруг окажется трудной для понимания — с радостью выслушаю все замечания.
С уважением, unfilled.
P.S. Когда я уже собрался было нажать на кнопочку «Опубликовать», мне на почту свалилась рассылка от SQL Server Central с вот таким вот комиксом.

Scenario 

The error of “SQL Server detected a logical consistency-based I/O error: incorrect checksum” might occur when you Inserting, reading, updating, backup or generating reports.

“SQL Server detected a logical consistency-based I/O error: incorrect checksum” will occur mostly due to system failed to identify and recognize the data in table

It is always recommended to restore with your latest healthy backup, if you don’t have it then can refer to this guide

Commonly address as database corruption and there are multiple type of corruption as below:

  • SQL page-level corruption: page-level corruption occurs when the information or data stored in the header, body, or slot array of a database page is altered such that the user cannot access the page. Page-level corruption can happen due to reasons like hardware issues, disk/sub-system failure, malware, faulty updates and patches, etc.
  • Boot page corruption: this is a more critical case of SQL database corruption as it concerns the boot page. There is only one boot page per SQL database, and it stores the metadata for the entire database. So, its corruption can affect the whole database file. Further, DBCC CHECKDB or page-level restore cannot fix the boot page corruption. This limitation is given the fact that the boot page stores Meta information like the current version, database ID, checkpoint LSN, etc.
  • Non-clustered index corruption: this type of corruption is associated with SQL Server 2008 and later versions. It typically occurs when a SQL DBA attempts running a complex UPDATE statement with NOLOCK hint against a table. Non-clustered index corruption leads to incorrect reading of the SQL database query or multiple read operations on the same value.
  • SQL database in suspect mode: SQL database suspect mode is a frequent issue DBAs face due to damage in the primary file group file, which stops the database recovery during SQL Server startup. A SQL Server may mark the database in SUSPECT mode after detecting a problem in the log file due to reasons like hardware malfunction, disk space issue, system crash, etc. A database in suspect mode fails to perform the read/write operations leading to downtime.

Solution 

Verify the corruption of database

  1. Connect your database with SSMS (SQL Server Management Studio)

https://support.qne.com.my/a/solutions/articles/81000385373 

  1. Right-click your server instance in Object Explorer, and then select New Query

  1. Paste the following T-SQL code snippet into the query window:
  2. To find out objects that caused “SQL Server detected a logical consistency-based I/O error: incorrect checksum”

——Replace [SampleDB_Testing] to your database name——

USE Master

GO

DBCC CHECKDB (SampleDB_Testing) WITH ALL_ERRORMSGS, NO_INFOMSGS

  1. Execute the query by selecting Execute or selecting F5 on your keyboard.

  1. The results of the query are displayed under the area where the text was entered.
  2. If there aren’t any corruption, it will show “Commands completed successfully”
  3. Else it will show Logical Consistency-Based I/O Error in which table
  4. For our sample, it shows there are 8 unrecognize data in table SalesInvoiceDetails that stored all the detail like Stock Code, Qty, Unit Price and etc. in Sales Invoice transaction that caused “SQL Server detected a logical consistency-based I/O error: incorrect checksum”

Repair / Recover the unrecognize / corrupted data

  1. Right-click your server instance in Object Explorer, and then select New Query

  1. First, we will try to repair “SQL Server detected a logical consistency-based I/O error: incorrect checksum” without data loss
  2. Paste the following T-SQL code snippet into the query window:

——Replace [SampleDB_Testing] to your database name——

USE MASTER

GO

ALTER DATABASE [SampleDB_Testing] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE

GO

USE MASTER

GO

DBCC CHECKDB (SampleDB_Testing, REPAIR_REBUILD) WITH ALL_ERRORMSGS

  1. Execute the query by selecting Execute or selecting F5 on your keyboard.

  1. The results of the query are displayed under the area where the text was entered.
  2. If Repair without data loss success, Bottom of the results will show “DBCC execution completed”
  3. Else will show “REPAIR_ALLOW_DATA_LOSS is the minimum repair level for the errors found”
  4. If such message show, then we have no choice but try to repair “SQL Server detected a logical consistency-based I/O error: incorrect checksum” with data loss
  5. Paste the following T-SQL code snippet into the query window:

——Replace [SampleDB_Testing] to your database name——

USE MASTER

GO

ALTER DATABASE [SampleDB_Testing] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE

GO

USE MASTER

GO

DBCC CHECKDB (SampleDB_Testing, REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS

  1. Execute the query by selecting Execute or selecting F5 on your keyboard.

  1. You can always execute check for corruption query to double check your database after repair

——Replace [SampleDB_Testing] to your database name——

USE Master

GO

DBCC CHECKDB (SampleDB_Testing) WITH ALL_ERRORMSGS, NO_INFOMSGS

  1. If you repaired your corrupted database with allow data loss query for “SQL Server detected a logical consistency-based I/O error: incorrect checksum” then it is recommended to compare your current reports with your previous generated reports to identify and re-entry back the unrecoverable data 

Find out more about Set-up Schedule Backup in QNE Optimum

Find out more about Effective SQL Server Monitoring

Recently, we encountered an issue with a restored database stating the below error message:

Msg 824, Level 24, State 2, Line 28
SQL Server detected a logical consistency-based I/O error: incorrect checksum (expected: 0xafbb455a; actual: 0xaf9a455a).
It occurred during a read of page (1:310732) in database ID 161 at offset 0x00000097b98000 in file ‘F:DATA1database.MDF’.
Additional messages in the SQL Server error log or system event log may provide more detail.
This is a severe error condition that threatens database integrity and must be corrected immediately.
Complete a full database consistency check (DBCC CHECKDB).
This error can be caused by many factors; for more information, see SQL Server Books Online.

As the error message is pretty straight forward, a clear issue with some consistency (I/O error). And this has been even confirmed by running a DBCC CHECKDB. To resolve the issue, we decided to go with REPAIR_ALLOW_DATA_LOSS option as this is a lower environment issue. I personally do not recommend to use this option for production databases as there is a chance of data loss.


alter database <database>  SET single_user with rollback immediate 
dbcc checkdb('<database>',REPAIR_ALLOW_DATA_LOSS)
alter database <database>  SET multi_user with rollback immediate 

Before we do this option, just curious to understand the object being corrupted from the error message.

Using DM_DB_DATABASE_PAGE_ALLOCATIONS

The below code will give you information on the objects. Please note the below is supported only from SQL 2012 and later versions. For earlier version, you need to use DBCC PAGE commands.


SELECT DB_NAME(susp.database_id) DatabaseName,
OBJECT_SCHEMA_NAME(ind.object_id, ind.database_id) ObjectSchemaName,
OBJECT_NAME(ind.object_id, ind.database_id) ObjectName
FROM msdb.dbo.suspect_pages susp
CROSS APPLY SYS.DM_DB_DATABASE_PAGE_ALLOCATIONS(susp.database_id,null,null,null,null) ind
WHERE allocated_page_file_id = susp.file_id
AND allocated_page_page_id = susp.page_id

Later, we identified the issue is associated with backup and we took a fresh backup of the database and restored. It worked like a treat!!!

Multiple Methods to Fix SQL Server Error 824 Severity 24 State 2

“Hello! I am new to this forum. Kindly help me by solving this issue. I have been using SQL Server 2008 R2 for quite some time. Till now there have been no issues and everything was going fine. Only two days back, the SQL Server stopped working. There was no apparent reason and I am still wondering about its cause. When it stopped, an error message appeared that says: ‘SQL Server Detected A Logical Consistency-Based I/O Error: Incorrect Checksum. (Microsoft SQL Server Error 824).’ Please help me to fix this problem. I will be very grateful. Thanks.”

SQL Server is a relational database management system. Due to ease of use and other features, it has gained immense popularity. Therefore, its usage as a database management system is very common. Just because it is full of useful features, does not mean it has no demerits. For SQL Server users, various types of error are not unusual. When SQL database faces any error it usually stops working. So, as an SQL Server user, people have no way to ignore the errors.

For this post, we have chosen to discuss SQL Error 824 Severity 24 State 2. This is a logical consistency related error that occurs frequently to SQL Database users. As readers can see in the beginning, multiple users have asked for the solution to this error. Therefore, we will talk about the symptoms, reasons, and solutions for this error message.

Download Purchase Now

This page-level error usually occurs due to the logical inconsistency of SQL Server. When some issue is detected in the page while performing read/write command. This error appears.

Various information can be found in the SQL error message 824. Once you know the meaning of all parts of the error message, you will have a better understanding of the error.

  • The file belongs to which database
  • I/O operation was performed against which database file
  • Whether the operation was read or write
  • The I/O operation was related to which page number
  • Complete information about the failed logical consistency check (Actual and expected value used for checking, the category of checking, etc.)

Reasons for SQL Error 824

It is not quite easy to determine the exact cause of this error. Many facts can contribute to the occurrence of SQL Server error 824 severity 24 state 2.

  • Insufficient Storage: If the SQL Database does not have sufficient storage space, this error can occur.
  • Driver Issue: The drive (also called hardware) that is located in the I/O path can also be the main culprit behind this error.
  • File System inconsistency: Any sort of inconsistency in the file system can be the cause that user is getting SQL Error 824.
  • Damaged Database: If SQL Server Database is damaged in any way, it will show 824 error while trying to use.
  • Corruption: If the file system is corrupt, SQL Server error message 824 can appear.

How to Fix SQL Server Error 824 Severity 24 State 2

If you have encountered this error message while running SQL Server, you can try these remedial techniques sequentially.

1. Check if any other page (whether in the same or different databases) is having the same error. To do that, review the table in MSDB that contains the suspect pages.
2. You should also check the database consistency with DBCC CHECKDB command. If some issues are found, troubleshoot them. It has to be the database situated in the same volume mentioned in the error 824 error message.
3. If the PAGE_VERIFY CHECKSUM database option is turned off in the database with error 824, turn it on immediately. Though this error can be the result of many reasons, CHECKSUM is the best way to verify page consistency after a page gets written to disk.
4. Go through Windows Event logs to see if any error got reported by Operating System, Device Driver or Storage Device. If the reports or messages are any way connected to error 824, resolve those errors first. Guess, an event like “The driver detected a controller error on DeviceHarddisk4DR4” is present in the event log, being reported by the Disk Source. Then you have to find if the file is located in this device and then resolve the disk errors.
5. There is s built-in utility in SQL Server 2008 named SQLIOSim. It can be used to know if the error can be recreated outside regular SQL I/O requests. Remember to find this utility within SQL Server 2008 and you do not have to download it separately.
6. You have to work in collaboration with hardware vendor or device manufacturer in order to evaluate:

  • If the hardware and their configuration match the requirements of SQL Server IQ.
  • If all hardware (drivers) and software elements of I/O path device are updated or not

7. Proceed to examine I/O path health. If you have any diagnostic utilities provided by the hardware vendor or device manufacturer, use those.
8. Evaluate Filter Drivers existing in I/O requests path that is facing problems:

  • If an update is available for the filter drivers
  • Is it possible to remove or disable filter drivers to check if the error 824 goes away or not

Concluding Words

In this post, we have discussed SQL Server error 824 severity 24 state 2. Since this error can be fatal, users should immediately take necessary steps to get rid of this error. Users can implement the solutions mentioned here and become free from this error. If these methods fail to solve the problem, they can take help of SQL Server database repair utility. This software is capable of solving all types of SQL database corruption.

Frequently Asked Questions

Can I use the DBCC CHECKDB command to repair major level corruption from the SQL database?

You can use the DBCC command to check the damage level of the SQL database. However, it is not able to successfully recover high-level corruption.

What is the best solution to fix SQL database corruption errors?

SQL Recovery is the perfect solution to repair and restore SQL database including all objects like tables, stored procedures, etc.

There can be several reasons that cause Database Logical Consistency based I/O error:

In both the circumstances, the Host instances on SQL server restart repeatedly or terminate the connection between SQL application and the database. The following error message is displayed in SQL Server error log:

SQL Server detected a logical consistency-based I/O error: incorrect pageid (expected 1:1848; actual 0:0). It occurred during a read of page (1:1848) in database ID 10 at offset 0x00000000e70000 in file ‘C:Program FilesMicrosoft SQL ServerMSSQL10.MSSQLSERVERMSSQLDATAABCDb.mdf’.  Additional messages in the SQL Server error log or system event log may provide more detail. This is a severe error condition that threatens database integrity and must be corrected immediately. Complete a full database consistency check (DBCC CHECKDB). This error can be caused by many factors; for more information, see SQL Server Books Online.

When a SQL Server database experiences a logical consistency based error, the first step is to diagnose the cause of error. The following methods can help in detecting the error:

DBCC CHECKDB (ABCD) WITH NO_INFOMSGS, ALL_ERRORMSGS

Executing above command highlights the problem in detail, and SQL database may display the I/O  error message as follows:

Msg 8906, Level 16, State 1, Line 1

Table error: Object ID 0, index ID -1, partition ID 0, alloc unit ID 0 (type Unknown), page ID (1:1846) contains an incorrect page ID in its page header. The PageId in the page header = (0:0).

Method 1 – Check hardware and application connectivity 

Database inconsistency error can be resolved by establishing proper connectivity between the database and SQL application. 

Method 2 — Restore from SQL backup

The most feasible solution is to use backup for SQL database restoration. Before restoring from backup, check that: 

  1. You have a recent full backup
  2. Backup is updated, just prior to corruption, and not long ago so as to avoid critical data loss
  3. Corruption is at page level, as page level corruption issue can be resolved with the help of page-level restoration. 

Note: Page-level restoration is valid when you are dealing with large database and corruption is in only in one-page of SQL database.

Step 1: Use the following command for restoring SQL database from full backup

Backup the transaction log
BACKUP LOG PageLevelRestores TO
DISK = ‘g:PageLevelRestores_LOG1.bak’
WITH INIT
GO

Step 2: Perform the restoration change to reflect the changes online.

Backup the tail of the log…
BACKUP LOG PageLevelRestores TO
DISK = ‘g:PageLevelRestores_LOG_TAIL.bak’
WITH INIT
GO

Note: There is no need to restore full SQL server database if corruption is confined to a single page. You can restore database from the available backup for that page which is corrupted. Performing the following commands will help in restoring backup for a single page:

Restore all available log backups in the correct order
RESTORE LOG PageLevelRestores FROM
DISK = ‘g:PageLevelRestores_LOG1.bak’
WITH NORECOVERY
GO

— Finally restore the tail log backup
RESTORE LOG PageLevelRestores FROM
DISK = ‘g:PageLevelRestores_LOG_TAIL.bak’
WITH NORECOVERY
GO

— Finally finish with the restore sequence
RESTORE DATABASE PageLevelRestores WITH RECOVERY
GO

Once the database backup has restored SQL database, run the query DBCC CHECKDB again to check that the select statement succeeds without SQL Database logical consistency-based I/O error. This command also checks that there is no data loss in this table. 

Limitations of SQL database backup:

  1. It is not possible to restore from SQL database backup when the available backup is obsolete.
  2. If Logical consistency based I/O error is spread across the SQL server database, then this method will not be valid.
  3. For those cases where faulty page exists in a non-clustered index, the SQL database can be fixed by dropping and recreating the index of SQL database. 

Method 3: Repair corrupt SQL database with REPAIR_ALLOW_DATA_LOSS

REPAIR_ALLOW_DATA_LOSS is the minimum repair level for the diagnosed errors. 

Notes: Before using REPAIR_ALLOW_DATA_LOSS, perform the following:

  1. Take a backup of SQL server database and save it with another name
  2. Set SQL database in Single user mode
  3. Get all Tables record count by using the following commands

DECLARE @T_Name VARCHAR(250)

DECLARE @COUNT INT

DECLARE @SQL VARCHAR(2000)

CREATE TABLE #T_Info(ID INT IDENTITY(1,1),T_Name VARCHAR(200),D_Count INT)

DECLARE TINFO_CUR CURSOR FOR

SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

WHERE TABLE_TYPE=’BASE TABLE’

OPEN TINFO_CUR

FETCH NEXT FROM TINFO_CUR INTO @T_Name

WHILE @@FETCH_STATUS =0

BEGIN

SET @SQL=’INSERT INTO #T_Info(T_Name,D_Count) SELECT »’+@T_Name+»’,COUNT(*) FROM ‘+@T_Name+»

EXECUTE (@SQL)

FETCH NEXT FROM TINFO_CUR INTO @T_Name

END

CLOSE TINFO_CUR

DEALLOCATE TINFO_CUR

SELECT * FROM #T_Info ORDER BY T_NAME

The following steps help to fix SQL database and resolve logical consistency based I/O error:

  • Run the command:

DBCC CHECKDB (DB_NAME, REPAIR_ALLOW_DATA_LOSS)

  • Once SQL database is repaired, repeat the process of ‘Table Record Count’ and compare with old record count. 

There must not be any difference between initial and final Table record count. 

Limitations:

REPAIR_ALLOW_DATA_LOSS may fix Database logical consistency-based IO error but there is a major issue of data loss, where an organization may experience loss of critical data. 

Alternative Solution

If above methods won’t work then, give a try to a SQL Recovery Software. Stellar Repair for MS SQL repairs corrupt MDF and NDF files and restores all the database objects. It supports MS SQL 2019 and all the lower versions. 

Conclusion

In this post, we have highlighted the cause of SQL Database logical consistency-based I/O error and the methods to detect this error. 

Based upon the error, we have tried to find the correct resolution method. If hardware or system is responsible for the error, it is recommended to resolve the hardware-related issues, and in case DBCC CHECKDB reports consistency error, then try to restore SQL database by using an updated backup. 

If the issue is not resolved with hardware correction and backup then try to repair the database with the help of REPAIR_ALLOW_DATA_LOSS. This is the minimum level of repair to resolve all errors from CHECKDB, but this does not mean that it will actually fix the error. Furthermore, it may result in data loss. 

SQL repair tool helps in repairing corrupt MS SQL database including corrupt .mdf and .ndf files and recovers all database components – Tables, Triggers, Indexes, Keys, Rules, deleted records and Stored Procedures. It is of great help in times of crisis, as the software provides a definite repair solution and supports all SQL database versions including the recent and older ones. 

Понравилась статья? Поделить с друзьями:
  • Sql server create file encountered operating system error
  • Sql server arithmetic overflow error converting numeric to data type numeric
  • Sql server 945 error
  • Sql server 4064 ошибка
  • Sql server 3415 error