script to restore database sql server from bak file, doesn't work

You need to use WITH REPLACE option in order to overwrite the existing database.

RESTORE DATABASE DB_Clients
FROM DISK = 'C:\OldDBClients.bak'
WITH REPLACE

Probably you also need to specify WITH MOVE options; in this case:

  • use RESTORE FILELISTONLY FROM DISK = 'C:\OldDBClients.bak' to know logical name of your MDF/LDF
  • use WITH MOVE options in your RESTORE

For example:

RESTORE DATABASE DB_Clients
FROM DISK = 'C:\OldDBClients.bak'
WITH REPLACE,
MOVE 'YourMDFLogicalName' TO '<MDF file path>',
MOVE 'YourLDFLogicalName' TO '<LDF file path>'

Please note that you can also DROP your empty DB_Clients database and use a simple RESTORE.


You should this syntax:

USE [master]
GO
RESTORE DATABASE DB_Clients FROM DISK = 'C:\OldDBClients.bak' WITH 
MOVE 'DB_Clients' TO 'D:\SQLServer\Data\DB_Clients.mdf',
MOVE 'DB_Clients_log' TO 'D:\SQLServer\Log\DB_Clients.ldf', REPLACE

It instructs SQL Server to overwrite the existing copy and specifies a valid location for your data and log files


Step 1: Check the logical file names with the help of the following command:

RESTORE FILELISTONLY 
FROM DISK = 'E:\DBBackups\mydb.bak'

Step 2: Use the logical names you get from the above query in the below query:

 RESTORE DATABASE [mydb_new]
  FILE = N'<MDFLogicalName>'
  FROM DISK = N'E:\DBBackups\mydb.bak'
  WITH 
    FILE = 1, NOUNLOAD, STATS = 10,
    MOVE N'<MDFLogicalname>'
    TO N'E:\DBBackups\mydb_new.mdf',
    MOVE N'<LDFLogicalName>'
    TO N'E:\DBBackups\mydb_new_0.ldf'

After running the above commands with the correct values you will see the output like this:

10 percent processed.
20 percent processed.
30 percent processed.
40 percent processed.
50 percent processed.
60 percent processed.
70 percent processed.
80 percent processed.
90 percent processed.
100 percent processed.
Processed 7672 pages for database 'mydb_new', file '<MDFLogicalname>' on file 1.
Processed 5 pages for database 'mydb_new', file '<LDFLogicalName>' on file 1.
RESTORE DATABASE ... FILE=<name> successfully processed 7677 pages in 0.780 seconds (76.893 MB/sec).

Completion time: 2019-10-20T11:35:31.8343787+05:30