Ms sql database restoring state как исправить

Моя база данных SQL Server находится в состоянии восстановления. Как это произошло и как я могу получить доступ к своей базе данных?

SQL Server Database Stuck in Restoring StateДанный материал является переводом оригинальной статьи «MSSQLTips : Daniel Calbimonte : SQL Server Database Stuck in Restoring State».

Вы обнаружили, что база данных Microsoft SQL Server находится в состоянии восстановления. Как это произошло и как получить обратно доступ к этой базе данных SQL Server?

SQL Server Database Stuck in Restoring State

В этой статье мы покажем причины, по которым база данных MS SQL Server находится в состоянии восстановления, и как получить доступ к базе данных в состоянии восстановления. Это не очень распространенная проблема, но когда так случается, для администратора баз данных это головная боль. В этой статье мы рассмотрим различные причины и возможные решения этой проблемы. Рассмотренные здесь рекомендации пригодны для любой версии SQL Server.

База данных SQL Server в состоянии RESTORING после восстановления

Обычно состояние восстановления возникает, когда вы восстанавливаете базу данных. Здесь мы рассмотрим пример этого.

Создадим файл полной резервной копии (файл *.bak) и файл резервной копии журнала транзакций (файл *.bak), запустив вот такой код T-SQL в SQL Server Management Studio (SSMS):

BACKUP DATABASE [earnings] TO DISK = N'c:sqlearnings.bak' 
WITH NOFORMAT, NOINIT, NAME = N'earnings-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO   BACKUP LOG [earnings] TO DISK = N'C:sqlearnings_LogBackup_2018-06-02_12-42-07.bak' 
WITH NOFORMAT, NOINIT, NAME = N'earnings_LogBackup_2018-06-02_12-42-07', SKIP, NOREWIND, NOUNLOAD, STATS = 10

Как только у нас будут созданы резервные копии, начнем процесс восстановления.

Чтобы восстановить полную резервную копию с резервной копией журнала, нам нужно использовать параметр NORECOVERY в процессе восстановления. Итак, если мы сперва восстановим полную резервную копию следующим образом:

RESTORE DATABASE [earnings] 
FROM DISK = N'c:sqlearnings.bak' WITH NORECOVERY, NOUNLOAD, STATS = 10

База данных теперь будет в состоянии восстановления. Если мы забудем восстановить дополнительные резервные копии, база данных застрянет в этом режиме.

SQL Server Database Stuck in Restoring State

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

RESTORE LOG [earnings]
FROM DISK = N'c:sqlearnings_LogBackup_2018-06-02_12-42-07.bak'

База данных SQL Server в состоянии RESTORING после выполнения резервного копирования журнала с помощью NORECOVERY

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

BACKUP DATABASE [earnings] TO DISK = N'c:sqlearnings.bak' 
WITH NOFORMAT, NOINIT,  NAME = N'earnings-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO   
BACKUP LOG [earnings] TO DISK = N'C:sqlearnings_LogBackup_2018-06-02_12-42-07.bak' 
WITH NOFORMAT, NOINIT, NAME = N'earnings_LogBackup_2018-06-02_12-42-07', SKIP, NOREWIND, NOUNLOAD, NORECOVERY, STATS = 10

Это приведет к переходу базы данных в состояние восстановления.

Чтобы исправить это, вы можете восстановить резервные копии базы данных, как показано выше.

Как сделать базу данных SQL Server доступной в состоянии RESTORING без восстановления резервных копий

Если база данных застряла в состоянии восстановления и у вас нет дополнительных резервных копий для восстановления, вы можете восстановить базу данных с помощью следующей команды:

RESTORE DATABASE [earnings] WITH RECOVERY

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

Дополнительные сведения о восстановлении базы данных в состоянии восстановления можно найти в статье «Recovering a SQL Server database that is in the restoring state».

База данных SQL Server в состоянии RESTORING и Database Mirroring

Другая причина, по которой ваша база данных находится в состоянии восстановления, заключается в том, что она является частью зеркального отображения базы данных SQL Server (Database Mirroring). Database Mirroring — это решение, позволяющее обеспечить высокую доступность базы данных. Если в первичной базе данных произошел сбой, база данных вторичной реплики на другом сервере возьмет на себя операции с базой данных. Основная база данных — это основной сервер, вторичная — это зеркальный сервер и, при желании вы можете иметь еще один зеркальный сервер.

Вот пример. Слева мы видим, что на основном сервере доступна база данных. Справа мы видим зеркало базы, которое находится в состоянии восстановления.

DB Restoring State and Database Mirroring

Дополнительные сведения о зеркальном отображении базы данных можно найти в статье «Configure SQL Server Database Mirroring Using SSMS».

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

Чтобы выполнить автоматическое переключение при отказе, выполните действия описанные в статье: «SQL Docs : Role Switching During a Database Mirroring Session — Manual Failover».

Чтобы «сломать» зеркало, вам нужно будет выбрать базу данных, перейти на страницу зеркального отображения и нажать кнопку удаления зеркального отображения. В следующей статье показано, как это сделать: «SQL Docs : Remove Database Mirroring (SQL Server)». После удаления база данных зеркального отображения вернется в нормальное состояние, и вы сможете создать резервную копию и восстановить базу данных как обычную базу данных.

База данных SQL Server в состоянии RESTORING и Log Shipping

Режим Доставки журналов SQL Server (Log Shipping) позволяет постоянно создавать резервные копии журналов транзакций, а также отправлять и восстанавливать резервные копии на другом сервере, чтобы иметь реплики базы данных в случае отказа основного сервера.

Доставка журналов переводит базу данных в состояние ожидания с восстановлением, либо без восстановления. В режиме «без восстановления» база данных доставки журналов будет находиться в состоянии восстановления, как показано ниже.

DB Restoring State and Log Shipping

Ссылка на статью об изменении состояния, чтобы избежать состояния восстановления: «Change the restore mode of a secondary SQL Server database in Log shipping with SSMS».

База данных SQL Server застряла в состоянии RESTORING после перезапуска компьютера

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

DB Restoring State after reboot

Если у вас возникла эта проблема, попробуйте сначала команду:

RESTORE DATABASE [databasename] WITH RECOVERY

Если вы получаете сообщение об ошибке, что база данных используется, сперва попробуйте установить однопользовательский режим:

USE master;
GO   
ALTER DATABASE Database_name
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;

Затем попробуйте снова выполнить восстановление с помощью предыдущей команды восстановления.

После восстановления вы можете перейти в многопользовательский режим с помощью следующей команды T-SQL:

USE master;
GO   
ALTER DATABASE Database_name
SET MULTI_USER;
GO

Кроме того, убедитесь, что вы используете последний пакет обновления или накопительное обновление SQL Server.

Так же, вам следует просмотреть журнал ошибок и средство просмотра событий Windows, чтобы проверить наличие ошибок.

Заключение

В этой статье мы рассмотрели разные причины, по которым база данных может находиться в состоянии восстановления. Надеемся, это будет полезно, если  вам придется устранять эту проблему.

Summary: A SQL database goes into restoring state for the following reasons; Hardware error, database size, machine restart during working transactions, database file corruption, missing log file, etc. In this article, we will study how we can save or restore the SQL database when it is stuck in a restoring state. First, we will see the scenarios where the database gets stuck in the restoring state. Secondly, we will study how we can handle these situations and solve this problem by Manual and Software approaches.

Free Download for Windows

Contents

  • How to Fix the SQL Database Stuck in Restoring State Issue?
  • Alternative Solution
  • Conclusion

When SQL database stuck in a restoring state, and you try to use the database then, it throws an error “the database DB_NAME is not accessible.” Click OK, and you will see the database still stuck in restoring state as shown in the figure:.

Stellar

How to Fix the SQL Database Stuck in Restoring State Issue?

  • The first thing we will try to do is drop the database that is stuck in the restoring state. That shows you a confirmation window that looks like below:
Stellar
  • Click OK and delete the database. When you delete the database then, it also removed from your database list.
  • Right-click on the database and select Restore Database option as shown in the figure:
Stellar
  • The Restore Database window will open:

Stellar

  • Select the “Device” checkbox to select the backup file in your machine. 
Stellar
  • After selecting the .bak file press the “OK” button. 
Stellar
  • In the left corner of the screenshot, you can see the progress of restoring which means your backup file is selected without any corruption. Click OK.
Stellar
  • The complete message is:
Stellar

Now, the database is ready to use.

Here I have explained the different method to fix the database from restoring state. Now, there is one more method by which you can fix the database restoring issue.

  • Right-click on the database and select Restore Database option (screenshot 3) and select the database backup file. Select the Options as shown in the figure:
Stellar
  • Check the recovery options:
Stellar
  • In this window, you can see a dropdown list with three options. Select the second option from the dropdown list “RESTORE WITH NORECOVERY” and press the “OK”. An instruction window opens from MS SQL Server Management Studio, which shows the database restored successfully.
Stellar
  • Click OK and check the database into the list.
Stellar
  • This is the differential backup because we don’t want to grant the access database to anyone during the restoration process. That’s why we use the option “RESTORE WITH NORECOVERY”.
  • As the database is still in Restoring state and, in this case, you can simply drop the database and restore from the backup or we have another solution.
  • Press “New Query,” which I highlighted in the image and you will see a new window open on the right side where you can write your query. Here we write “RESTORE DATABASE DB_NAME WITH RECOVERY.”
Stellar
Stellar
  • Click Execute and refresh the database. Now, you can access your database.
Stellar

Alternative Solution

The alternative solution is Stellar Repair for MS SQL which repairs and rebuilds corrupt SQL database. Select the corrupt MDF file and repair it. You can also save the database in four different formats.

free download stellar repair for mssql

Conclusion

We went through the detailed methods on how to recover MS SQL Database from when a database stuck in the Restoring state. MS SQL Database used for storing a large amount of data. We will retrieve useful results using MS SQL Management Studio. Sometimes when the server and machine are restarting, and some operations are in the process, the database got corrupted. Then the database is stuck in the restoring state. We use a simple database restore method that takes the .bak file and restore our database. But first, we need to drop the database from the root folder of the database.
On the other hand, we studied a second method in which we restored our database with no recovery option. After completing the restore successfully, we see the file is in restoring state. In the next step, we write a query that recovers the database and make the database is useful.

About The Author

Priyanka

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.

Best Selling Products

Stellar Repair for MS SQL

Stellar Repair for MS SQL

Stellar Repair for MS SQL is an enterpri

Read More

Stellar Toolkit for MS SQL

Stellar Toolkit for MS SQL

3-in-1 software package, recommended by

Read More

Stellar Converter for Database

Stellar Converter for Database

Stellar Converter for Database is an eff

Read More

Stellar Repair for Access

Stellar Repair for Access

Powerful tool, widely trusted by users &

Read More

SQL is a famous database management system used over the globe. Even though it’s a developed application, SQLs data should be upheld up every now and then. SQL administrators create the backup of the databases to avoid data loss situations. But sometimes the SQL administrators have to face the SQL database stuck in Restoring state issues. Due to this, the database is not accessible to users.

Therefore, in this blog, we will discuss the reasons behind the issue SQL Database stuck in restoring state and the best possible solution to fix this issue. Before proceeding further let us have a look at reasons first.

Restoring state

Instant Solution: In case if your SQL Database is inaccessible and you are looking for an instant solution to access and restore the database components then the user can download the SQL Repair Tool. This software supports SQL Server 2019 and the below version.

