处理sql server的死锁 [kill spid]

  1. 死锁会照成管理--活动监视器打不开
  2. select * from sysprocesses where  blocked>0 
  3. 可以查出来锁的线程,blocked那一列就是需要kill掉的。
  4. exec('kill blocked列')

  5. use master  
  6. go  
  7. create procedure sp_who_lock  
  8. as  
  9. begin  
  10. declare @spid int,@bl int,  
  11.         @intTransactionCountOnEntry  int,  
  12.         @intRowcount    int,  
  13.         @intCountProperties   int,  
  14.         @intCounter    int  
  15.   
  16.  create table #tmp_lock_who (  
  17.  id int identity(1,1),  
  18.  spid smallint,  
  19.  bl smallint)  
  20.    
  21.  IF @@ERROR<>0 RETURN @@ERROR  
  22.    
  23.  insert into #tmp_lock_who(spid,bl) select  0 ,blocked  
  24.    from (select * from sysprocesses where  blocked>0 ) a   
  25.    where not exists(select * from (select * from sysprocesses where  blocked>0 ) b   
  26.    where a.blocked=spid)  
  27.    union select spid,blocked from sysprocesses where  blocked>0  
  28.   
  29.  IF @@ERROR<>0 RETURN @@ERROR   
  30.     
  31. -- 找到临时表的记录数  
  32.  select  @intCountProperties = Count(*),@intCounter = 1  
  33.  from #tmp_lock_who  
  34.    
  35.  IF @@ERROR<>0 RETURN @@ERROR   
  36.    
  37.  if @intCountProperties=0  
  38.   select '现在没有阻塞和死锁信息' as message  
  39.   
  40. -- 循环开始   
  41. while @intCounter <= @intCountProperties  
  42. begin  
  43. -- 取第一条记录  
  44.   select  @spid = spid,@bl = bl  
  45.   from #tmp_lock_who where Id = @intCounter   
  46.  begin  
  47.   if @spid =0   
  48.       select '引起数据库死锁的是: 'CAST(@bl AS VARCHAR(10)) + '进程号,其执行的SQL语法如下'  
  49.   else  
  50.       select '进程号SPID:'CAST(@spid AS VARCHAR(10))+ '被' + '进程号SPID:'CAST(@bl AS VARCHAR(10)) +'阻塞,其当前进程执行的SQL语法如下'  
  51.  DBCC INPUTBUFFER (@bl )  
  52.  end  
  53.   
  54. -- 循环指针下移   
  55.  set @intCounter = @intCounter + 1  
  56. end  
  57.   
  58. drop table #tmp_lock_who  
  59.   
  60. return 0  

  1. end  
    1. use master  
    2. go  
    3.   
    4. if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_killspid]'and OBJECTPROPERTY(id, N'IsProcedure') = 1)  
    5. drop procedure [dbo].[p_killspid]  
    6. GO  
    7.   
    8. create proc p_killspid  
    9. @dbname varchar(200)    --要关闭进程的数据库名  
    10. as    
    11.     declare @sql  nvarchar(500)    
    12.     declare @spid nvarchar(20)  
    13.   
    14.     declare #tb cursor for  
    15.         select spid=cast(spid as varchar(20)) from master..sysprocesses where dbid=db_id(@dbname)  
    16.     open #tb  
    17.     fetch next from #tb into @spid  
    18.     while @@fetch_status=0  
    19.     begin    
    20.         exec('kill '+@spid)  
    21.         fetch next from #tb into @spid  
    22.     end    
    23.     close #tb  
    24.     deallocate #tb  
    25. go 
    26. exec master..sp_who_lock
    27. exec master..sp_who_lock 
      1. exec master..p_killspid 'dbname'  


猜你喜欢

转载自blog.csdn.net/heizistudio/article/details/77638949