Create a database from a .bak file in Microsoft SQL Server Management Studio

scyqe7ek  于 2023-10-15  发布在  SQL Server
关注(0)|答案(1)|浏览(135)

I'm trying to create a test database from the production database, but I keep getting the following error:
Restore of database 'TestLeo' failed.
Exclusive access could not be obtained because the database is in use.

Here are the options I used.

I'm not sure if something is missing. I've tried everything and can't seem to achieve it.

I was hoping to create a test database using a .bak from the production database.

gijlo24d

gijlo24d1#

I really, really, really wouldn't point and click through the UI to do this. It will lead you astray in about 15 different ways.

You want to create a copy of the database that's there. That means you need to give it a different name (since database names are unique) and move the files to a different location (since you can't overwrite the files for the existing database). So the first step is to run the following query in SSMS:

DECLARE @bak varchar(1024) = CONCAT
(
  'C:\DB\Testing\Backup\Production_Test',
  '\Production_Test_backup_2023_10_06_014001_8731590.bak'
);

RESTORE FILELISTONLY FROM DISK = @bak;

This will tell you the files you need to move. Let's say the logical names are Leo and Leo_log .

(This assumes the original source database was named Leo ; it's unclear if the error message is because you tried to use the original name or if you've tried to restore the test database more than once.)

Next you need to figure out where to put them. One way is to check where the source database's files are stored:

EXEC Leo.sys.sp_helpfile;

This will provide you paths in the filename column where the original database's data and log files are stored, maybe D:\data\Leo.mdf or C:\Program Files\...obnoxious path...\Leo.mdf . There may be more than two files, they may be spread in different locations. You want to replace Leo in those paths with Leo_copy or something similar.

You indicated in a comment you want the files to be in C:\DB\Testing\Data , so, fair enough. Leaving the above in as it may be helpful to future readers who don't know the paths ahead of time.

Now write a RESTORE statement like this:

RESTORE DATABASE Leo_copy
  FROM DISK = 'C:\...that path...\...that file....bak'
  WITH REPLACE, RECOVERY,
  MOVE 'Leo'     TO 'C:\DB\Testing\Data\Leo_copy.mdf',
  MOVE 'Leo_log' TO 'C:\DB\Testing\Data\Leo_copy.ldf';

If you can't do that because Leo_copy already exists and is in use (which is why your previous attempt failed), see:

相关问题