sql 开发篇一 之 表锁查询及解锁

  • Post author:
  • Post category:其他


1、查询表锁进程id

select   request_session_id   spid,OBJECT_NAME(resource_associated_entity_id) tableName   
from   sys.dm_tran_locks where resource_type='OBJECT'

2、根据进程id kill掉

spid为查询到进程编号

declare @spid int
Set @spid = 56
declare @sql varchar(1000)
set @sql='kill '+cast(@spid as varchar)
exec(@sql)

3、游标循环释放表锁

DECLARE @spid VARCHAR(50),
@talbename varchar(100)
DECLARE cursor_name CURSOR FOR --定义游标

SELECT   request_session_id   spid,OBJECT_NAME(resource_associated_entity_id) tableName   
from   sys.dm_tran_locks where resource_type='OBJECT'

OPEN cursor_name --打开游标
FETCH NEXT FROM cursor_name INTO  @spid,@talbename  --抓取下一行游标数据
WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT '表名:'+@talbename+'            '+'spid:'+@spid
		exec('kill '+@spid)
        FETCH NEXT FROM cursor_name INTO @spid,@talbename
    END
CLOSE cursor_name --关闭游标
DEALLOCATE cursor_name --释放游标





版权声明:本文为u013730110原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。