简体   繁体   中英

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

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 .

  1. Take a backup of database one (DB1).

  2. Verify backup is valid.

  3. Get correct logical and physical file names

  4. Restore with a move command to create database two (DB2).

  5. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM