If I run SQL Server Management Studio, and tell it to connect to (localdb)\v11.0, it knows about every database I've ever used, despite the fact that most of the the database files are long gone.
If I ask it to delete one of these databases, it complains that it can't DROP the database because the database file is gone (duhhh). So, how do I clean up this mess and delete all of database references whose assicated database files are gone?
Bob
In this situation, detach the database rather than trying to drop it. In SQL Management Studio, right-click on the database, select "Tasks" then "Detach".
All you need to do is to recreate the instance, tested with SQL 2012 !
just go in command prompt with admin rights and type:
//list the instancies
sqllocaldb i
//stop selected instance
sqllocaldb p "selected instance"
//delete
sqllocaldb d "selected instance"
//recreate or create new one
sqllocaldb c "new instance"
I had the same problem. When designing DB using code first, I simply remove old DBs. It ends up with multiple deleted DB appearing in SQL Server Management Studio. Then when I try to query the DB, it becomes difficult to find the correct DB instance from amongst the deleted.
As IRM suggested, I tried to Detach those deleted DBs, and for some of them it works great!
However still I have several left. Then I tried "Take offline" on those DBs. Each time when I tried to take DB offline, the SQL Server Management Studio crashed. After SQL Server Management Studio restarted, the DB was gone. So try to do "take offline" if detach and delete don't work for you.
I'd collected hundreds of these, and detaching them individually was just too damned tedious.
What I did:
SELECT 'EXEC sp_detach_db ''' + name + ''''
FROM sys.databases
;
This gave me a list of exec commands:
EXEC sp_detach_db 'E:\...\ADATABASE.MDF'
EXEC sp_detach_db 'E:\...\ANOTHERDATABASE.MDF'
EXEC sp_detach_db 'E:\...\ATHIRDDATABASE.MDF'
....
EXEC sp_detach_db 'master'
EXEC sp_detach_db 'model'
EXEC sp_detach_db 'msdb'
EXEC sp_detach_db 'tempdb'
Copy the results back into the command window, highlight everything other than the system databases, and execute.
The accepted answer here says to detach your server, however if you have snapshots you can't detach them, and you run into the same issue deleting them.
You can delete them, however, by creating empty files in the location where sql server thinks the files should be, restarting the sql server service and then trying again.
If you are unsure how to find the physical location, you might find it here: https://dba.stackexchange.com/questions/49811/location-of-the-mdf-file-of-the-database#:~:text=5%20Answers&text=There%20are%20few%20ways%20to,the%20Path%20and%20FileName%20columns.
Related
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.
I distribute updates to our database in the form of backups "With Replace", but the users can install it to any location on any hard drive, which means I need to "Exec SP_HelpFile" on it before running "Restore With Move". But SP_HelpFile requires me to "Use TheDatabase" first, which I can't do if it's already stuck in a failed restore. I can't even run "With Recovery" if I can't tell it where to restore. Is there any way to use the Master database to get the filenames? Right now my only solution is to delete and reinstall, but I'd like the automated updater to be able to handle it on its own.
UPDATE: Server version is 2005 & 2008
In SQL 2005+, you can use the system view sys.master_files.
select name, physical_name
from sys.master_files
where db_id = db_id('your_database')
You should be able to get the path+filename without having to use the database. sp_helpfile uses the local sys.sysfiles but for now at least you can use the catalog view sysaltfiles, still in master for backward compatibility reasons... this is assuming SQL Server 2005+ (please always specify the version of SQL Server you're using):
SELECT filename
FROM master.sys.sysaltfiles
WHERE db_id = DB_ID('database name');
In the SQL Server 2008, you should use as follows:
SELECT filename
FROM master.sys.sysaltfiles
WHERE dbid = DB_ID('db_name');
I am wanting to backup a SQl Server 2005 db at a remote site (ie. to ultimately have a backup file of the db here locally on my machine).
Can this be done using SQL Server Management Studio Express ? I have this installed and running.. but cannot seem to find a way of backing up using it.
If this isn't possible, how do I create a backup of my remote db some other way ?
Thank you,
Bazza
It should be possible, right click on the database, select Tasks->Backup.
The other good option is the bcp command line utility. If your backup needs to be done regularly it's a better option since you can use it in a bacth file or script and create a scehduler task for it.
I'm not sure, however if you have remote access to the system concerned you should be able to run a SQLCMD and issue the backup from the command line.
1) create a script called say backup.sql
USE [master]
GO
BACKUP DATABASE [somedatabase]
TO DISK = N'C:\somedatabase.bak'
WITH NOFORMAT,
INIT,
NAME = N'Full Database Backup of somedatabase',
SKIP, NOREWIND, NOUNLOAD, STATS = 10
GO
2) issue:
sqlcmd -U username -P password -i backup.sql
Then copy the file over.
Unfortunately, I can't answer your specific question regarding SSMS Express - I've not used the tool extensively. However, I do know that you can open a New Query window and issue a BACKUP DATABASE command. An example of this would be:
backup database <dbname,,> to disk='c:\mydbbackup.bak';
You could then use standard methods (such as FTP) to get the file copied locally. Hope that helps!
This works in SSMS 2008 Express:
Right-click the database name in object explorer > Tasks > Backup…
Select "Full" (should already be default), enter a name, and at the bottom click "Add" and create the file to which you want to back up.
Run the backup.
Copy the file to your local machine.
Connected to the local machine, select the "Databases" node in Object Explorer > Restore Database…
Now name the new database, select "from device" and choose the backup file from which to create the new database, and go.
Done.
I'm trying to restore backups of our production databases to our development server. When I run the following script which has previously worked:
RESTORE DATABASE M2MDATA01 FROM DISK = 'C:\Install\SQLBackup\M2MDATA01.SQLBackup' WITH REPLACE,
MOVE 'M2MDATA01' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\M2MData01.mdf',
MOVE 'M2MDATA01_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\M2MData01.ldf'
I get the following error:
Error 12/21/2009 9:06:09 AM 0:00:00.000 SQL Server Database Error: Exclusive access could not be obtained because the database is in use. 5 0
However, I have no idea how what could possibly be using it. How can I tell?
Check what's connected (the easy way)
SELECT * FROM sys.sysprocesses S WHERE S.dbid = DB_ID('M2MDATA01')
Note: sysprocesses can not be emulated using dmvs...
Edit, check for locks too
SELECT * FROM sys.dm_tran_locks L WHERE L.resource_type = 'DATABASE' AND L.resource_database_id = DB_ID('M2MDATA01')
In SQL Server Management Studio, go to Management => Activity Monitor. This will show you all processes that are connected to all databases, and allow you to kill these processes (only recommended as a last resort).
Profiler is one option.
From Sql Server Management Studio, select Tools|Sql Server Profiler.
Connect to the server instance that the database you are working with is on.
Switch to the Event Selection tab
check the checkbox below the grid labeled "Show all columns"
In the grid find the DatabaseName column and check the entire column.
(optional) press the Column Filters button and filter to the database name you are working with.
This should at least tell you if something is using the database in question.
Easiest solution here is to delete the database and select the "close existing connections" checkbox before hitting okay. Then the restore will work just fine. It's just DEV right? :}
If you're restoring a db, do you really care who is connected? Or what is being done with those connections? I would think not. Just "kick everyone out" by setting the database into single user mode and then restore the database.
USER master
GO
ALTER DATABASE M2MDATA01
SET SINGLE_USER
--This rolls back all uncommitted transactions in the db.
WITH ROLLBACK IMMEDIATE
GO
RESTORE DATABASE M2MDATA01
FROM DISK = 'C:\Install\SQLBackup\M2MDATA01.SQLBackup'
WITH REPLACE,
MOVE 'M2MDATA01' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\M2MData01.mdf',
MOVE 'M2MDATA01_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\M2MData01.ldf'
GO
Now, one additional item to be aware of. After you set the db into single user mode, someone else may attempt to connect to the db. If they succeed, you won't be able to proceed with your restore. It's a race! My suggestion is to run all three statements at once in a single batch.
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.