restore database sql server script code example

Example 1: Check database restore status sql script

SELECT r.session_id,r.command,CONVERT(NUMERIC(6,2),r.percent_complete)
AS [Percent Complete],CONVERT(VARCHAR(20),DATEADD(ms,r.estimated_completion_time,GetDate()),20) AS [ETA Completion Time],
CONVERT(NUMERIC(10,2),r.total_elapsed_time/1000.0/60.0) AS [Elapsed Min],
CONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0) AS [ETA Min],
CONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0/60.0) AS [ETA Hours],
CONVERT(VARCHAR(1000),(SELECT SUBSTRING(text,r.statement_start_offset/2,
CASE WHEN r.statement_end_offset = -1 THEN 1000 ELSE (r.statement_end_offset-r.statement_start_offset)/2 END)
FROM sys.dm_exec_sql_text(sql_handle))) AS [SQL]
FROM sys.dm_exec_requests r WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE')

Example 2: sql server restore database

--Step 1: Check the logical file names with the help of the following command:

  RESTORE FILELISTONLY 
  FROM DISK = 'E:\DBBackups\mydb.bak'

--Step 2: Use the logical names you get from the above query in the below query:

  RESTORE DATABASE [mydb_new]
  FILE = N'<MDFLogicalName>' 
  FROM DISK = N'E:\DBBackups\mydb.bak'
  WITH FILE = 1
	  ,NOUNLOAD
	  ,STATS = 10
	  ,MOVE N'<MDFLogicalname>' TO N'E:\DBBackups\mydb_new.mdf'
	  ,MOVE N'<LDFLogicalName>' TO N'E:\DBBackups\mydb_new_0.ldf'

Tags:

Sql Example