Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Solution: The WITH MOVE Clause Can Be Used to Relocate One or More Files

5.00/5 (3 votes)
9 Jan 2014CPOL 73.4K  
The WITH MOVE clause can be used to relocate one or more files

Today, while working with SQL Server, I was trying to restore a DB from .bak file and got a strange error while restoring using the normal procedure. I was working on SQL Server 2008 R2 and the backup was from an old version making me think the problem may be because of incorrect SQL versions. The error read as below:

SQL
TITLE:
Microsoft SQL Server Management Studio
——————————
Restore failed for Server ‘MYSQLSERVER’. (Microsoft.SqlServer.SmoExtended)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.4000.0+
((KJ_PCU_Main).120628-0827+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.
FailedOperationExceptionText&EvtID=Restore+Server&LinkId=20476

——————————

ADDITIONAL INFORMATION:

System.Data.SqlClient.SqlError: 
File ‘C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\MyDatabase.mdf’ 
is claimed by ‘MyDatabase_log’(2) and ‘MyDatabase’(1). 
The WITH MOVE clause can be used to relocate one or more files. (Microsoft.SqlServer.Smo)

For help, click http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.4000.0+((KJ_PCU_Main).120628-0827+)&LinkId=20476.

As usual, the links provided by SQL Server were of least use. After reading the error closely a few times, I understood the error is not related to SQL Server version but is related to the files being used by the restoration. It was found that the .mdf file of the database is being used twice by the restoration process and hence tried to restore the database using a script. Below is the solution to restore the database using a script.

SQL
RESTORE DATABASE [MyDatabase]
FROM DISK = N'E:\MyDatabase.bak'
WITH FILE = 1,
MOVE N'MyDatabase'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Data\MyDatabase.mdf',
MOVE N'MyDatabase_Log'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Data\MyDatabase.ldf',
NOUNLOAD, REPLACE, STATS = 10
GO

Using the script and changing proper values for your database, you will be able to restore the database with ease. Hope you like this post! :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)