Sql server ошибка 5172

Problem:

SQL Error 5172

In this article we will know: —

  • What is SQL error 5172?
  • Reasons For «file size property is incorrect SQL Server»
  • How to Fix SQL Error 5172 (.mdf is not a valid database file header)?

Solution:

What Is SQL Error 5172?

The SQL Server stores its physical data in primary database file, which contains the data according to pages. The header information of a .mdf file is hold by first page, which is known as the header page. This page contains the important information of that database file like: file size and signature etc.While attaching the .mdf file in SQL Server, One of the most common error users encounter i:e Microsoft SQL Server Error 5172. The issue .mdf is not a valid database file header generally occurs when the header information of a .mdf file gets corrupted. Due to this the header file information got mismatched and the result of this error could be the database becomes inaccessible.

Reasons For «file size property is incorrect SQL Server»

There could be several reasons behind of header information corruption. It could be corrupt due to following reasons:

  • Bad system Shutdown
  • Improper Shutdown of Microsoft SQL Server
  • Malfunctioning of a hardware
  • Virus attacks

These corruption reasons could be result the issue file size property is incorrect SQL Server and make the database file inaccessible or user failed to attach the database file and get this SQL Server error 5172.

In order to fix this error, one can try restoring the recent backup of the database. If you have a latest copy of backup then it is the right time to use it. Sometimes, the Microsoft SQL Error 5172 arises when a higher version database file is attached to a lower version Server. So, make sure that the database file is attached with the right version to prevent such situation.

Another method to solve this database file header issue is to try SQL Database Recovery Software, if you don’t have the recent backup. The software is capable to fix the file size property of a database file and resolve the issue «mdf is not a valid database file header».

How the Tool Fix File Header Corruption In SQL Server?

Follow the Below Steps to Resolve SQL Server Error 5172:

Bottom Lines

There could be several reasons behind the header information corruption. The article describes some major issues which could be the cause of SQL Server error 5172. Also, it explains the possible recovery solution to fix the issue .mdf is not a valid database file header.

  • Remove From My Forums
  • Question

  • Tried to attach the Adventure Works databases from CodePlex to a named instance of SQL Server 2012 Enterprise evaluation using the following suggested statement:

    CREATE DATABASE AdventureWorks2012 ON (FILENAME = ‘C:\AdventureWorks2012_Data.mdf’)

    FOR ATTACH_REBUILD_LOG;

    There was this 5172 error:

    Msg 5172, Level 16, State 15, Line 1
    The header for file ‘C:\AdventureWorks2012_Data.mdf’ is not a valid database file header.

    The FILE SIZE property is incorrect.

    Trying to attach the database using the UI in SSMS also produced the same error (removed the ldf file from the UI).

    Are these database files corrupt by any chance?


    mysorian

Answers

  • This issue has been resolved. Please try again.

    • Marked as answer by

      Monday, January 21, 2013 6:00 PM

How to Resolve SQL Server Error 5172 – 100 % Working Methods

SQL error 5172

Are you facing Microsoft SQL Server header error 5172? Unfortunately! Do not know how to get rid of this error message –The header for file ‘test.mdf’ is not a valid database file header. The FILE SIZE property is incorrect? Then it is the right blog where you will get the all the possible solutions to resolve SQL Server Error 5172 Header issue in 2008 / 2008 R2 / 2000 / 2005 / 2012 / 2014 / 2016 / 2017 / 2019.

SQL Server Error 5172

Related Solution: Methods to fix Microsoft SQL Server Error 2 Account

What is Microsoft SQL Server Header Error 5172?

Basically, the SQL Server database comprises of two operating system files – Date File & Log File. The Data Files contain information of data and other database objects like – Tables, Stored Procedures, Views, Indexes. Whereas Log file has the details regarding each transaction in the database.

The data files – Primary MDF & Secondary NDF stores data in Pages in a sequential manner that starting with zero. Every page has a unique ID to easily distinguish in the database. The first page of every file is known as header page. This header page comprises details about the attributes of file. Thus when the header information got no harmony or mismatched with the rest of the files, then it leads to SQL Server Error 5172 header issue.

