Sql server ошибка 823

title description author ms.author ms.date ms.service ms.subservice ms.topic helpviewer_keywords

MSSQLSERVER error 823 | mssqlserver_823

A description and some common solutions to Microsoft SQL Server Error 823 (mssqlserver_823), which is a severe system-level error condition that threatens database integrity and must be addressed immediately.

MashaMSFT

mathoma

01/27/2019

sql

supportability

reference

823 (Database Engine error)

MSSQLSERVER error 823

[!INCLUDE SQL Server]

Details

Attribute Value
Product Name SQL Server
Event ID 823
Event Source MSSQLSERVER
Component SQLEngine
Symbolic Name B_HARDERR
Message Text The operating system returned error %ls to SQL Server during a %S_MSG at offset %#016I64x in file ‘%ls’. Additional messages in the SQL Server error log and system event log may provide more detail. This is a severe system-level 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.

Explanation

SQL Server uses Windows APIs (for example, ReadFile, WriteFile, ReadFileScatter, WriteFileGather) to perform file I/O operations. After performing these I/O operations, SQL Server checks for any error conditions associated with these API calls. If the API calls fail with an Operating System error, then SQL Server reports Error 823.

The 823 error message contains the following information:

  • The database file against which the I/O operation was performed
  • The offset within the file where the I/O operation was attempted. This is the physical byte offset from the start of the file. Dividing this number by 8192 will give you the logical page number that is affected by the error.
  • Whether the I/O operation is a read or write request
  • The Operating System error code and error description in parentheses

Operating system error: A read or write Windows API call is not successful, and SQL Server encounters an operating system error that is related to the Windows API call. The following message is an example of an 823 error:

Error: 823, Severity: 24, State: 2.
2010-03-06 22:41:19.55 spid58 The operating system returned error 1117 (The request could not be performed because of an I/O device error.) to SQL Server during a read at offset 0x0000002d460000 in file 'e:program filesMicrosoft SQL Servermssqldatamydb.MDF'. Additional messages in the SQL Server error log and system event log may provide more detail. This is a severe, system-level error condition that threatens database integrity and must be corrected immediately. It is recommended to complete a full database consistency check (DBCC CHECKDB). This error can be caused by many factors; for more information, see SQL Server Books Online.

You may or may not see errors from the DBCC CHECKDB statement on the database that is associated with the file in the error message. You can run the DBCC CHECKDB statement when you see an 823 error. If the DBCC CHECKDB statement does not report any errors, you probably have an intermittent system problem or a disk problem.

Additional diagnostic information for 823 errors may be written to the SQL Server error log file when you use trace flag 818.
For more information, see KB 826433: Additional SQL Server diagnostics added to detect unreported I/O problems

Cause

The 823 error message usually indicates that there is a problem with underlying storage system or the hardware or a driver that is in the path of the I/O request. You can encounter this error when there are inconsistencies in the file system or if the database file is damaged. In the case of a file read, SQL Server will have already retried the read request four times before it returns 823. If the retry operation succeeds, the query will not fail but message 825 will be written into the ERRORLOG and Event Log.

User Action

  • Review the suspect_pages table in MSDB for other pages that are encountering this problem (in the same database or different databases).
  • Check the consistency of databases located on the same volume (as the one reported in the 823 message) using DBCC CHECKDB command. If you find inconsistencies from the DBCC CHECKDB command, use the guidance from How to troubleshoot database consistency errors reported by DBCC CHECKB.
  • Review the Windows Event logs for any errors or messages reported from the Operating System or a Storage Device or a Device Driver. If they are related to this error in some manner, address those errors first. For example, apart from the 823 message, you may also notice an event like «The driver detected a controller error on DeviceHarddisk4DR4» reported by the Disk source in the Event Log. In that case, you have to evaluate if this file is present on this device and then first correct those disk errors.
  • Use the SQLIOSim utility to find out if these 823 errors can be reproduced outside of regular SQL Server I/O requests. The SQLIOSim utility ships with SQL Server 2008 and later versions so there is no need for a separate download. You can typically find it in your C:Program FilesMicrosoft SQL ServerMSSQLxx.MSSQLSERVERMSSQLBinn folder.
  • Work with your hardware vendor or device manufacturer to ensure
    • The hardware devices and the configuration conforms to the I/O requirements of SQL Server
    • The device drivers and other supporting software components of all devices in the I/O path are up to date
  • If the hardware vendor or device manufacturer provided you with any diagnostic utilities, use them to evaluate the health of the I/O system
  • Evaluate if there are filter drivers that exist in the path of these I/O requests that encounter problems.
    • Check if there are any updates to these filter drivers
    • Can these filter drivers be removed or disabled to observe if the problem that results in the 823 error goes away

