且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL-Server: 错误 - 无法获得独占访问,因为数据库正在使用中

更新时间:2021-08-24 22:16:02

我假设如果您正在恢复一个数据库,您不会关心该数据库上的任何现有事务.对?如果是这样,这应该适合您:

I'll assume that if you're restoring a db, you don't care about any existing transactions on that db. Right? If so, this should work for you:

USE master
GO

ALTER DATABASE AdventureWorksDW
SET SINGLE_USER
--This rolls back all uncommitted transactions in the db.
WITH ROLLBACK IMMEDIATE
GO

RESTORE DATABASE AdventureWorksDW
FROM ...
...
GO

现在,还有一项需要注意.将数据库设置为单用户模式后,其他人可能会尝试连接到数据库.如果它们成功,您将无法继续进行恢复.这是一场比赛!我的建议是同时运行所有三个语句.

Now, one additional item to be aware. After you set the db into single user mode, someone else may attempt to connect to the db. If they succeed, you won't be able to proceed with your restore. It's a race! My suggestion is to run all three statements at once.