Related: How to Fix SQL Server Error 5171 – A Complete Guide

Reasons for File Size Property is Incorrect (SQL Error 5172) in SQL Server

There are mentioned various reasons behind the error “the file size property is incorrect” (Microsoft SQL Server Header Error 5172). The page header could corrupt due to the following reasons. So let’s have a look once:

  • The system not shutdown properly
  • Unexpected termination of SQL Server Management Studio during any transaction
  • Hardware malfunction
  • Virus or Malware Attack

These are some major reasons that can result file size property is incorrect SQL server issue and make the database inaccessible. Or, it is also possible that users may fail to attach the database file and get SQL error 5172.

Well-Rounded Approach to Resolve SQL Server Error 5172 Header Issue

One can quickly remove the SQL database corruption with the help of SQL Recovery Software. The SQL file repair application can recover both corrupted MDF or NDF files and export it into Live SQL Server environment or SQL Server Compatible Scripts. With this tool, one can easily repair the header error. It supports SQL server 2019, 2017, 2016, 2014 and all below versions. It allow to recover all the deleted records back into the place. The tool allows users to recover SQL Database using two scanning modes i.e., Quick Scan and Advance Scan mode.

Also, the software will generate a preview of all scanned and recovered database items like columns, keys, indexes, triggers, etc. Before that, it is important to know the benefits of the software:

Some Salient Features are listed here:

  1. Repair SQL database MDF & NDF SQL Server database
  2. Support SQL server 2017, 2016, 2014, 2012, 2008 / 2008 R2, 2005, 2000
  3. Recover deleted records from the corrupted SQL Server files
  4. Installation of SQL Server application is not mandatory
  5. Recovers Tables, Triggers, Keys, Indexes, Rules & Stored procedures

Working of SQL Database Recovery Tool to Fix Microsoft SQL error 5172

Steps to resolve SQL Server error 5172 header issue are as follows;

Step 1. First, Download and Install the Software on your Windows platform.

Download Tool Purchase Now

Step 2. Hit on the Open button to select the MDF file whose header is corrupted.

SQL Recovery

Step 3. Now, choose the Scan Mode and SQL MDF file version. If you want to see the deleted records, check the box Preview Deleted Record

Repair MDF File

Step 4. After this, the tool will scan the database file and recover the database from damaged MDF file. Adding to it, all the deleted records appear in red color.

Recover SQL Database

Step 5. Select the mode and export the repaired MDF file & fix the 5172 error safely.

Fix File Header Corruption

Step 6: At last, click on Export and export SQL database files.

Resolve SQL Server Error 5172

How to Fix SQL Server Error 5172 Header Issue – Manual Technique

Almost all corporates have a backup of their database hence, the best way to solve the Microsoft SQL Server header error 5172 is backup data restoration. But, there may be a situation where the backup is also taken at the same location and there is a sudden power outage, and this may result in SQL backup file corruption. So, in that case below mentioned steps needed to be follow:

Step 1. You need to stop the SQL Server instance

Step 2. Afterward, copy your MDF and LDF file to other location on the system

Step 3. Time to delete the original MDF and LDF files

Step 4. Then, start the SQL Server instance again

Step 5. In this Step, create the new database with same DB name and file name

Step 6. Now, stop the SQL Server Management Studio

Step 7. Overwrite the newly created MDF and LDF database file and check whether the error 5172 get resolved or not

Unfortunately! There are some limitations while Performing Manual

  • Highly complex to follow and implement properly for users lacking technical knowledge
  • The users needed the great amount of time for resolving SQL Server error
  • If method are not performing carefully then, high risk of irreversible damage to the database

Resolved Microsoft SQL Server Header Error 5172

This blog have discussed about one of the most common SQL Server Error 5172 header issue. This technical glitch encountered while users tries to attach their SQL Server Database files. Also, we describe the various reasons behind the header information corruption. Henceforth, this write-up explains the both manual as well as automated solution. So, try any workaround that suite you best and fix the Error 5172 – The header for file ‘test.mdf’ is not a valid database file header. The FILE SIZE property is incorrect  without any fail.

