How to fix Recovery Pending State in SQL Server Database? - sql-server

How to fix Recovery Pending State in SQL Server Database?

Execute the following set of queries:
ALTER DATABASE [DBName] SET EMERGENCY;
GO
ALTER DATABASE [DBName] set single_user
GO
DBCC CHECKDB ([DBName], REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS;
GO
ALTER DATABASE [DBName] set multi_user
GO
For more info: https://www.stellarinfo.com/blog/fix-sql-database-recovery-pending-state-issue/

When your Database .mdf file name is renamed, this issue is occurred. To solve:
Restart SQL EXPRESS in Services, Pending issue is solved.

In our case it was caused by the disk drive running out of space. We deleted some junk to free space, then fixed the "Recovery Pending" by stopping and restarting the SQL Server Service.

Detach, re-attach, solved !
ALTER DATABASE MyDatabase SET EMERGENCY;
EXEC sp_detach_db MyDatabase
EXEC sp_attach_single_file_db #DBName = MyDatabase, #physname = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\MyDatabase.mdf'

While using SQL Management Studio, there is an intermittent issue when a user is changing the Database Names then sometimes SQL Server uses the same DB file for two different Databases. If SQL Server is in this state then you would be probably seeing the following error if you try Mahesh's answer:
"The process cannot access the file because it is being used by another process"
To fix this issue:
Stop MSSQLServer service from the Services Console MMC
Rename the DB and the Log files (Database Properties -> Files)
In the Object Explorer window in SQL Management Studio, refresh the 'Databases Folder', if you see that there is another Database node (in addition to the one which you are trying to rectify this issue) which is shown in 'Recovery Pending State' then proceed to the next step. If you do not see this error then you need to try something else to resolve this issue
Make a backup of the DB and Log files for new offending node from step 3 and !!Careful!! delete the database
Restore the Db File names which you changed in Step 2
Now start the MSSQLServer service from the Services Console
Re-try the steps from Mahesh's answer

In my case, this affected the secondary server in a High Availability SQL Server cluster.
The primary was Synchronizing but the secondary was Recovery Pending.
After checking in cluadmin.msc, realised that the secondary server wasn't healthy in the cluster.
Then determined Cluster Service had failed to start on the second cluster box after a Windows Update enforced reboot (may have happened because the file share witness was rebooting after a similar Windows Update at the same time).
Starting the Cluster Service brought the databases back into Synchronizing status.

Ensure that the "Log On" account for the "SQL Server (201x)" service (listed in Windows Services (Manager)) has sufficient rights. You may try changing it to another Logon. In my case, changing it from "This account" to "Local System account", restarting the "SQL Server (xxxx)" service and SQL Server Management Studio (SSMS), and logging into SSMS again resolved the issue.
Background (in my particular case):
I had 3 different instances of SQL (2008r2, 2012 and 2014) running on my local PC, and was busy moving a folder (which I later discovered contained some SQL data & log database files) to another PC. Halfway through, I stopped the SQL Services in Service (Manager), hoping that the files would move across without issues - since they would now, no longer be in use. I realized that I needed to confirm the database names, and file locations in SQL (in order to set them up again on the new pc), so I copied the SQL data and log files back (to the original locations). After restarting the PC - the majority of the databases on various instances all showed as: "Recovery Pending" in SSMS. After first trying the procedure from stellarinfo (listed as an answer here by #Mahesh Thorat) on 2 of the databases, and still not having any luck, a post SQL SERVER – Where is ERRORLOG? Various Ways to Find ERRORLOG Location on Pinal Dave's SQL Authority website and the post: Operating System error 5(Access is Denied) on SQL Server Central gave me an idea that it could be rights related after looking at the SQL Errorlog and finding "Operating system error 5: "5(Access is denied.)". Another post Msg 3201, Level 16 Cannot open backup device. Operating system error 5(Access is denied.) at SqlBak Blog seems to support this.

I was using azure, the mdf and log file are in different disk and not attached that disk with which it is not able to figure that files and hence the file Recovery Pending

This could happen due to insufficient permissions for a folder with database files (in my case due to a domain migration).
Just give access to the folder for an SQL service's account.

Related

SQL Server: How to attach / repair a detached / damaged database?

A database server crashed. I was able to get the mdf and the log file and I am trying to mount it on another server. I don't have backup as it was a development database.
When I try to attach the mdf and ldf files, Sql Server Management Studio give me this error:
TITLE: Microsoft SQL Server Management Studio
------------------------------
Attach database failed for Server
------------------------------
Could not redo log record (457:14202:19), for transaction ID (0:478674), on page (1:519205), database 'WSS_Content_5555' (database ID 15). Page: LSN = (370:463:113), type = 1. Log: OpCode = 2, context 2, PrevPageLSN: (298:40524:64).
Restore from a backup of the database, or repair the database.
During redoing of a logged operation in database 'WSS_Content_5555', an error occurred at log record ID (457:14202:19).
Typically, the specific failure is previously logged as an error in the Windows Event Log service.
Restore the database from a full backup, or repair the database.
Could not open new database 'WSS_Content_5555'.
CREATE DATABASE is aborted. (Microsoft SQL Server, Error: 3456)
I don't know how to repair the database. Does it need to be attached before beeing repaired? In that case, how can I attach it?
You can try a workaround. In short:
Create a dummy DB with the same name (may need to remove the real DB first, save the original files or rename then).
Take the dummy off line (detach and (set offline or stop the SQL service)).
Delete dummy files, replace then with the real DB files.
Try to re-attach de DB
Edit
As by OP comment note you also can need to rebuild the log (if you lost transactions)
ALTER DATABASE [MyDatabase ] REBUILD LOG ON (NAME=’MyDatabaseLog’,FILENAME=’D:\Microsoft SQL Server\YourDataPath\Data\Logfile.ldf’)
and put the DB in multiple users log (taking the DB off can require you to put it in single use mode)
ALTER DATABASE [nomdb] SET MULTI_USER
For all the gore details you can refer to the Paul Randal Article
(Note in this article the author uses EMERGENCY MODE to (attempt) repair the transaction log)
I already used it with success but depending on the extent of the damage or others details it can be a impossible task. Consider restoring a backup.
Note this stunts are fine in a development server but you really need to plan (and drill) for disaster recovery in a prodution server.

Error 21 when trying to delete a SQL Server DB

I had a SQL Server database on an external HDD. I forgot to detach the DB. I do not need it anymore, but I am unable to delete or take it off line.
When I try to delete or take the DB offline, I get the following error.
Msg 823, Level 24, State 2, Line 7
The operating system returned
error 21(The device is not ready.) to SQL Server during a read at
offset 0x00000000012000 in file 'E:\Kenya Air\Monet - Paulus.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.
Complete a full database consistency check (DBCC CHECKDB). This error
can be caused by many factors; for more information, see SQL Server
Books Online.
I have tried to run a DBCC CHECK, but I get the same error.
Try taking the database offline and then online.
Alter database DatabaseName set offline
Then bring it back online after a while
Alter database DatabaseName set online
I would try the system stored procedure sp_detach_db in SQL. From the fine manual:
Dropping a database deletes the database from an instance of SQL Server and deletes the physical disk files used by the database. If
the database or any one of its files is offline when it is dropped,
the disk files are not deleted. These files can be deleted manually by
using Windows Explorer. To remove a database from the current server
without deleting the files from the file system, use
sp_detach_db.
The OS is reporting exactly what you said in your question: In dropping the database, SQL Server attempts to remove the file from a device that no longer exists. Thus the database cannot be "dropped", per definition. But perhaps it can be detached, because that affects only the system's internal definition of the list of available databases.
Do NOT try to set the database offline and back online - this will eventually make things worse.
Stop SQL Server - move the respective database files (data and logfile(s)) to a different location. Start SQL Server again - eventually the DB will indicate (restore pending) - now delete the DB from SQL server. Next attach the database files back to the server and you should be ok - unless the files are physically corrupt. I have seen this problem numerous times - especially on virtualized SQL instances where SQL server is set to autostart and wasn't shut down in a coordinated manner before a system reboot. A momentary connection problem to either the data or log file can cause this problem. In case your system shows this problem more than once set SQL server to start manually.
I had the same problem, even when I wanted to take the database offline, it gave me this error.
But the problem was solved by restarting SQL.

SQL Server Copy Database Issue

I'm running the copy database wizard on a 2008 R2 instance of SQL Server.
The database I want to copy is a SQL 2000 database.
I'm copy that database to another SQL SErver 2008 R2.
The wizard uses SQL authentication for both servers, and both are sysadmins.
When I run it, I get the following error (FYI I have tried both copying the logins and leaving them out):
Event Name: OnError
Message: ERROR : errorCode=-1073548784 description=Executing the query "sys.sp_addrolemember #rolename = N'RandomRoleName..." failed with the following error: "The role 'RandomRoleName' does not exist in the current database.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
helpFile= helpContext=0 idofInterfaceWithError={C81DFC5A-3B22-4DA3-BD3B-10BF861A7F9C}
StackTrace: at Microsoft.SqlServer.Management.Dts.DtsTransferProvider.ExecuteTransfer()
at Microsoft.SqlServer.Management.Smo.Transfer.TransferData()
at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.TransferObjectsTask.TransferDatabasesUsingSMOTransfer()
Any help would be appreciated!
Jim
My suggestion is dont use the copy database wizard. Create a full backup of the database on the 2000 server and then restore it on the 2008 server.
If you google "Microsoft.SqlServer.Management.Dts.DtsTransferProvider.ExecuteTransfer Copy Database Wizard" you will find that many many people have gotten this same error or other nearly identical smo errors... no-one appears to have gotten past it.
That's isn't to say its impossible... just, restoring a backup is so much easier then the wizard or troubleshooting the wizard. Good luck.
The copy wizard had missed some security and IIRC it's caused by subtle differences in security tables, principals etc between the 2 versions.
Frankly, the easiest way is to do one of these two:
backup/restore
detach, copy, attach
If you don't have access to the O/S and can't get it, another option is to create the missing role(s) in the background as the copy runs. You have to catch it between the creation of the files and when it tries to reference the roles, but there are a few seconds in which to create them if you keep clicking execute - I managed to create 9 roles.
Unfortunately, you'll end up with the roles in another database too (while yours cannot be used) so those need to be deleted.
Of course, this is only an option when you really can't use the other method.
Though the answer which is using the backup technique solves the problem generally, after facing the same issue several times, I was able to trace down the root of the problem using the Event Viewer of Windows to that the Database Copy wizard, using the SQL Agent, will eventually create a Job for the agent to run, after which the Agent will run using its own credentials (i.e. the credentials that you can look up in Windows Services, in my case, NT Service\SQLAgent$SQL2014)
All you need to do is to go the folder where SQL Server creates DB files (e.g. C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\DATA by default for SQL 2014) and give the SQL Agent windows user write/read access on the folder.
The reason can be that a file with the new Database name already exist on the filesystem. We encountered this when we renamed Database X to X_Old, and tried to copy database Y to X. This cannot be done, because database X_Old is still associated with the filename X.
Either delete the conflicting database, or rename the file on the file system.
See http://codecopy.wordpress.com/2012/01/03/error-while-copying-a-database/

mssql '5 (Access is denied.)' error during restoring database

I want to restore a database from a file (Tasks → Restore → Database; after I select from device and select file) via SQL Server Management Studio.
After that, I get this error:
The operating system returned the error '5(Access is denied.)' while attempting
'RestoreContainer::ValidateTargetForCreation' on 'E:\Program Files\Microsoft SQL
Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\XXXXXX.mdf'.
Msg 3156, Level 16, State 8, Server XXXX, Line 2
How do I fix this problem? Is it a security error?
I recently had this problem. The fix for me was to go to the Files page of the Restore Database dialog and check "Relocate all files to folder".
The account that sql server is running under does not have access to the location where you have the backup file or are trying to restore the database to. You can use SQL Server Configuration Manager to find which account is used to run the SQL Server instance, and then make sure that account has full control over the .BAK file and the folder where the MDF will be restored to.
Well, In my case the solution was quite simple and straight.
I had to change just the value of log On As value.
Steps to Resolve-
Open Sql Server Configuration manager
Right click on SQL Server (MSSQLSERVER)
Go to Properties
change log On As value to LocalSystem
Hoping this will help you too :)
I just ran into this same problem but had a different fix. Essentially I had both SQL Server and SQL Server Express installed on my computer. This wouldn't work when I attempted to restore to SQL Express, but worked correctly when I restored it to SQL Server.
A good solution that can work is go to files > and check the reallocate all files
I tried the above scenario and got the same error 5 (access denied). I did a deep dive and found that the file .bak should have access to the SQL service account. If you are not sure, type services.msc in Start -> Run then check for SQL Service logon account.
Then go to the file, right-click and select Security tab in Properties, then edit to add the new user.
Finally then give full permission to it in order to give full access.
Then from SSMS try to restore the backup.
I was getting the same error while trying to restore SQL 2008 R2 backup db in SQL 2012 DB. I guess the error is due to insufficient permissions to place .mdf and .ldf files in C drive. I tried one simple thing then I succeeded in restoring it successfully.
Try this:
In the Restore DB wizard windows, go to Files tab, change the restore destination from C: to some other drive. Then proceed with the regular restore process. It will definitely get restores successfully!
Hope this helps you too. Cheers :)
There are several causes for this error, I got this error because I checked "Reallocate all files to folder" in the Files tab of Restore Database window but the default path did not exist on my local machine. I had the ldf/mdf files in another folder, once I changed that I was able to restore.
The operating system returned the error '5(access denied.)' when restoring database in sql server can be solved by enabling the Relocate all files to folder in the Files options as follows:
I found this, and it worked for me:
CREATE LOGIN BackupRestoreAdmin WITH PASSWORD='$tr0ngP#$$w0rd'
GO
CREATE USER BackupRestoreAdmin FOR LOGIN BackupRestoreAdmin
GO
EXEC sp_addsrvrolemember 'BackupRestoreAdmin', 'dbcreator'
GO
EXEC sp_addrolemember 'db_owner','BackupRestoreAdmin'
GO
In my case I had to check the box in Overwrite the existing database (WITH REPLACE) under Options tab on Restore Database page.
The reason I was getting this error: because there was already an MDF file present for the database and it was not getting overwritten.
Hope this will help someone.
If you're attaching a database, take a look at the "Databases to attach" grid, and specifically in the Owner column after you've specified your .mdf file. Note the account and give Full Permissions to it for both mdf and ldf files.
I had exactly same problem but my fix was different - my company is encrypting all the files on my machines. After decrypting the file MSSQL did not have any issues to accessing and created the DB. Just right click .bak file -> Properties -> Advanced... -> Encrypt contents to secure data.
this happened to me earlier today, i was a member of the local server's admin group and have unimpeded access, or i thought so. I also ticked the "replace" option, even though there is no such DB in the instance.
Found out that there used to be DB of the same name there, and the MDF and LDF files are still physically located at the data and log folders of the server, but the actual metadata is missing in the sys.databases. the service account of SQL server also can't ovewrwrite the existing files. Found out also that the files' owner is "unknown", i had to change ownership, to the 2 files above so that it is now owned by the local server's admin group, then renamed it.
Then finally, it worked.
The account does not have access to the location for backup file.
Take the following steps to access the SQL Server Configuration Manager via Computer Manager easily
Click the Windows key + R to open the Run window.
Type compmgmt.msc in the Open: box.
Click OK.
Expand Services and Applications.
Expand SQL Server Configuration Manager.
Change User Account in Log On As tab .
Now you can Restore Data Base easily
The fix for me was to go into Options when trying to Restore the database and change the path to the new path.
Here is the screenshot
I encountered the same problem, but my setup is a bit different.
I run my database in a linux docker container
sqlserver management tool in Windows.
What I did was:
sudo docker exec -u root -it sqlserver /bin/bash
This enters the docker container as a root user.
Then:
chmod 777 /path/to/file.bak
777 gives read, write & execute permissions to the file for any group, user

