Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to copy a database (SQL Server 2008)

Dumb question - what's the best way to copy instances in an environment where I want to refresh a development server with instances from a production server?

I've done backup-restore, but I've heard detach-copy-attach and one guy even told me he would just copy the datafiles between the filesystems....

Are these the three (or two, the last one sounds kind of suspect) accepted methods?

My understanding is that the second method is faster but requires downtime on the source because of the detach aspect.

Also, in this situation (wanting an exact copy of production on a dev server) what's the accepted practice for transferring logins,etc.? Should I just backup and restore the user databases + master + msdb?

like image 284
user248260 Avatar asked Jan 11 '10 17:01

user248260


People also ask

How do I copy a SQL Server database to another server?

Right-click on the database and select Tasks and then Copy Database. Once you click on Copy Database then the following screen will appear. Click on "Next". Enter the Source server name (for example, Server A) and enter the Server Authentication mode and click on "Next".

Can I copy SQL Server database to another computer?

One of the easiest ways to do this is back up and restore. Another option you have is detaching your database from SQL Server, copying the MDF and LDF files to the target machine, and re-attaching there. Note, if you want to keep a copy of the database on the original server, you will also need to attach there too.


1 Answers

Easiest way is actually a script.

Run this on production:

USE MASTER;  BACKUP DATABASE [MyDatabase] TO DISK = 'C:\temp\MyDatabase1.bak' -- some writeable folder.  WITH COPY_ONLY 

This one command makes a complete backup copy of the database onto a single file, without interfering with production availability or backup schedule, etc.

To restore, just run this on your dev or test SQL Server:

USE MASTER;  RESTORE DATABASE [MyDatabase] FROM DISK = 'C:\temp\MyDatabase1.bak' WITH MOVE 'MyDatabase'   TO 'C:\Sql\MyDatabase.mdf', -- or wherever these live on target MOVE 'MyDatabase_log'   TO 'C:\Sql\MyDatabase_log.ldf', REPLACE, RECOVERY 

Then save these scripts on each server. One-click convenience.

Edit:
if you get an error when restoring that the logical names don't match, you can get them like this:

RESTORE FILELISTONLY FROM disk = 'C:\temp\MyDatabaseName1.bak' 

If you use SQL Server logins (not windows authentication) you can run this after restoring each time (on the dev/test machine):

use MyDatabaseName; sp_change_users_login 'Auto_Fix', 'userloginname', null, 'userpassword'; 
like image 94
MGOwen Avatar answered Sep 23 '22 20:09

MGOwen