Frequently Asked Questions:-

Q-1. Is it possible to use SQL database recovery software to fix error 5172 in SQL Server 2000?

Ans: The software can easily repair MDF file of any MS SQL Server without considering its edition.

Q-2. Does the automated solution fix -the pageaudit property is incorrect. (Microsoft SQL Server error 5172) error?

Ans: With the above-mentioned workaround, one can easily fix this issue.

Q-3. I am using SQL 2014 on Windows 10 platform and getting the 5172 error code. Can I resolve it with SQL recovery tool?

Ans: No matter which Windows version the user is working, the utility supports all the editions of Windows OS to fix.

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

    • 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 Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Log\ERRORLOG, или там, куда его поместил администратор системы.

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

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

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

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

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

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

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

  • зайдите в C:\Program Files\Microsoft SQLServer\MSSQL.1\MSSqL\Data — Безопасность\Настройки доступа — Учетная запись сетевой службы — добавьте учетную запись сетевой службы
  • проверьте, что 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, либо позвонив в колл-центр нашей компании.

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

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

Read time 3 minutes

Microsoft SQL Server is a Relational Database Management System for storing and retrieving data from the database whenever required. Every MS SQL database server is housed with a MDF (Master Data File) that stores all the tables, functions, rules, triggers, etc. and attached with a LDF that stores transaction logs. MS SQL database server is the preferred choice of users amongst RDBMS platforms and unlike other RDBMS, MS SQL database is also vulnerable to corruption and one such error is the file header corruption error 5172.

It occurs when a user tries to attach the MDF/LDF database file saved on your machine, a message window pops up with the MS SQL Server environment saying: “The header for file ‘test.mdf’ is not a valid database file header. The FILE SIZE property is incorrect. (SQL Server Error 5172)”

SQL Recovery

Reason for Microsoft SQL Server Error 5172?

The possible reasons that can cause file header corruption are mentioned below:

  • Damaged or corrupt log file or data file.
  • When you try to attach higher version SQL database server files to a lower version of the SQL database server.
  • Sudden power failure due to which drivers and controllers get affected.
  • Improper system shutdown or SQL Server reboot.

Solution to Fix MS SQL File Header Error 5172

You can solve the file header error 5172 with the help of two methods that solve the error by repairing and restoring data back to the database server from database files.

Solution 1: Manually Fix with Recent Backup of Database

It is the best solution to recover data from backup files of the database. To do so, you need to follow the given steps:

Step 1: Exit from SQL Server running instance.
Step 2: Now, copy MDF and LDF files to another location on your current machine.
Step 3: Simply delete the original MDF and LDF data files and start SQL Server instance once again.  
Step 4: Create a new database with a similar name and filename. Then, stop the SQL Server.
Step 5: Finally, overwrite MDF and NDF file data files for online database recovery.

Solution 2: Automated Solution to Fix File Header Corruption Error 5172

The best and possible solution to repair and recover MDF file data with 100% accuracy and security is using a third-party automated solution. You must consider the professional Kernel for SQL Database Recovery tool to repair, recover and restore corrupt MDF file back to SQL Database Server.

The tool is specially designed to recover all database objects such as functions, tables, rules, functions, deleted records and so on. You can recover large data files that got affected by ransomware. The software supports recovery of UNICODE characters from the database.

Final Words:

The manual method to recover the SQL error 5172 is not entirely safe to follow as it can further damage the tables present in the database of MDF files. Whenever you get an SQL error where the manual solutions are harder to follow, you need to use this software to retrieve the complete database. All the tables present in the database will be at their place. You can even get a preview of the tables in each database.

Понравилась статья? Поделить с друзьями:
  • Sql server ошибка 5030
  • Sql server ошибка 4046
  • Sql server ошибка 4014
  • Sql server ошибка 3624
  • Sql server ошибка 29506