Sql server Database Suspected marked?

My sql server marked one database as suspected , on checking i found my mdf,ldf files are missing, but no errors on chkdsk, what it means some virus ?
Either the files were deleted, or they have been moved and a master database backup restored from before the change in location. In both cases the physical files can only be deleted or moved if the database is offline - either because sql server was shut down or the database was closed.
Either of these things is highly unlikely to have happened accidentally. It's unlikely to be a generic virus or trojan as such would either have to specifically delete the files on startup before SQL Server started (assuming your database starts automatically) or shut down the database then specifically delete the files. Given that chkdsk doesn't report errors either it's unlikely to be a disk issue, so it's a virtual certainty that the cause of the error is deliberate database (mis)management.
I think the most likely option is that a dba has decided that the files should be moved elsewhere - typically this is done for space or performance reasons - for instance if a new drive is added to a machine that is running out of space then the database could be moved to that. For some reason a backup of the master database has subsequently been restored from a point before the move.
My first action would be to do a full scan of the system for all mdf/ldf files and (hopefully) locate them. I'd also do a scan of backups and look for the latest master database backup. You could either then try restoring the last master backup and see if that fixed the issue (i'd back up the current master first of course), and failing that, or directly, reattach the missing files.
If you cannot find the mdf/ldf files then your only option is restore from backup. If you don't have a backup then your database is lost.
http://support.microsoft.com/kb/180500
At startup, SQL Server attempts to obtain an exclusive lock on the device file. If the device is being used by another process (for example, backup software) or if the file is missing, the scenario described above will be encountered. In these cases, there is usually nothing wrong with the devices and database. For the database to recover correctly, the device must be made available, and the database status must be reset.
It means someone deleted the files.
They can not be deleted when in use so it happened:
when SQL Server was shut down
the database was closed (Express version usually)
the database was taken offline
All user dbs will share the same folder (edit) by default (end edit) so this is deliberate
The more exotic options include restoring the master db where the databases/MDF files listed in the restored master db do not exist etc. But I doubt it.
In this situation, you can check the SQL Server logs. Go to Management, Click on SQL Server Logs and click on current and check the message.
In my case, I got this:
Error 17207, severity 16, state 1 (it is related to log file deletion or corruption)
Solution:
Set the database into single user mode:
Alter database dbname set single_user
Now set the database into emergency mode:
Alter database dbname set emergency
Repair missing log file or corrupted log file with data loss.
DBCC CHECKDB ('dbname', REAPIR_ALLOW_DATA_LOSS)
Note: You may loss the data by using this command. It also depends on client's approval.
Now set the db in multi user mode;
alter database dbname set multi_user
In SQL Server suspect database is a mode when user unable to connect with database.
At this time user unable to perform any action and can not do anything like no open no backup and no restore etc.
Possible cause for this problem can be one of the following:
1. Database is corrupted
2. Insufficient memory state.
3. unexpected shutdown etc.
4. OS is unable to find the database file

Resources