USE MASTER
GO
ALTER DATABASE MyDB
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE
RECONFIGURE
GO
-- To enable xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 1
GO
-- Update currently configured values for advanced options.
RECONFIGURE
GO
EXEC xp_cmdshell 'NET USE Z: \\Server\path passoword /USER:DOMAIN-NAME\UserName'
RESTORE DATABASE MyDB
FILE = N'logicalName'
FROM DISK = N'Z:\backupfilename'
WITH REPLACE,
FILE = 1, NOUNLOAD, STATS = 10,
MOVE N'logicalName'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\MyDB.mdf',
MOVE N'logicalName_log'
TO N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\MyDB_log.ldf'
EXEC xp_cmdshell 'net use Z: /delete'
GO
ALTER DATABASE MyDB SET MULTI_USER
GO
-如果数据库将处于多用户模式,则语句中没有错误。 -如果发生错误,请执行以下命令,它将以多用户身份转换数据库。