Summary: SQL server error 823 occurs due to an operating system or an I/O error. It may impact database integrity and needs to be fixed immediately. This blog explains in detail about the error and how you can fix it. You may try using a SQL repair tool to fix consistency errors against the database that reported 823 error.

Free Download for Windows

What is SQL error 823?

A SQL Server database encounters error 823 when an I/O operation (read or write request) fails. This usually happens due to issues with the operating system, drivers, or hardware issues. The SQL error 823 may also occur due to inconsistencies in the file system or a corrupted database file.

The complete text of the SQL 823 error message looks similar to:

Error: 823, Severity: 24, State: 2.
2010-03-06 22:41:19.55 spid58 The operating system returned error 38 (Reached the end of the file.) to SQL Server during a read at offset 0x000000a72c0000 in file ‘C:Program FilesMicrosoft SQL Server MSSQLDATAdb.mdf’. Additional messages in the SQL Server error log and system event log may provide more detail. This is a severe, system-level error condition that threatens database integrity and must be corrected immediately. It is recommended to complete a full database consistency check (DBCC CHECKDB). This error can be caused by many factors; for more information, see SQL Server Books Online

In the error message, 823 is the error code. The severity level 24 means that the error occurred due to problems with the hardware or software. The state 2 is used to differentiate the error from other errors with the same number but in a different state.

Further, the error provides the following information:

  • The data file (usually a .MDF file) against which the I/O (read or write) operation was performed.
  • The offset, i.e., the physical byte offset from the start of the file, dividing it by 8192 will help you find the logical page number that is corrupted due to the error.
  • Identifies whether a read or write request was made to a device.

What problems are associated with the 823 IO error?

This problem can be related to the following problems:

  1. A Torn Page
  2. Bad Page ID
  3. Insufficient bytes transferred

What is a torn page?

It is a page that was incorrectly written. We could say Torn Page Detection writes a bit for every 512 bytes on the page. It helps detect a page that is not successfully written to disk. But, it does not tell if the data stored to disk is actually correct as a couple of bytes may have been written incorrectly.

What is the error message for the torn page error?

The error will be like this one:

2015-08-05 16:51:18.90 spid17 Error: 823, Severity: 24, State: 2
2015-08-05 16:51:18.90 spid17 I/O errors (torn page) detected during read at offset 0x00000094004000 in file ‘c:Program FilesMicrosoft SQL ServerMSSQLdatatempdb.mdf’

How can I detect torn page IO error?

You can detect these errors when you run the CHECKDB command in your database.

What is Bad Page ID?

It is when the header page ID is not the same as the expended one when reading in the disk.

Why is the error insufficient bytes transferred produced in SQL Server?

It means that the API call was invoked successfully, but the bytes transferred are not the expected ones.

How to solve SQL Server error 823 ?

The first step would be to run a DBCC CHECKDB command and check if it returns consistency errors. If it does, try to restore your database from a backup. Once the database is restored, run a CHECKDB to verify that the problem is solved.

If the problem persists or backup is not available, try to repair the database using the following T-SQL statement:

DBCC CHECKDB (DB_NAME, REPAIR_REBUILD);

