问题
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.
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
来源:https://stackoverflow.com/questions/22462198/how-do-i-make-a-copy-of-an-sql-server-database-and-connect-to-it