0

I'm working with a bunch of *.mdf files which I'm attaching on my local computer. After I accidentally deleted the a folder containing some of the *.mdf files, I'm unable to view the databases in SQL Management Studio, and therefore can't detach them.

When opening SQLMS I'm getting the error:

Unable to open the physical file "D:\Foo\bar.mdf".
Operating error 5: "5(Access is denied)". (Microsoft SQL Server, Error: 5120)

I have backups of the files, and even if I restore the files, I still get this error.

After restoring the file to the original path, I'm trying to re-attach the database from file, but get the error:

Cannot attach a database with the same name as an existing database.

But I can't see the previous database either, so I can't detach it.

How do I detach/remove/delete the old database so I can re-attach it from file?

2 Answers 2

1

You should try:

  1. Stopping SQL Server
  2. Copying the files back to where they should have been
  3. Start SQL Server

Failing that you can try and drop the database

  1. (In SSMS in master database) DROP Database < DatabaseName >
  2. Copying the files back to where they should have been
  3. Attach the database again
1
  • Thanks! I tried stopping and starting the database earlier, but I might have forgotten to copy the files back or something then. That worked now, however, and I was able to delete and re-attach the databases.
    – steffen
    Apr 4, 2014 at 11:11
0

In this case, you can run

select * from sys.databases

To check the databases that exist in your SQL Server instance. If the database exists, check its state_desc column value, it might not be online.

Then, run the following to see where its files are located:

SELECT type_desc, name, physical_name
FROM sys.master_files
WHERE database_id = DB_ID('Db_Name')

Replace Db_Name with your database name.

Based on that, you can take adequate actions.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .