Import database backup (.bak file) into another database - sql-server

I'm using microsoft SQL server. I have a database that we can call database1 and its backup in .bak format.
I need to restore the backup to another, blank database that we can call database_temp, so both database must exist. I need to get and confirm some data from the database_temp archive and then delete it when I'll end my job.
what I did:
1) created new database "database_blank"
2) tasks - restore database. In source I choose "device" and then my .bak file, in destination I select database_temp.
3) in option I choose Overwrite the existing database with replace.
I got the error "Restore of database failed the file cannot be overwritten it is being used by database1 database"

You have to move the database files.
e.g.
RESTORE DATABASE [AdventureWorks] FROM DISK = 'c:\backup\Adv.bak'
WITH CHECKSUM,
MOVE 'AdventureWorks_Data' TO 'c:\mssql\data\AdventureWorksCopy_Data.mdf',
MOVE 'AdventureWorks_Log' TO 'c:\mssql\log\AdventureWorksCopy_Log.ldf',
RECOVERY, REPLACE, STATS = 10;
The first part of the move is the logical file name of the database file. Right click on the original database - Properties - Files to get the right names.
The full documented syntax can be found here

Related

RESTORE database with different name Fails - "The backup set holds a backup of a database other than the existing"

I have database backup A.bak
I want to restore that backup file, using the SQL Server Management Studio, into database B which has all the same tables/columns but just different name.
If I try to do the restore - I am getting error:
The backup set holds a backup of a database other than the existing
How can I resolve this? I tried renaming the .bak file but it didn't work
Specify the "Overwrite the existing database (WITH REPLACE)" option:

Database restore is missing tables

I am using SSMS 2017 and attempting to restore a SQL Server 2016 backup (.bak) file to a new database (the data file and log file names in the original backup are different from the new database I am restoring to), so for example, db1.bak is being used to create a new database called db2 through a restore operation.
After the restore completes, all stored procedures and views are present, but none of the tables are there.
These are the steps I've taken in SSMS to perform the restore:
Right click the Databases folder
Select "Restore Database"
Under the General Page: For "Source" I choose Device and select the db1.bak file, and for "Destination" I enter the name of the new database to be created from the backup (db2)
Under the Files Page I select Relocate all files to folder (both Data and Log folder paths have been pre-populated with the correct names) as have the Logical File Name and the Restore As paths.
Under the Options Page I either select nothing or select Overwrite the existing database (WITH REPLACE).
Once the restore completes "successfully" I expand the newly created db2 and click to expand the tables and receive this error message:
What am I doing wrong?
Here is the script:
USE [master]
RESTORE DATABASE [PdsClone] FROM DISK = N'F:\SQLBackups\PDS_backup_2017_12_12_001015_0199267.bak' WITH FILE = 1, MOVE N'PDS_Data' TO N'E:\Program Files\Microsoft SQL Server\MSSQL13.PDS\MSSQL\DATA\PdsClone.mdf', MOVE N'PDS_Log' TO N'E:\Program Files\Microsoft SQL Server\MSSQL13.PDS\MSSQL\DATA\PdsClone_log.ldf', NOUNLOAD, REPLACE, STATS = 5 GO
UPDATE
I had the server group add another disk to that server and moved the SQL backups there, and I was able to successfully complete the restore this morning. I had previously cleaned off most of the backup files, but could it have been a space issue that prevented the tables from showing up in the restore? Every try it indicated success but no tables. They are there now, and I am thankful for your suggestions and help!
Not really an answer to what happened, but perhaps SSMS was doing something a little buggy as #JeroenMostert suggested.

Create Duplicate SQL Database for Testing