To repair the database, you must restrict its usage to a single user. This requires changing the database state to Single-user mode. To do so, run the following T-SQL query:

ALTER DATABASE DB2 SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

You can also set the database to a Single-user using the point-in-click interface in SQL Server Management Studio (SSMS). For this, right-click on the database in SSMS and go to the Options page. On the ‘Options’ page, choose the SINGLE USER option from the Restrict Access drop-down box, then click OK.

SQL Server error 823

After setting the database to Single_user mode, repair the database, and run ‘DBCC CHECKDB’ again to verify that the database was repaired.

Note: If the error persists, an issue with the hardware might have caused SQL error 823. In that case, you will need to repair your hard disk. Contact the IT members in charge of the hardware. Check also if there are fragmentation problems in the hard disk.

If you have a Torn page error, you can use the CHECKSUM and the torn page detection to repair and verify the errors.

What Else You Can Do to Resolve SQL Error 823?

Use Stellar Repair for MS SQL to fix database consistency errors reported by DBCC CHECKDB and preview the recoverable data. This SQL repair tool  can be downloaded from the link below.

free download

This software will repair the .MDF/.NDF files of SQL Server database. Before using the software, make sure to stop the SQL Server Service first. It is recommended to stop the service using the SQL Server Management Studio (SSMS) or the SQL Server Configuration Manager.

stop SQL server service

Now follow these steps to repair and recover your SQL database file:

  • Browse or search the corrupt .MDF file.
  • Once the .MDF file is uploaded, press the Repair button.

select corrupt mdf file

Note: If you have one or multiple secondary data files (.NDF file) associated with your database, then put all the NDF files at the location of the MDF file. Once everything is done, you can restart the SQL Server Service and rerun the CHECKDB command.

  • Run standard scan to repair the selected database file quickly.

select scan mode

  • Preview the repairable database objects and select all or specific objects you want to restore. Next, press the Save button from the File menu.

repaired database file preview

  • Enter the details as shown in the following screen to complete the file saving process.

repaired file saving options

Once the software repairs the .MDF file, you will no longer see the SQL Server error 823.

Conclusion

This blog discussed the reasons that could result in SQL Server database error 823. It can be caused by hardware (disk errors, hardware or software failures) or system problems. Also, the blog explained how to fix the SQL 823 error by restoring the database from backup, running DBCC CHECKDB with a repair option, or using Stellar Repair for MS SQL software. Stellar Repair for MS SQL is a simple SQL repair tool. If you have any queries, please do not hesitate to write your questions and comments.

About The Author

Priyanka Chauhan

Priyanka is a technology expert working for key technology domains that revolve around Data Recovery and related software’s. She got expertise on related subjects like SQL Database, Access Database, QuickBooks, and Microsoft Excel. Loves to write on different technology and data recovery subjects on regular basis. Technology freak who always found exploring neo-tech subjects, when not writing, research is something that keeps her going in life.

Are you seeking for a solution of SQL error 823? We can help you fix it.

Often, the SQL server error 823 occurs when there is a problem in SQL Server. It can either due to fault in the operating system error or an IO error.

Here at Bobcares, we have seen several such SQL errors as part of our Server Management Services for web hosts, Linux/Windows users, and online service providers.

Today, we’ll take a look at the cause for this error and see how to fix it.

Reasons for SQL Error 823?

SQL Server uses Windows APIs (ReadFile, WriteFile, ReadFileScatter, WriteFileGather) to perform file I/O operations.

Further, the SQL Server uses Application Programming Interface or API to perform file I/O operations in Windows OS. Once finishes I/O operations, SQL Server tests any error conditions related to these API calls

However, if an API calls fail with an Operating System error results in SQL Error 823. Mostly, it happens due to operating system error or an IO error.

Further, the 823 error message contains the following information:

1. A database file that was used for the I / O process.

2. The offset within the file where you tried the I / O process.

3. Indicates if the I/O operation is a read or write request.

4. The Operating System error code and error description.

Also, other reasons behind the API-Server incompatibility are;

