How do I make a copy of an SQL Server database and connect to it? - sql-server

I'm working on vb.NET 2013 and SQL server 2008R2.
I have this situation to resolve:
I have a database "DB1". I want to create a copy of this database on the same SQL server with another name "DB2", and after make this database ready to connect.
How can I do this through code from Vb.NET?

Check out this tech net link for restore with new file names.
http://technet.microsoft.com/en-us/library/ms190447(v=sql.105).aspx.
Take a backup of database one (DB1).
Verify backup is valid.
Get correct logical and physical file names
Restore with a move command to create database two (DB2).
Change ownership to SA. Defaults to SQL login that creates the database
Here is a script that I tested on my laptop. Nice thing about backup is no need for down time. If you decide to take off line, copy data files, and create database for attach, down time is created.
-- Sample database
USE AdventureWorks2012;
GO
-- 1 - Make a backup
BACKUP DATABASE AdventureWorks2012
TO DISK = 'C:\mssql\backup\AdventureWorks2012.Bak'
WITH FORMAT,
MEDIANAME = 'SQLServerBackups',
NAME = 'Full Backup of AdventureWorks2012';
GO
-- Use master
USE master
GO
-- 2 - Is the backup valid
RESTORE VERIFYONLY
FROM DISK = 'C:\mssql\backup\AdventureWorks2012.Bak';
GO
-- 3 - Check the logical / physical file names
RESTORE FILELISTONLY
FROM DISK = 'C:\mssql\backup\AdventureWorks2012.Bak';
GO
-- 4 - Restore the files change the location and name
RESTORE DATABASE Adv2012
FROM DISK = 'C:\mssql\backup\AdventureWorks2012.Bak'
WITH RECOVERY,
MOVE 'AdventureWorks2012_Data' TO 'c:\mssql\data\MyAdvWorks_Data.mdf',
MOVE 'AdventureWorks2012_Log' TO 'c:\mssql\log\MyAdvWorks_Data.ldf';
GO
-- 5 - Switch owner to system admin
ALTER AUTHORIZATION ON DATABASE::Adv2012 TO SA;
GO

Related

Restoring database from script

I have created a small scrip to restore databases from backups. Once the script is run it displays
RESTORE DATABASE successfully processed 28818 pages in 1.568 seconds
(143.584 MB/sec).
I have more code to alter the database, alter a few views and sp too but I am getting the following error; User does not have permission to alter database 'GreyGoo', the database does not exist, or the database is not in a state that allows access checks.
I have noticed too that I cannot see the database in the object explorer
this is what I use to restore the DB from a backup
if DB exists set to a single user
if DB exist drop database
Ran the below script
RESTORE DATABASE GreyGoo FROM DISK = 'C:\Bkp\GreyGoo_backup_2020_03_02_180002_5403592.bak'
WITH
MOVE 'GreyGoo' TO 'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\DATA\GreyGoo.mdf',
MOVE 'GreyGoo_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\DATA\GreyGoo.ldf',
REPLACE;
set DB to multi-users and other properties
So what is the problem and how can I solve it, I am currently testing my code on SQL Server 2008
Thanks
During your restore process, you will need to ensure your
login / permissions are correct.
if another previous database with same name is not there, if so delete it. Perhaps from a previous attempt
You can also turn off recovery option like below, recovery is default
RESTORE FILELISTONLY
Sample -- MSDN
USE master;
GO
-- First determine the number and names of the files in the backup.
-- AdventureWorks2012_Backup is the name of the backup device.
RESTORE FILELISTONLY
FROM AdventureWorks2012_Backup;
-- Restore the files for MyAdvWorks.
RESTORE DATABASE MyAdvWorks
FROM AdventureWorks2012_Backup
WITH RECOVERY,
MOVE 'AdventureWorks2012_Data' TO 'D:\MyData\MyAdvWorks_Data.mdf',
MOVE 'AdventureWorks2012_Log' TO 'F:\MyLog\MyAdvWorks_Log.ldf';
GO
EXEC msdb.dbo.sp_delete_database_backuphistory #database_name = N'MYDB'
GO
USE [master]
GO
/* Database [MYDB] */
DROP DATABASE [MYDB]
GO
USE [master]
RESTORE DATABASE [MYDB] FROM DISK = N'E:\FTP\local_MYDB_01.bak' WITH FILE = 1, MOVE N'blank' TO N'E:\DBs\2019\MYDB.mdf', MOVE N'blank_log' TO N'E:\DBs\2019\MYDB.ldf', NOUNLOAD, STATS = 5
GO

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.

Duplicate a Database in SQL Server 2014

I have a live database. I need to create a test database with all the data from the live one, but I've encoutneered an error. I've tried to create this new one by restoring from a "live database .bak", but an error message appears saying that could not do the process because the database is in use. Also, I don't know why but after that, the live database starts restoring and keep on it until getting stuck. It does not finish restoring and I have to force stop, deleting the live database and restoring from scratch. Checking the activity log it seems that it goes to restoring mode after failing to create a backup of the database log and that's what happens right after I try to create the new test database using the .bak.
What am I doing wrong? Is there another way to duplicate the live database to use it as a test one?
Note: I've done the process when nobody is using the DB or connected to it but no success.
You need to relocate/rename the Files. Just changing the Database name that you are restoring to may not be changing the Database File and Log File that SQL is trying to actually create when you perform the restore. Go to the Option page of the Restore Database and ensure the files are pointing to Valid locations and not trying to utilize the same files as the Live database.
--At First take ypur database backup and restore it as DatabaseName_Test and also change Datafiles As database _test.mdf and DatabaseName_test_log.ldf
--try to follow as below script
USE master
GO
BACKUP DATABASE [DatabaseName]
TO DISK = N'D:\SQLSERVER_Installation\setup\MSSQL12.SQLSERVER2014\MSSQL\Backup\DatabaseName.bak'
WITH COPY_ONLY, NOFORMAT, NOINIT,
NAME = N'DatabaseName-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10
GO
USE [master]
RESTORE DATABASE [DatabaseName_Test] FROM
DISK = N'D:\SQLSERVER_Installation\setup\MSSQL12.SQLSERVER2014\MSSQL\Backup\DatabaseName.bak'
WITH FILE = 2,
MOVE N'DatabaseName' TO N'D:\SQLSERVER_Installation\setup\MSSQL12.SQLSERVER2014\MSSQL\DATA\DatabaseName_test.mdf',
MOVE N'DatabaseName_log' TO N'D:\SQLSERVER_Installation\setup\MSSQL12.SQLSERVER2014\MSSQL\DATA\DatabaseName_test_log.ldf', NOUNLOAD, STATS = 5
GO

Retrieve SQL Server database from old Windows

I have just changed my Windows. In the old SQL Server, I had some important databases and I want to find and copy them to new installed windows and SQL Server.
How can I find and copy old databases from old windows and copy them to new SQL Server?
P.S: Actually, my I have changed my hard disk and all of the old files
is located on my old hard drive and I want to find and copy the old
server from old hard drive to new drive.
You can either backup the prior database or detach the database .mdf (data) and .ldf (log) file and reattach via http://blog.sqlauthority.com/2007/08/24/sql-server-2005-t-sql-script-to-attach-and-detach-database/
or
Backup your database and restore. Six of one, half dozen of the other.
-- Step 1 : Detach Database using following script
USE [master]
GO
EXEC MASTER.dbo.sp_detach_db #dbname = N'AdventureWorks',
#keepfulltextindexfile = N'true'
GO
-- Step 2 : Move Data files and Log files to new location
-- Do this step and move to Step 3
-- Step 3 : Attach Database using following script
USE [master]
GO
CREATE DATABASE [AdventureWorks] ON
( FILENAME = N'C:\Data\AdventureWorks_Data.mdf' ),
( FILENAME = N'C:\Data\AdventureWorks_Log.ldf' )
FOR ATTACH
GO
IF EXISTS ( SELECT name
FROM MASTER.sys.databases sd
WHERE name = N'AdventureWorks'
AND SUSER_SNAME(sd.owner_sid) = SUSER_SNAME() )
EXEC [AdventureWorks].dbo.sp_changedbowner #loginame=N'sa',
#map=false
GO
Create a Full Database Backup
There are other options as well (Red Gate tools, Visual Studio Tools, etc)
Make sure your database engine is running. Connect to your old server using SSMS (SQL Server Management Studio) and backup the database. Then transfer the backup file to the new system and restore the backup using SSMS again.

Restoring database - Cannot access file because it is in use by another process

I have a backup of a database from another SQL Server 2005 machine. I'm attempting to restore it to my SQL Server 2008 instance.
I have created a new database for the restore to go in to, but when attempting the restore with the following (generated by ssms):
RESTORE DATABASE [WendyUAT]
FROM DISK = N'D:\wanda20130503.bak'
WITH FILE = 1,
MOVE N'Wendy' TO N'D:\databases\\WendyUAT.mdf',
MOVE N'Wendy_log' TO N'D:\databases\\WendyUAT.ldf',
MOVE N'sysft_WendyFti' TO N'D:\databases\\WendyUAT.WendyFti',
NOUNLOAD, REPLACE, STATS = 10
I get the following error:
System.Data.SqlClient.SqlError: The operating system returned the error '32 (The process cannot access the file because it is being used by another process.)' while attempting 'RestoreContainer::ValidateTargetForCreation' on 'D:\databases\WendyUAT.mdf'.
As far as I can tell (using Process Explorer etc) nothing else is using the file. I've disabled real-time protection in windows defender. I just cannot understand why SQL Server thinks the file is in use as windows explorer lets me delete it with no problems so Windows doesn't seem to think it's in use.
Any help would be gratefully received.
How are you connecting to your SQL Server in your application before running this backup? What database are you connecting to?
You cannot connect to the WendyUAT database and use it when you want to restore it - you'll have to explicitly use some other database, e.g. master, before running your SMO restore code
All my T-SQL restore scripts will always include:
USE [master]
GO
RESTORE DATABASE [WendyUAT] ......
So if you run this backup from your app, make sure you explicitly connect to e.g. master before running this T-SQL restore script
Update:
Is this something you did on purpose, or might it just be a typo??
MOVE N'Wendy' TO N'D:\databases\\WendyUAT.mdf',
* **
* *
* * two backslashes here -why???
* only one backslash here...
Does it work if you use single backslashes only??
RESTORE DATABASE [WendyUAT]
FROM DISK = N'D:\wanda20130503.bak'
WITH FILE = 1,
MOVE N'Wendy' TO N'D:\databases\WendyUAT.mdf',
MOVE N'Wendy_log' TO N'D:\databases\WendyUAT.ldf',
MOVE N'sysft_WendyFti' TO N'D:\databases\WendyUAT.WendyFti',
NOUNLOAD, REPLACE, STATS = 10
Try following script before restore
alter database DB_NAME set offline with rollback immediate;
and this script after restore to enable multi user
alter database DB_NAME set online with rollback immediate;
In my case I had installed two instances of SQL Server (2008 R2 and 2012). I had to stop one SQL Server service (2008 R2) from my two available SQL instances. This helped me to resolve this issue and I could restore my database.
I have the same issue.
What I did is that I just rename the Destination database to different name, then the restoration executed successfully. After the restoration, I just rename it to my desired database name.

Resources