download

Reason Behind SQL Database Stuck in Restoring State

The Restoring state in SQL Server states that the user has started the database restore process with RESTORE COMMAND or LOG T SQL Command. It means the SQL database is not available for the end-user until the restoration process completed. The most common of the reason for this issue is that the user has run the restoration process with NO RECOVERY Command and has not finished the process with Recovery Command.

Here are the various other reasons in which the database goes into restoring state such as Hardware or software errors, database file corruption, missing log files, improper termination of the recovery process, etc.

Manual Methods to Fix SQL Database Stuck in Restoring State

Method:1

  1. Open Object Explorer in SSMS.
  2. Select and drop the database.
  3. Click on the OK and delete the database.
  4. At the point when you erase the database at that point, it likewise expelled from your database list.
  5. Now, right-click on the database and choose “Restore Database”
  6. The Restore Database window will open.
  7. Choose the “Device” checkbox to choose the backup file in your machine.
  8. In the wake of choosing the .bak file press the “Ok” button.
  9. Finally, your database will be restored successfully.

Method 2:
Another method to fix the database from the restoring state is by using a database backup file. Now, in order to process this method, follow these methods:

  1. Open SSMS on your PC and Right-click on the database folder.
  2. Now, click on the “Restore Database” option.
  3. Select the database backup file.
  4. Now, click on the Options button.
  5. Check, the Restoring options.
  6. Here, you will found dropdown list with three alternatives. Select the subsequent choice from the dropdown list “Restore WITH NORECOVERY” and press the “Ok”. A guidance window opens from MS SQL Server Management Studio, which shows the database restored effectively.
  7. Click on the “OK” and check the database in the database list.
  8. This is the differential backup so we would say not to give the access of the database to anybody during the restoration procedure. That is the reason we utilize the alternative “Restore WITH NORECOVERY”.
  9. As the database is still in Restoring state and, for this situation, you can basically drop the database and restore from the backup or we have another arrangement.
  10. Press “New Query,” Here we express “Restore DATABASE DB_NAME WITH RECOVERY.”
  11. Finally, press the “Execute” button and revive the database and you can get to your database.

Try the Safe, Trusted and Efficient Solution

An alternative method to fix the “SQL database stuck in the restoring state” issue is by using the SysTools SQL Database Recovery tool. This tool is an advanced tool used to recover the SQL database files. Moreover, this tool can also recover the corrupted SQL database files.

Follow the Steps to Access and Recover the Inaccessible Database

  1. Download and Install the Software and Click on Add file.

add-mdf-file2. Browse the MDF file and Select the Advanced Scan mode, SQL Server version, Check the deleted records option,

auto-detect-sql-server-version

3. Now the tool will Preview the Inaccessible SQL database components.

sql9999

4. Click on the Export button to recover SQL database objects easily.

sql-9999

Conclusion

We experienced the itemized strategies on the best way to fix MS SQL Database stuck in Restoring state issue. MS SQL Database used for putting away a lot of information. We will recover helpful outcomes utilizing MS SQL Management Studio. Some of the time when the server and machine are restarting, and a few activities are simultaneous, the database got corrupted or damaged. At that point, the database is stuck in the restoring state. We utilize a straightforward database restore technique that takes the .bak document and restore the database. On the whole, we have to drop the database from the root folder of the database.

Then again, we considered a second strategy wherein we recover our database with no recuperation choice. After finishing the restoration effectively, we see the file is in a restoring state. But in case if your SQL database is still inaccessible then the best and genuine approach to fix this issue is by using SysTools SQL Recovery tool.

Понравилась статья? Поделить с друзьями:
  • Ms settings ошибка файловой системы 2018374635
  • Ms settings personalization background ошибка как исправить
  • Ms settings personalization background windows 10 как исправить
  • Ms settings display ошибка windows 10
  • Ms office ваша лицензия не является подлинной как исправить