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

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.

Related

Recover deleted data from SQL Server

How can I retrieve deleted data from a table in an SQL Server Database with full recovery model?
To Recover the deleted SQL Data first repair the error that caused the error.
Open DB Browse for your Database
Click on Execute SQL tab
In the console type the command 'PRAGMA integrity_Check' and click on the Play button
Once it is known the Database is in a consistent state run the command DBCC DBREPAIR to run repair DB files
Rebuild the database with REPAIR_REBUILD option
Now you can easily recover the files in SQL Database.
Recover deleted database in SQL and get your files back.

How to fix Recovery Pending State in SQL Server Database?

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.

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 backup to Azure stopped working after moving DB files

I have a database in SQL Server 2014 on premises. For that database I have a backup to Azure storage configured using smart_admin.sp_set_db_backup procedure.
Recently I had to move the database files from one disk to another. I detached database, moved files, reattached it.
After that my backup stopped working. The function smart_admin.fn_backup_db_config shows that database backup record exists but database marked as is_dropped = 1
Any attempt to enable or disable backup for this database fails with error:
SQL Server Managed Backup to Windows Azure cannot configure the database, 'DATABASE_NAME', because it either does not exist or is offline.
Any way I can remove backup configuration information and create a new one? One of the ideas I found is rename the database, but I cannot do that in production.
Vad's answer is close, but there can be more than one record in autoadmin_managed_databases for a given db_name. You need to get the last record, which is the one with the max autoadmin_id. I picked the wrong one, and SQL Server repopulated the drop_date after I ran smart_admin.sp_set_db_backup or the 15 minute interval ran.
use msdb;
go
update [dbo].[autoadmin_managed_databases]
set drop_date = null
where [autoadmin_id]= (select max(autoadmin_id)
from [dbo].[autoadmin_managed_databases]
where db_name = '<DROPPPED_DATABASE_NAME>')
go
Managed Backups - is_dropped flag set to Yes after detaching database
and reattaching DB
Rename the database and set up managed backup again.
Reference
As I mentioned earlier I was not allowed to rename the database on the Production. So I found where it's marked as dropped and changed the value. That helped. Automated backups for the database started working again. IMO what happened looks like a bug in SQL Server 2014.
use msdb;
go
update [dbo].[autoadmin_managed_databases]
set drop_date = null
where [db_name] = '<DROPPED_DATABASE_NAME>'
go

How to recover database from MDF in SQL Server 2005?

I have an MDF file and no LDF files for a database created in MS SQL Server 2005. When I try to attach the MDF file to a different SQL Server, I get the following error message.
The log cannot be rebuilt because there were open transactions/users when the database was shutdown, no checkpoint occurred to the database, or the database was read-only. This error could occur if the transaction log file was manually deleted or lost due to a hardware or environment failure.
I would like to accomplish any one of the following options:
Attach the database without data loss (unlikely but would save me some time).
Attach the database with data loss (whatever transactions were open are lost).
Recover the schema only (no data) from the MDF file.
What SQL commands can I try to get my database going again?
I found the following document on Experts Exchange.
patrikt:
You will have data loss but it can be done.
1. Detach database and move your mdf to save location.
2. Create new databse of same name, same files, same file location and same file size.
3. Stop SQL server.
4. Swap mdf file of just created DB to your save one.
5. Start SQL. DB will go suspect.
6. ALTER DATABASE yourdb SET EMERGENCY
7. ALTER DATABASE yourdb SET SINGLE_USER
8. DBCC CHECKDB (yourdb, REPAIR_ALLOW_DATA_LOSS)
9. ALTER DATABASE yourdb SET MULTI_USER
10. ALTER DATABASE yourdb SET ONLINE
Here are details that cover parts 2) and 3) in case re-creating log doesn’t work which can happen if MDF file is corrupted.
You can recover data and structure only by reading MDF file with some third party tool that can de-code what’s written as binary data but even with such tools you can’t always do the job completely.
In such cases you can try ApexSQL Recover. From what I know this is the only tool that can do this kind of job but it’s quite expensive.
Much better idea is to try to recover these from any old backups if you have any.
FROM a post at SQL Server Forums Attaching MDF without LDF:
If you want to attach a MDF without LDF you can follow the steps below
It is tested and working fine
Create a new database with the same name and same MDF and LDF files
Stop sql server and rename the existing MDF to a new one and copy the original MDF to this location and delete the LDF files.
Start SQL Server
Now your database will be marked suspect 5. Update the sysdatabases to update to Emergency mode. This will not use LOG files in start up
Sp_configure "allow updates", 1
go
Reconfigure with override
GO
Update sysdatabases set status = 32768 where name = "BadDbName"
go
Sp_configure "allow updates", 0
go
Reconfigure with override
GO
Restart sql server. now the database will be in emergency mode
Now execute the undocumented DBCC to create a log file
DBCC REBUILD_LOG(dbname,'c:\dbname.ldf') -- Undocumented step to
create a new log file.
(replace the dbname and log file name based on ur requirement)
Execute sp_resetstatus
Restart SQL server and see the database is online.
UPDATE: DBCC REBUILD_LOG does not existing SQL2005 and above. This should work:
USE [master]
GO
CREATE DATABASE [Test] ON
(FILENAME = N'C:\MSSQL\Data\Test.mdf')
FOR ATTACH_REBUILD_LOG
GO
have you tried to ignore the ldf and just attach the mdf:
sp_attach_single_file_db [ #dbname = ] 'dbname' , [ #physname = ] 'physical_name'
i don't know exactly what will happen to your open transactions (probably just lost), but it might get your data back online.
-don
See here : Rebuild master and restore system databases from complete disk failure which has a very nice explanation
Just had this problem myself, but none of the above answers worked for me.
But instead, I found this which worked a treat and so I thought I'd share this for everyone else:
http://www.kodyaz.com/articles/sql-server-attach-database-mdf-file.aspx
Found a another way that works completely:
Create new database with same name to default database location.
Stop SQL server.
Copy old mdf file to overwrite newly created mdf file and delete new ldf file
Start SQL Server, database will be in emergency mode
Detach the emergency mode database
Copy original ldf file to default database location (where new LDF file as created and deleted under step 3 above.
Attach the database MDF file.
I got a working database after trying all of the above that failed for me.
I hope it is easy to do so,
Open SQL Server
Click New Query
Execute the following query
sp_attach_single_file_db #dbname='dbname',#physname='C:\Database\dbname.MDF'
Where dbname is you want to show in Object Explorer, where #physname is the local filepath location of your mdf file.
Hope it will help someone, i done by above, got both structure and also data.
Tested in Sql Server 2000 and 2008. In Sql Server 2000 it is not working, but works perfectly in 2008.

Resources