I have created a database on SQL server and a front end user application in winforms c#.
It's up and running and working fine, but I've now been asked to set up a test version by the client for training new employees, so they can put in dummy data whilst they are trained without effecting the 'real' live database.
When I installed the database I had it all scripted, but things have changed since, and I don't particularly want to script all the tables again.
Is there a fast, convenient way of duplicating the database (and its data) on the same server, but under a different name?
EDIT (subsequent to Tony Hopkinson post)
I've got as far as this
exec sp_addumpdevice 'Disk','MyDatabaseBackup',N'D:\MyDatabaseBackup'
Restore Database MyDatabase From MyDatabaseBackup With File = 1,
Move 'MyDatabase' To N'C:\Program Files\Microsoft SQL
Server\MSSQL11.SQLE\MSSQL\DATA\MyDatabaseTEST.mdf',
Move 'MyDatabase_Log' To N'C:\Program Files\Microsoft SQL
Server\MSSQL11.SQLE\MSSQL\DATA\MyDatabaseTEST_log.ldf',
NORECOVERY, NOUNLOAD, STATS = 10
RESTORE LOG [MyDatabaseTEST] FROM [MyDatabaseBackup] WITH FILE = 2, NOUNLOAD, STATS = 10
exec sp_dropdevice MyDatabaseBackup
But I'm getting the following error message
Msg 3234, Level 16, State 2, Line 2
Logical file 'MyDatabase' is not part of database 'MyDatabase'. Use RESTORE FILELISTONLY to list the logical file names.
Msg 3013, Level 16, State 1, Line 2
RESTORE DATABASE is terminating abnormally.
Msg 3154, Level 16, State 4, Line 6
The backup set holds a backup of a database other than the existing 'MyDatabaseTEST' database.
Msg 3013, Level 16, State 1, Line 6
RESTORE LOG is terminating abnormally.
Device dropped.
use copy database option in SQL server management studio
I found this method to be most effective on SQL Server 2005 and 2008, Express Editions:
From the Microsoft Docs:
Right click on the database you want to duplicate and choose Tasks->"Back Up..."
Save the back up to a .bak file
Right click on the "Databases" folder in the Object Explorer in SQL Server Management Studio
Choose "Restore Database"
As the source, select "File" and point to the .bak file you created earlier.
Change the name of the database to restore to (this was the key step for me - you are not constrained to the options in the dropdown.)
SSMS will restore your .bak file to a new database, according to the name that you give it.
First do a full backup your current database, which of course you have :)
The you restore it to another one
e.g. something like
exec sp_addumpdevice 'Disk','LiveDataBackup',N'Insert backup file name here including path'
Restore Database TestData From LiveDataBackup With File = 1,
Move 'LiveData' To N'Path to where sqlserver expects the mdfs to be\TestData.mdf',
Move 'LiveData_Log' To N'Path to where sqlserver expects the ldf to be\TaxData1.ldf',
NORECOVERY, NOUNLOAD, STATS = 10
RESTORE LOG [TestData] FROM [LiveDataBackup] WITH FILE = 2, NOUNLOAD, STATS = 10
exec sp_dropdevice LiveDataBackup
Above assume your live database is cunningly named LiveData and test, TestData.
The path to where the mdf and ldf will be depends on the version of sql server and the instance name
It should be something like
C:\Program Files\Microsoft SQL Server\MSSQL11.DENALI\MSSQL\DATA\
MSSQL11 because it's sql 2012, and DENALI is my instance name and it was installed by default in C: \Program Files
Also there's no with replace, so if you wanted to run it again, you'd need to Drop your test database.
There's probably some way to do this from the GUI, but I found it a massive PIA trying to relate the UI, to what I wanted to do.
using MS SQLServer 2012, you need to perform 3 basic steps
first, generate .sql file containing only the structure of the source DB
=> right click on the source DB and then Tasks then Generate Scripts
=> follow the wizard and u can save the .sql file locally
Second, replace in .sql file the source db with the destination one
=> right click on the destination file, open the .sql file and press New Query and Ctrl-H or (edit - find and replace - Quack replace)
finally, populate with data
=> right click on the detination DB, then Tasks and then Import Data
=> Data source drop dow set to ".net framework data procider for sql server" + set connection string text field under DATA ex: Data Source=Mehdi\SQLEXPRESS;Initial Catalog=db_test;User ID=sa;Password=sqlrpwrd15
=> Same thing to do with the destination
=> check the table you want to transfer or check box besides "source :....." to check all of them
you are done.
You want to copy one Database_Production to Database_Testing in the same server. I would take database_production database as an example. I tested it in my server successfully.
Firstly, backup the database Database_Production.
BACKUP DATABASE Database_Production TO DISK ='H:\test\Database_Production.bark';
Secondly, restore Database_Production and this could rename the database name to Database_Testing.
RESTORE DATABASE Database_Testing
FROM DISK='H:\test\Database_Production.bark'
WITH
MOVE 'Database_Production_Data' TO 'H:\test\Database_Testing_Data.mdf',
MOVE 'Database_Production_log' to 'H:\test\Database_Testing_Data.ldf';
GO
Then the database Database_Production is copied to database Database_Testing. The MOVE statement causes the data and log file to be restored to the specified locations. You do not need to create database Database_Testing and the script would create it.
Dump your database into a backup file
Re-create your database from your dump - that is a script which you can run - with different name (that you have to change into the script)
You can follow (this)
If you need to create a database on the same server just create the empty database. Right Click on it and Select Restore-> Choose the database you want to make a copy of and click okay.