1. User errors in the system.

2. System corruption.

3. Database corruption.

4. SQL Server update or reinstallation.

5. Hardware corruption.

How to fix SQL Error 823

Here, let’s see the different solutions provided by our Support Engineers to fix this error.

Operating system error

SQL Server reports an operating system error if a read or write Windows API call is not successful.

And, the error message looks like,

Error: 823, Severity: 24, State: 2.
2010-03-06 22:41:19.55 spid58 The operating system returned error 1117 (The request could not be performed because of an I/O device error.) to SQL Server during a read at offset 0x0000002d460000 in file 'e:program filesMicrosoft SQL Servermssqldatamydb.MDF'. Additional messages in the SQL Server error log and system event log may provide more detail. This is a severe, system-level error condition that threatens database integrity and must be corrected immediately. It is recommended to complete a full database consistency check (DBCC CHECKDB). This error can be caused by many factors; for more information, see SQL Server Books Online.

In order to fix the error, our Support Engineers check the suspect_pages table in MSDB for other pages that having this problem.

Also, verify the consistency of databases located on the same volume using DBCC CHECKDB command. Otherwise, the consistency errors can be eliminated by restoring data from a good backup.

An IO error

Frequently, this error can be related to the following problems,

1. A Torn Page.
2. Bad Page ID.
3. Insufficient bytes transferred.

So, our Support Engineers initially run a DBCC CHECKDB command. then, we try to repair the database using the below command.

DBCC CHECKDB (DB_NAME, REPAIR_REBUILD);

Again, we run “DBCC CHECKDB” to verify whether the database is repaired.

If repairing ends in failure, we restore the database with a backup. Once the database is restored, run a CHECKDB to verify that the problem is solved.

Sometimes, the problem can persist after the restoration or repairing. Mostly, this happens due to a hardware problem, then the customer may need to repair the hard disk.  Or, they need to contact the hardware vendor or device manufacturer to ensure the following,

1.  Firstly, check whether the hardware devices and the configuration conforms to the I/O requirements of SQL Server.

2. Then, the device drivers and other supporting software components for devices in the I/O path are not outdated.

[Need assistance to SQL error 823? We’ll help you.]

Conclusion

In this article, we learned different reasons that produced the SQL Server error 823. Mostly, this problem can be caused by hardware (disk errors, power failures) or system problems. Today, we saw how our Support Engineers provide a work-around for this error.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Содержание статьи:

    • SQL-сервер не найден или недоступен, ошибки соединения с SQL-сервером
      • Ошибка SQL-сервера 26
      • Ошибка SQL-сервера 18456
      • Не удалось запустить SQL-server — код ошибки 3417
    • Повреждена база данных
      • Код ошибки SQL-сервера 945
      • Код ошибки SQL-сервера 5172
      • Ошибка SQL-сервера 823
      • Ошибка SQL-сервера 8946
    • Другие ошибки SQL Server
      • Код ошибки SQL-сервера 1814
      • Код ошибки SQL-сервера 1067
      • SQL-сервер запускается, но работает слишком медленно

SQL-сервер не найден или недоступен, ошибки соединения с SQL-сервером

  • Если SQL-сервер не найден, убедитесь, что ваш экземпляр SQL-сервера действительно установлен и запущен. Для этого зайдите на компьютер, где он установлен, запустите диспетчер конфигурации SQL и проверьте, есть ли там тот экземпляр, к которому вы пытаетесь подключиться и запущен ли он. Нелишним будет также получить отчет об обнаружении компонентов SQL-серверов.
  • Если вы проделали п1. и не обнаружили источник проблемы, возможно, неверно указан IP-адрес компьютера или номер порта TCP. Перепроверьте их настройки.
  • Причиной того, что невозможно подключиться к SQL-серверу, также может быть сеть, убедитесь, что компьютер с SQL-сервером доступен по сети.
  • Проверьте, может ли клиентское приложение, установленное на том же компьютере, что и сервер, подключиться к SQL-серверу. Запустите SQL Server Management Studio(SSMS), в диалоговом окне “Подключиться к серверу” выберите тип сервера Database Engine, укажите способ аутентификации “Аутентификация Windows”, введите имя компьютера и экземпляра SQL-сервера. Проверьте подключение.

