SQL未能排它地锁定数据库以执行该操作解决

SQL未能排它地锁定数据库以执行该操作解决:

--原因其他用户或进程在用着数据库

/*  
关闭用户打开的进程处理  
*/  
use   master  

if   exists   (select   *   from   dbo.sysobjects   where   id   =   object_id(N'[dbo].[p_killspid]')   and   OBJECTPROPERTY(id,   N'IsProcedure')   =   1)  
drop   procedure   [dbo].[p_killspid]    
   
create   proc   p_killspid  
@dbname   varchar(200) --要关闭进程的数据库名  
as      
declare   @sql     nvarchar(500)      
declare   @spid   nvarchar(20)  

declare   #tb   cursor   for  
select   spid=cast(spid   as   varchar(20))   from   master..sysprocesses   where   dbid=db_id(@dbname)  
open   #tb  
fetch   next   from   #tb   into   @spid  
while   @@fetch_status=0  
begin      
exec('kill   '+@spid)  
fetch   next   from   #tb   into   @spid  
end      
close   #tb  
deallocate   #tb  

--关闭对数据库newhis   的连接  
exec   p_killspid     'hjdb'  

--更改排序规则  
alter   database   hjdb   COLLATE   Chinese_PRC_BIN    

--结束后删除存储过程  
if   exists   (select   *   from   dbo.sysobjects   where   id   =   object_id(N'[dbo].[p_killspid]')   and   OBJECTPROPERTY(id,   N'IsProcedure')   =   1)  
drop   procedure   [dbo].[p_killspid]  

原文地址:https://www.cnblogs.com/zjoch/p/1793738.html