Sql-Server

如何在 SQL Server 中使用的數據庫上將備份還原為覆蓋?

  • April 19, 2021

我想通過覆蓋正在使用的數據庫來****恢復備份以 解決此問題我想根據以下步驟創建查詢:

1-刪除所有連接

$$ MyDB $$ 2-創建一個備份

$$ MyDB $$ 3-將備份還原為覆蓋

$$ MyDB $$從指定路徑 非常感謝您的幫助

您可以通過這種方式終止所有連接:

USE [master];

DECLARE @kill varchar(8000) = '';  
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';'  
FROM sys.dm_exec_sessions
WHERE database_id  = db_id('MyDB')

EXEC(@kill);

然後你傳遞給單使用者 mkode:

ALTER DATABASE YourDB
SET SINGLE_USER WITH
ROLLBACK AFTER 60 --this will give your current connections 60 seconds to complete

然後我們創建一個備份:

BACKUP DATABASE AdventureWorks 
TO DISK = 'C:\AdventureWorks.BAK'
GO

然後我們替換數據庫:

--Do Actual Restore
Restore Database [MyDatabase] From Disk = 'D:\Path\to\Backup.bak'
With Replace,
Move 'Data file logical name' To 'New physical path and name.mdf',
Move 'Log file logical name' To 'New physical path and name.ldf'';

然後我們回到多使用者模式:

/*If there is no error in statement before database will be in multiuser
mode.  If error occurs please execute following command it will convert
database in multi user.*/
ALTER DATABASE YourDB SET MULTI_USER
GO

引用自:https://dba.stackexchange.com/questions/290011