Обратите внимание, что многие сообщения об ошибках могут быть не показаны или не содержат достаточной информации для устранения проблемы. Это сделано из соображений безопасности, чтобы при попытке взлома злоумышленники не могли получить информацию об SQL-сервере. Полные сведения содержатся в логе ошибок, который обычно хранится по адресу C:Program FilesMicrosoft SQL ServerMSSQL13.MSSQLSERVERMSSQLLogERRORLOG, или там, куда его поместил администратор системы.

Ошибка SQL-сервера 26

Одна из наиболее часто встречающихся ошибок подключения к SQL-серверу, обычно связана с тем, что в настройках SQL-сервера не разрешены или ограничены удаленные соединения. Чтобы это исправить, попробуйте:

  • в SSMS в настройках SQL-сервера включите аутентификацию Windows
  • для брандмауэра Windows  создайте новое правило, которое разрешает подключение для всех программ и протоколов с указанного IP-адреса
  • убедитесь, что запущена служба SQL Server Browser

Ошибка SQL-сервера 18456

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

Не удалось запустить SQL-server — код ошибки 3417

Возникает в случае, если были изменены настройки Windows или перемещена папка с файлами MSSQL.

  • зайдите в C:Program FilesMicrosoft SQLServerMSSQL.1MSSqLData — БезопасностьНастройки доступа — Учетная запись сетевой службы — добавьте учетную запись сетевой службы
  • проверьте, что MDF-файл не сжимается. Если это не так, отключите “Сжимать содержимое для экономии места на диске” в свойствах файла

Иногда ни один из этих способов не помогает, это значит, что файлы БД повреждены и ее придется восстанавливать из резервной копии.

Повреждена база данных

Код ошибки SQL-сервера 945

Ошибка 945 возникает, когда БД SQL-сервера помечена как IsShutdown. Проверьте, достаточно ли места на диске, достаточно ли прав у учетной записи для операций с БД, файлы MDF и LDF не должны быть помечены “Только для чтения”.

Код ошибки SQL-сервера 5172

SQL-сервер хранит свою физическую БД в первичном файле, в котором информация разбита постранично. Первая страница содержит информацию о заголовке mdf-файла и называется страницей заголовка. Она состоит из разнообразной информации о БД, такой как размер файла, подпись и т.д. В процессе прикрепления MDF на SQL-сервере часто возникает ошибка 5172. Это в основном происходит, если MDF-файл поврежден, информация в его заголовке тоже и соответственно сложно добраться до данных. Причиной может быть вирус, аварийное выключение системы, ошибка оборудования.

Ошибка SQL-сервера 823

SQL использует API Windows для операций ввода-вывода, но кроме завершения этих операций SQL проверяет все ошибки обращений к API. Если эти обращения несовместимы с ОС, появляется ошибка 823. Сообщение об ошибке 823 означает, что существует проблема с базовым оборудованием для хранения данных или с драйвером, который находится на пути запроса ввода-вывода. Пользователи могут столкнуться с этой ошибкой, если в файловой системе есть противоречия или поврежден файл базы данных.

Ошибка SQL-сервера 8946

Основной причиной ошибки 8946 так же, как и для 5172, является повреждение заголовков страниц БД SQL вследствие сбоя питания, вирусной атаки, отказа оборудования — SQL-сервер больше не может прочесть эти страницы.

Перечисленные ошибки 945, 5172, 823, 8946 можно устранить двумя методами:

  • если у вас есть свежая резервная копия базы — восстановить базу из этой копии
  • можно попробовать использовать специализированное ПО, такое как SQL Recovery Tool, чтобы восстановить поврежденные файлы

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

Другие ошибки SQL

Код ошибки SQL-сервера 1814

