Search This Blog

Showing posts with label Restore a SQL Server database to a new server?. Show all posts
Showing posts with label Restore a SQL Server database to a new server?. Show all posts

SQL Restore Database Backup From Another Server

On one of my recent projects, I needed to restore a backup from production to another development server, on a daily basis.  I used the logic below in a SQL Server Agent job on the dev server, to identify the remote backup, and restore it locally.  

Of course, the two servers have to be linked, but first I connect to the production server, and query the msdb database in order to retrieve the remote backup filename as @backupfile.  In this case, the format of the filename is like this:

     C:\MSSQL\Backup\DatabaseName_DB_20110122.bak

I wrote this into a BakFiles working table, so that I could manipulate it for the actual restore.  Because I was restoring from the remote server, I needed to update the filename to include the UNC path, like this:

    \\ProductionServerName\C$\MSSQL\Backup\DatabaseName_DB_20110122.bak
At that point, the local database is then set to SINGLE_USER in order to perform the restore, and set back to MULTI_USER afterward.  Pretty much like this:



  SET NOCOUNT ON;
  
  DECLARE @backupfile VARCHAR(100)
  SET @backupfile = (
   SELECT TOP (1) BUMF.physical_device_name
   FROM ProductionServerName.msdb.dbo.backupmediafamily AS BUMF 
   INNER JOIN ProductionServerName.msdb.dbo.backupmediaset AS BUMS   
    ON BUMF.media_set_id = BUMS.media_set_id 
   INNER JOIN ProductionServerName.msdb.dbo.backupfile AS BUF 
   INNER JOIN ProductionServerName.msdb.dbo.backupset AS BUS 
    ON BUF.backup_set_id = BUS.backup_set_id 
    ON BUMS.media_set_id = BUS.media_set_id
   WHERE (BUS.database_name = 'DatabaseName')
   AND (BUMF.physical_device_name LIKE  
    'C:\MSSQL\Backup\DatabaseName\DatabaseName_db_%') 
   ORDER BY BUS.backup_start_date DESC 
   )


  /* BAKFILES WORKING TABLE */
  TRUNCATE TABLE dbo.BakFiles
  INSERT dbo.BakFiles (bakfilename)
  SELECT (@backupfile)


    UPDATE dbo.BakFiles
  SET bakfilename =   
  REPLACE(bakfilename,'C:\','\\ProductionServerName\C$\')


   DECLARE @newfile VARCHAR(100)
  SELECT @newfile = [bakfilename] FROM dbo.BakFiles 


  /* SET DATABASE TO SINGLE_USER */
  ALTER DATABASE DatabaseName 
  SET SINGLE_USER WITH ROLLBACK IMMEDIATE


  /* RESTORE DATABASE */
  RESTORE DATABASE DatabaseName
  FROM DISK = @newfile
  WITH REPLACE, STATS = 5,
  MOVE 'DatabaseName_Data.mdf' TO   
   'D:\MSSQL10.MSSQLSERVER\MSSQL\Data\DatabaseName_Data.mdf',
  MOVE 'DatabaseName_Log.ldf' TO 
   'D:\MSSQL10.MSSQLSERVER\MSSQL\Log\DatabaseName_Log.ldf'
  GO


  /* SET BACK TO MULTI_USER */
  ALTER DATABASE DatabaseName
  SET MULTI_USER


  SET NOCOUNT OFF;
  
I also ran another step after this, to drop and recreate the database users, and then add them back to the appropriate role.  You'll need to replace 'ProductionServerName' and 'DatabaseName' to suit your needs, but that's pretty much it.  Providing your remote server is reachable, and the backup files are available, it should work just fine.  




How to copy SQL Server database from one machine to another(Copy DB from Instance to Another Instance )


Method 1: SQL Server has feature which copy database from one database to another database and it can be automated as well using SSIS.
Make sure you have SQL Server Agent Turned on as this feature will create a job. The same job will execute the task. Make sure that SSIS is properly configured as well with necessary security permissions. You can automate this process as well control error logging.
Following are the steps to copy database from one instance to another instance.

Specify Source Server

Specify Destination Server

Here you can select option if you want to keep the database ONLINE when it is being copied.

You can also select option of MOVE or COPY database as well.

Give appropriate database name.

On this screen you can select additional options to copy as well.

You create the package over here.

You can schedule the package using SQL Server Agent.

When this process is over it will show the success message and database will be copied to another server.
You can see how easy is the process to copy the database to another server.Watch SQL in Sixty Seconds Episode on same subject.



Method 2:How to manually copy a SQL Server database from one machine to another


Step by step instruction for manually copying a SQL Server database to a separate instance of SQL Server. This procedure applies to both MOVEit DMZ and MOVEit Central databases (examples below use MOVEit Central's "micstats" database with a SQL Server login/database user called "moveitcentral").


1.  Backup the current database. First, stop the services for the MOVEit product(s) using this database. To perform the backup, connect to SQL Server with using either SQL Server Management Studio or by opening a command prompt and running "sqlcmd.exe".  If using sqlcmd.exe, use the following command to connect to SQL Server (if connecting to SQLExpress you must specify this instance):

sqlcmd -S hostname[\SQLExpress] -U username

Issue the following query to backup the MOVEit database in question (our example uses "micstats" for the database name, here you should substitute the name of your database. You can also choose a different location to save the backup file.):

BACKUP DATABASE micstats
TO DISK = 'C:\tmp\micstats.bak'
WITH FORMAT,
NAME = 'Full Backup of micstats'
GO


2.  Copy the "micstats.bak" file to the new server.


3.  Restore the backup file on the new server. Stop the services for all MOVEit products using the destination database. The SQL Server service account must have Read access to the backup file. Connect to SQL server, either using Management Studio or sqlcmd.exe, and submit the following query from the master database (or any database other than the destination database).

Note this will overwrite all existing data if micstats already exists:


RESTORE DATABASE micstats
FROM DISK = 'C:\tmp\micstats.bak'
WITH RECOVERY, REPLACE
GO



4.  Next, check to make sure that a valid SQL Server username and login name exist. During the Restore process, any previous usernames tied to the MOVEit database will lose their Login Name associations, which means MOVEit will be unable to connect to the new database after a Restore. First, make sure that the Login Name that MOVEit is using to connect to SQL Server exists in the destination SQL Server instance (this should already exist if MOVEit has been installed). If using SQL Server Management Studio, you can verify this by looking under "Security - Logins".

Image
If using sqlcmd.exe, use the following query to list all SQL Server logins, you should see the MOVEit login listed here:

SELECT name FROM sys.server_principals
GO


5.  Once you verified and noted the name of the MOVEit Login, either create a new database user for the newly restored database and associate this with the MOVEit Login, or, re-associate the existing MOVEit database user with this login (if the SQL user was created using the MOVEit installation program, then you can assume the SQL server login and database user share the same name). The latter is most easily accomplished by submitting a simple query (substituing appropriate username/login):


ALTER USER moveitcentral WITH LOGIN=moveitcentral
GO


Alternativey, If creating a new database user, in addition to associating the user with the MOVEit login, also make sure to give the user "db_datareader" and "db_datawriter" permissions. Creating new user is most easily accomplish using the SQL Server Management Studio GUI. To add a new user, go to "Security - Users" underneath the database in question, right-click, and choose "New User...":
Image
Image



5.  Verify the database connection is working by either starting the MOVEit services or by testing the database connection through MOVEit's Config utility.

6. If you are running MOVEit DMZ, run the following command on the new SQL Server:
sp_configure 'clr enabled', 1;
To make the change take effect, you will have to run the following statement:
RECONFIGURE


However, according to Microsoft:
"WOW64 servers must be restarted before the changes to this setting will take effect. Restart is not required for other server types."

A WOW64 server would be a 32-bit version of SQL Server running on a 64-bit operating system.

Restore a SQL Server database to a new server?

As a DBA, I have been in many situations where I had to move databases to a new server due to old hardware, failed hardware, failed drives, etc. You have two options you could use to carry out this task:
  • SQL Server Management Studio (GUI)
  • T-SQL (Command line)
The method I prefer is T-SQL. It is simple and easy and avoids clicking the mouse all over the screen. This How do I... will show you both methods and allow you to choose the one you prefer.

Moving a database with Microsoft SQL Server Management Studio

We will begin by opening SQL Server Management Studio from the Start Menu by choosing Start and typing SQL Server in the Instant Search field (Figure A) The SQL Server Management Studio appears (Figure B) and it will be the main area you use to restore your backups.

Figure A

Search field

Figure B

SQL Server Management Studio
Note: I am going to assume that you already know how to backup a SQL Server database and that you have placed the backups on a file server or copied the backups to the new server. We will continue the tutorial from this point. Now that you have the Management Studio opened, right-click on Databases and choose Restore Database (Figure C).

Figure C

Restore Database
The Restore Database window appears and we will begin by typing the name of the Database we want to restore in the To Database field (Figure D) and choosing the From Device radio button to choose where your backup file is, shown in Figure E.

Figure D

To Database

Figure E

From Device
Your file now appears in the Select backups to restore text box. Place a check in the checkbox to continue as shown in Figure F.

Figure F

Select backups
You are now at the critical point of the restore where you choose Options from Select a Page. This is where you specify a new path for your database files. It is the same as the move option that will be discussed later in this tutorial. Simply type a new path to the database and log file (Figure G). For example, the current structure is the following:
  • C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\Database_Name_Here.mdf
  • C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\Database_Name_Here_1.ldf

Figure G

New path
We want to move these database files to a new path. Simply type the new path (Figure H). For purposes of this tutorial, we will move it to the following:
  • D:\ SQL\DATA\Database_Name_Here.mdf
  • D:\SQL\Logs\Database_Name_Here_1.ldf

Figure H

Move to path
You are now ready to click OK and let the database be restored (Figure I).

Figure I

Progress
You have now successfully restored and moved the database files as shown in Figure J andFigure K.

Figure J

Restored

Figure K

Database moved
Let's move on to my preferred method which eliminates all the point and clicking. You can do this same thing using a TSQL Restore with move statement.

Moving a database with T-SQL

Let's begin by opening up SQL Server Management Studio and clicking the New Query button (Figure L).

Figure L

New query
Our first step will be to run the following query:
Restore FILELISTONLY FROM DISK='d:\Business_Data.bak'
This query allows us to find out the logical name of the database and log file which is needed to appropriately restore a database to a new path (Figure M).

Figure M

Logical names
Once we have these names, we will use the following query to restore a database to a new location.
RESTORE DATABASE Business_Data_TSQL
FROM DISK='d:\Business_Data.bak'
WITH
MOVE 'Business_Data' TO 'D:\TSQL\Business_Data.mdf',
MOVE 'Business_Data_log' TO 'D:\TSQL\Business_Data_log.ldf'

Eg:
RESTORE DATABASE AdventureWorks2012
FROM AdventureWorksBackups
   WITH NORECOVERY, 
      MOVE 'AdventureWorks2012_Data' TO 
'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data\NewAdvWorks.mdf', 
      MOVE 'AdventureWorks2012_Log' 
TO 'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Data\NewAdvWorks.ldf';
RESTORE LOG AdventureWorks2012
   FROM AdventureWorksBackups

   WITH RECOVERY;
This query will restore the database to a new path (Figure N).

Figure N

Restore to new path
You can see where the logical name and the physical name are necessary for the RestoreFileListOnly TSQL statement. You can also add the stats clause if it is a big database to know the percentage finished (Figure O).
RESTORE DATABASE Business_Data_TSQL
FROM DISK='d:\Business_Data.bak'
WITH
MOVE 'Business_Data' TO 'D:\TSQL\Business_Data.mdf',
MOVE 'Business_Data_log' TO 'D:\TSQL\Business_Data_log.ldf', STATS=5

Figure O

Percentage finished

In this tutorial, I restored Full Backups. If you are restoring differential or transactions log backups, do not forget to use the With NORECOVERY clause in your statement.

Transfer logins from one SQL Server 2005 instance to another?