无法将数据库从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')

 

 

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

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

 

 

KILL 53

 

转载于:https://www.cnblogs.com/OpenCoder/p/10037560.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值