SQL-сервер не может создать базу данных tempdb.  Убедитесь, что на выделенном под нее диске достаточно места и что у учетной записи хватает прав для записи в указанную директорию.

Код ошибки SQL-сервера 1067

Эта ошибка может возникать по разным причинам. Наиболее часто оказывается, что повреждены или отсутствуют конфигурационные файлы, SQL-сервер обращается к поврежденным системным файлам, ошибочные данные пользователя, нет информации про лицензию. В самых тяжелых случаях придется переустанавливать SQL-сервер. Но иногда помогает восстановление поврежденных файлов или изменение настроек SQL-сервера — вы можете создать новую учетную запись в домене и использовать ее для службы MSSQL.

SQL-сервер запускается, но работает слишком медленно

Проанализируйте журнал сервера, индексы (фрагментацию), запросы, задания, возможность взаимных блокировок.  Причин может быть масса.

Мы работаем с разными версиями SQL-сервера уже много лет, знакомы со всевозможными инструкциями SQL-сервера, видели самые разные варианты его настройки и использования на проектах у своих клиентов. В целом мы можем выделить четыре основных источника неполадок:

  • Индексы — причина проблем номер один. Неправильные индексы, отсутствующие индексы, слишком много индексов и подобное. Чаще всего при проблеме с индексами пользователи или администраторы базы данных не получают сообщения об ошибке, они просто видят, что база работает очень медленно и докопаться до причин бывает очень нелегко
  • изначально плохая архитектура сервера баз данных — ошибка, которую очень сложно и дорого исправлять на этапе, когда база уже используется
  • плохой код, в котором возможны блокировки и тупиковые места
  • использование конфигурации по умолчанию,

Если у вас не получается устранить ошибки сервера SQL-server самостоятельно, если они появляются снова и снова, то скорее всего в основе лежит одна из этих причин. В таком случае — если у вас произошла ошибка с SQL сервером, ваше ПО не видит SQL-сервер, либо нужно развернуть кластер SQL-серверов — вы всегда можете обратиться за консультацией и технической поддержкой к специалистам Интегруса, отправив заявку с сайта, написав на e-mail, либо позвонив в колл-центр нашей компании.

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

Кейсы и стратегии от экспертов рынка.








Home
Login
Join



  1. Home
  2. Databases
  3. Microsoft SQL Server
  4. How-tos
Helpdesk icon
Spiceworks Help Desk

The help desk software for IT. Free.

Track users’ IT needs, easily, and with only the features you need.

Learn More »

Author Adom (Aryson Technologies)
Adom (Aryson Technologies)

This person is a Verified Professional

This person is a verified professional.
Verify your account
to enable IT peers to see that you are a professional.


Last Updated:

Mar 11, 2023
2 Minute Read

  • Spice
  • Reply (1)
  • Subscribe

  • Share
    Opens a new window

    • Facebook
      Opens a new window

    • Twitter
      Opens a new window

    • Reddit
      Opens a new window

    • LinkedIn
      Opens a new window

Author Adom (Aryson Technologies)

Adom Click

This person is a Verified Professional

This person is a verified professional.
Verify your account
to enable IT peers to see that you are a professional.

Adom (Aryson Technologies)Technical Specialist at Aryson Technologies
Badge Review Champ Level 1
Badge Verified Professional
Badge Version 7.4
Badge United States
Badge Voice of IT


Areas of expertise
What’s this?

Email, Microsoft Office

829
Contributions
13
Best Answers
0
Projects

Main Areas of Contribution:
  • Microsoft Office 365 |
  • Microsoft Exchange |
  • Microsoft Office |
  • Email |
  • Data Recovery
Register. Track Progress. Earn Credits.
Learning has never been so easy!

Sign Up

Возможно, вам также будет интересно:

  • Sql server ошибка 3313
  • Sql server ошибка 3201
  • Sql server ошибка 313
  • Sql server ошибка 300
  • Sql server ошибка 26011

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии