How to use the command line on SQLServer database backup and restore to another new database

How to use the command line on SQLServer database backup and restore to another new database

First, we should have a regular backup plan, you can add a backup task in the database agents, the recommended practice is as follows:

Perform once a week: full backup

Executed once a day: Differential backup

Every hour: transaction log backup (transaction log can be achieved to restore the database to a specified second level)

Here we command to back up the database, these commands can also be applied to the backup job to go

DECLARE @FULLPATH NVARCHAR(100)
declare @DIFFPATH nvarchar(100)
declare @LOGPATH nvarchar(100)
SET @FULLPATH='数据库全备份路径.bak'
SET @DIFFPATH='数据库差异备份路径.bak'
SET @LOGPATH='数据库日志备份路径.bak'
BACKUP DATABASE 数据库名称 TO DISK = @DIFFPATH with DIFFERENTIAL #差异备份,仅备份数据
BACKUP DATABASE 数据库名称 TO DISK = @FULLPATH #完全备份,仅备份数据
BACKUP LOG 数据库名称 TO DISK=@LOGPATH #事务日志备份

Now we will need to log copied to other computers, we begin to restore the database to a new database

First, we may not know what the logical file name of the database that need to check your log file

#首先我们可能并不知道数据库的逻辑文件名是什么,需要查询一下日志文件
DECLARE @PATH NVARCHAR(100)
SET @PATH='数据库全备份路径.bak'
RESORE FILELISTONLY FROM DISK=@PATH

Secondly, after the inquiry into the logical file name can be used for the following recovery

#使用以上查询的逻辑文件名
RESTORE DATABASE 新数据库名称 FROM DISK = @PATH with RECOVERY,REPLACE,
      MOVE 'DATA' TO 'C:\BAK\DATA\DATA.mdf',
      MOVE 'DATA_LOG' TO 'C:\BAK\DATA\DATA.ldf'

Finally, if we need to continue to use the transaction log to recover data, then restore the above command,

WITH后面需要变成NORECOVERY
RESTORE DATABASE 新数据库名称 FROM DISK = @PATH with NORECOVERY

You can then right in the new database, select Restore, select a transaction log, choose our log file, you can select the target time required to recover.

Published 48 original articles · won praise 3 · views 20000 +

Guess you like

Origin blog.csdn.net/chscomfaner/article/details/103729467