SQL-Server: The backup set holds a backup of a database other than the existing

I am trying to restore a SQL Server backup file for my database, but it is throwing an error as follow:
The backup set holds a backup of a database other than the existing
My database in SQL Server 2008 and the backup file is in 2005.
What can be the problem?
I too came across this issue.
Solution :
Don't create an empty database and restore the .bak file on to it.
Use 'Restore Database' option accessible by right clicking the "Databases" branch of the SQL Server Management Studio and provide the database name while
providing the source to restore.
Also change the file names at "Files" if the other database still exists. Otherwise you get "The file '...' cannot be overwritten. It is being used by database 'yourFirstDb'".
Either:
1) Use WITH REPLACE while using the RESTORE command (if using the GUI, it is found under Options -> Overwrite the existing database (WITH REPLACE)).
2) Delete the older database which is conflicting and restore again using RESTORE command.
Check the link for more details.
First create a blank database of the same name. Then go for the restore option
Under Options on the left pane don't forget to select
Overwrite the existing database
Preserve the replication settings
That's it
I was facing same problem and found the solution by doing this, using SSMS 2014
Just select the Option Overwrite the existing database(WITH REPLACE)
This causes always due to version incompatibility.
follow these steps to solve:
Step 1: Create a database with your preferred name. (In our case AdventureWorks)
Step 2: Write click on the database and click on Tasks >> Restore >> Database…
Step 3: On the restore screen go to third selection of Options. Now select the checkbox “Overwrite the existing database (WITH REPLACE)”
Step 4: Click OK. It should successfully restore the database.
Note: When you restore a database WITH REPLACE it will overwrite the old database.
USE [master];
GO
CREATE DATABASE db;
GO
CREATE DATABASE db2;
GO
BACKUP DATABASE db TO DISK = 'c:\temp\db.bak' WITH INIT, COMPRESSION;
GO
RESTORE DATABASE db2
FROM DISK = 'c:\temp\db.bak'
WITH REPLACE,
MOVE 'db' TO 'c:\temp\db2.mdf',
MOVE 'db_log' TO 'c:\temp\db2.ldf';
Simple 3 steps:
1- Right click on database → Tasks → restore → Database
2- Check Device as source and locate .bak (or zipped .bak) file
3- In the left pane click on options and:
check Overwrite the existing database.
uncheck Take tail-log backup before restore
check Close existing connection to destination database.
Other options are really optional (and important of course)!
If you are using the script approach and have an error concerning the LDF and MDF files, you can first query the the backup file for the logical names (and other details) of files in the backup set, using the following:
-- Queries the backup file for the file list in backup set, where Type denotes
-- type of file. Can be L,D,F or S
-- info: https://learn.microsoft.com/en-us/sql/t-sql/statements/restore-statements-filelistonly-transact-sql
RESTORE FILELISTONLY FROM DISK = 'C:\Temp\DB_backup.bak'
GO
You will get results similar to the following:
And then you can use those logical names in the queries:
-- Script assumes you want MDF and LDF files restored on separate drives. Modify for your scenario
RESTORE DATABASE DB
FROM DISK='C:\Temp\DB_backup.bak'
WITH REPLACE,
MOVE 'DB' TO 'E:\MSSQL\Data\DB.mdf', -- "DB" is the mdf logical name from query above
MOVE 'DB_log' TO 'F:\MSSQL\Logs\DB.ldf'; -- "DB_log" is LDF logical name from query above
More info on RESTORE FILELISTONLY can be found from the SQL Server docs.
Its because the .mdf and .ldf Files from the original Db were locate at maybe c:\programFile\.... and this info is saved in the Backup!
If you create the same DB on a different SQL Server where the installation is on c:\program Files (x86)\ .... you can not restore as usually. You need to relocate the path for .mdf and .ldf Files.
Therefore:
Create a empty DB on the new Server
Right click on the empty Db > Tasks > Restore > Database > click Device select your .bak Files > Select Db to restore into
click on Files at left side > Select "Relocate all Files to Folder"
click Options on the left site > click on Overwrite
Done!
Hope it helps!
I had ran into similar problem today. Tried all the above solutions but didn't worked. So posting my solution here.
Don't forget to uncheck Tail-long Backup before restore
Hope it help others too!
Also as important is to make sure that, your database name matches the data base name in the backup you are trying to restore. If it does not match, you will get the same error.
system.data.sqlclient.sqlerror:The backup set holds a backup of a database other than the existing 'Dbname' database
I have came across to find soultion
Don't Create a database with the same name or different database name !Important.
right click the database | Tasks > Restore > Database
Under "Source for restore" select "From Device"
Select .bak file
Select the check box for the database in the gridview below
To DataBase: "Here You can type New Database Name" (Ex:DemoDB)
Don't select the Existing Database From DropDownlist
Now Click on Ok Button ,it will create a new Databse and restore all data from your .bak file .
you can get help from this link even
Hope it will help to sort out your issue...
Before doing anything else, confirm if your backup is Full or Differential. If you're trying to create a new database out of a differential backup, no matter what you do you will encounter the error.
Same issue with me.The solution for me is:
Right click on the database.
Select tasks, select restore database.
Click options on the left hand side.
Check first option OverWrite the existing database(WITH REPLACE).
Go to General, select source and destination database.
Click OK, that's it
I was just trying to solve this issue.
I'd tried everything from running as admin through to the suggestions found here and elsewhere; what solved it for me in the end was to check the "relocate files" option in the Files property tab.
Hopefully this helps somebody else.
Some of you have highly over complicated this. I found this to be extremely simple.
1) Create a database with the same name as your .bak file database name !Important
2) right click the database | Tasks > Restore > Database
3) Under "Source for restore" select "From Device"
4) Select .bak file
5) Select the check box for the database in the gridview below
6) Under "Select a Page" on the right Select "Options"
7) Select the checkbox labeled "Preserve the replication settings(WITH KEEP_REPLICATION)
Now Go back to the General page and click OK to restore the database...That is it.
I had to create new db on my local for testing & i had a back up from my prod. I created the db first and tried to run the BAK on top of the new db which produced this error for me. I deleted the db and restored it while sourcing the new db name in the restore screen itself. The db was automatically created on restore.
I got work done through alternate way, using Generate scripts. That did work for me as Backup-Restore didn't help to resolve the issue due to same error.
In the Options, change the "Restore As" file name to the new database mdf and ldf. It is referencing the source database .mdf and .ldf files.
You can restore to a new DB, verify the file name syntax, it ll be in the log file, for the new SQL version ll be a "_log" suffix
ad check the overwrite the existing database flag in option tab
Fabio
This helped me to import the back-up file from the system drive
Create a database with the same name(preferably) as your .bak file database name
Right click the database > Tasks > Restore > Database
Under "Source for restore" select "From Device"
Select the .bak file selecting the path from the system
Select the check box for the database in the list box below
Under "Select a Page" on the right Select "Options"
Select the checkbox labeled "Preserve the replication settings(WITH KEEP_REPLICATION)
Select the checkbox for Overwrite the existing database(WITH REPLACE)
Now Go back to the General page and click OK to restore the database...
Im sure this problem is related to the files and folders permissions.
I was trying to restore a production database to a staging database on the same server.
The only thing that worked in my case was restore to a new blank database. This worked great, did not try to overwrite production files (which it would if you just restore production backup file to existing staging database). Then delete old database and rename - the files will keep the new temp name but in my case that is fine.
(Or otherwise delete the staging database first and then you can restore to new database with same name as staging database)
instead of click on Restore Database click on Restore File and Filegroups..
thats work on my sql server
I had the same issue but on PS. I leave it here in case someone is trying to do the same
Restore-SqlDatabase -ServerInstance "<your instance name>" -Database "<your db name>" -BackupFile "<backup file route>.bak" -ReplaceDatabase
remember to use Set-ExecutionPolicy Unrestricted -Force and import import-module sqlps. Don't forget to set back your Execution Policy back to restricted once you are done.
Usually dealing with .bak files are coming with headaches, a more straight forward way is using sqldump files to transfer databases.
Generate script of current database you want to move or copy.
Instead of entire database, select All Tables.
From the option menu choose save as script, and click on advance button and set the following configs (I am suing MSSQL 2016):
Now, where you want to import these data, create a new database, switch to this new database (I mean set it as default)
Finally run the script, all table and data will be imported.
Good Luck.
List item

