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

你离开我真会死。 提交于 2021-02-18 19:41:42

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/22462198/how-do-i-make-a-copy-of-an-sql-server-database-and-connect-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!