无法将数据库从SINGLE_USER模式切换回MULTI_USER模式(Error 5064),及查找SQL Server数据库中用户spid(非SQL Server系统spid)的方法

时间:2021-12-13 22:50:47
无法将数据库从SINGLE_USER模式切换回MULTI_USER模式(Error 5064),及查找SQL Server数据库中用户spid(非SQL Server系统spid)的方法

今天公司SQL Server数据库无意间变为SINGLE_USER模式了,而且使用如下语句切换回MULTI_USER失败:

ALTER DATABASE [MyDB] SET MULTI_USER  WITH ROLLBACK IMMEDIATE 

报错:

Msg 5064, Level 16, State 1, Line 1
Changes to the state or options of database 'MyDB' cannot be made at this time. The database is in single-user mode, and a user is currently connected to it.
Msg 5069, Level 16, State 1, Line 1
ALTER DATABASE statement failed.

该错误提示是有其它用户在使用数据库,没办法只好排查是谁:

1)通过sys.sysprocesses或者sys.dm_exec_sessions,或者存储过程sp_who,然后用KILL命令把会话切断

select * from sys.sysprocesses
where spid > 50
And dbid=DB_ID ('MyDB')

这里解释下为什么上面有spid > 50这个where条件:
50以下都是SQL Server系统自带的进程。由于在windows之上SQL Server有一套自己的os,所以这些对于windows来说是线程的对于SQL Server os是进程。

需要注意的是spid > 50这个判断条件只对SQL Server 2005及之后的版本有效,如果是SQL Server 2000,那么SQL Server系统的spid也是可能会大于50的,所以查找数据库中用户spid的最好方法是通过sys.dm_exec_sessions的is_user_process列,is_user_process值为1的spid都是用户spid:

SELECT * FROM sys.dm_exec_sessions
WHERE is_user_process=1 AND database_id = DB_ID ('MyDB')

无法将数据库从SINGLE_USER模式切换回MULTI_USER模式(Error 5064),及查找SQL Server数据库中用户spid(非SQL Server系统spid)的方法

2)如果上面还是行不通,再检查sys.dm_tran_locks,然后用KILL命令把会话切断

select request_session_id as [spid],* from sys.dm_tran_locks where resource_database_id= DB_ID ('MyDB')

无法将数据库从SINGLE_USER模式切换回MULTI_USER模式(Error 5064),及查找SQL Server数据库中用户spid(非SQL Server系统spid)的方法

KILL 53