如何在同一台服务器上将整个数据库复制到另一个数据库?

时间:2013-01-14 09:13:56

标签: sql-server database

我想将数据库A完全复制到数据库B(相同的SQL Server)中 - 最简单的SQL或实用程序命令是什么? (数据库B应在复制前100%删除)

请注意,它可以是非SQL的东西,但无论如何我需要一键运行它。因此,只要我只需单击一下或从命令行运行复制,一些实用程序也可以接受。

SQL Server 2008R2或2012。

最佳,Askar

1 个答案:

答案 0 :(得分:0)

我根据大卫的想法提出了一个解决方案。它看起来像这样( Prod - 源数据库,演示 - 目标副本)

 DECLARE @backup varchar(300) = 'e:\Prod.bak'; 
 DECLARE @logic_db_file varchar(300) = 'koe'; 
 DECLARE @logic_log_file varchar(300) = 'koe_log'; 
 DECLARE @out_db_file varchar(300) = 'c:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Demo.mdf'; 
 DECLARE @out_log_file varchar(300) = 'c:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Demo_log.ldf'; 

 PRINT N'Backing up Production database.'
 BACKUP DATABASE Prod
    TO DISK = @backup WITH FORMAT;


 PRINT N'Restoring FILELISTONLY, see log file for data.'
 -- Restore the files to Demo
 RESTORE FILELISTONLY
    FROM DISK = @backup

 PRINT N'Getting exclusive access to Demo'  
 Alter database  Demo set single_user with rollback immediate
 drop database Demo



 PRINT N'Restoring backup to Test database'
 RESTORE DATABASE Demo
  FROM DISK = @backup
  WITH REPLACE,
  MOVE @logic_db_file TO @out_db_file, 
  MOVE @logic_log_file TO @out_log_file
 GO

  -- if you want you can do some SQL fixes to newly made DB

  PRINT N'Changing normal users to demo users, if account type is OK'

  USE Demo; 
  UPDATE USER_ACCOUNTS SET ACCOUNT_TYPE=3 WHERE (STATUS=1) AND (ACCOUNT_TYPE=1);  
  GO