Import .bak file to a database in SQL server

I have a file with .bak extension.
How can I import this date to a database in SQL Server?
On SQL Server Management Studio
Right click Databases on left pane (Object Explorer)
Click Restore Database...
Choose Device, click ..., and add your .bak file
Click OK, then OK again
Done.
This will show you a list of database files contained in DB.bak:
RESTORE FILELISTONLY
FROM DISK = 'D:\3.0 Databases\DB.bak'
You will need the logical names from that list for the MOVE operation in the second step:
RESTORE DATABASE YourDB
FROM DISK = 'D:\3.0 Databases\DB.bak'
and you have to move appropriate mdf,ndf & ldf files using
With Move 'primarydatafilename' To 'D:\DB\data.mdf',
Move 'secondarydatafile' To 'D:\DB\data1.ndf',
Move 'logfilename' To 'D:\DB\log.ldf'
You can simply restore these database backup files using native SQL Server methods, or you can use ApexSQL Restore tool to quickly virtually attach the files and access them as fully restored databases.
Disclaimer: I work as a Product Support Engineer at ApexSQL
Instead of choosing Restore Database..., select Restore Files and Filegroups...
Then enter a database name, select your .bak file path as the source, check the restore checkbox, and click Ok. If the .bak file is valid, it will work.
(The SQL Server restore option names are not intuitive for what should a very simple task.)
On Microsoft SQL Server Management Studio 2019:
On Restore Database window:
Choose Device
Choose Add and pick target file
OK to confirm
OK to confirm restore
Connect to a server you want to store your DB
Right-click Database
Click Restore
Choose the Device radio button under the source section
Click Add.
Navigate to the path where your .bak file is stored, select it and click OK
Enter the destination of your DB
Enter the name by which you want to store your DB
Click OK
Done
Although it is much easier to restore database using SSMS as stated in many answers.
You can also restore Database using .bak with SQL server query, for example
RESTORE DATABASE AdventureWorks2012 FROM DISK = 'D:\AdventureWorks2012.BAK'
GO
In above Query you need to keep in mind about .mdf/.ldf file location.
You might get error
System.Data.SqlClient.SqlError: Directory lookup for the file "C:\PROGRAM FILES\MICROSOFT SQL SERVER\MSSQL.1\MSSQL\DATA\AdventureWorks.MDF" failed with the operating system error 3(The system cannot find the path specified.). (Microsoft.SqlServer.SmoExtended)
So you need to run Query as below
RESTORE FILELISTONLY
FROM DISK = 'D:\AdventureWorks2012.BAK'
Once you will run above Query you will get location of mdf/ldf use it Restore database using query
USE MASTER
GO
RESTORE DATABASE DBASE
FROM DISK = 'D:\AdventureWorks2012.BAK'
WITH
MOVE 'DBASE' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DBASE\MSSQL\DATA\DBASE.MDF',
MOVE 'DBASE_LOG' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.DBASE\MSSQL\DATA\DBASE_1.LDF',
NOUNLOAD, REPLACE, NOUNLOAD, STATS = 5
GO
Source:Restore database from .bak file in SQL server (With & without scripts)
Simply use
sp_restoredb 'Your Database Name' ,'Location From you want to restore'
Example: sp_restoredb 'omDB','D:\abc.bak'
You can use node package, if you often need to restore databases in development process.
Install:
npm install -g sql-bak-restore
Usage:
sql-bak-restore <bakPath> <dbName> <oldDbName> <owner>
Arguments:
bakpath, relative or absolute path to file
dbName, to which database to restore (!! database with this name will be deleted if exists !!)
oldDbName, database name (if you don't know, specify something and run, you will see available databases after run.)
owner, userName to make and give him db_owner privileges (password "1")
!! sqlcmd command line utility should be in your PATH variable.
https://github.com/vladimirbuskin/sql-bak-restore/

Resources