快速查询DB Lock的方法

时间:2022-04-01 18:21:59

DBCC Opentran

DBCC inputBuffer(id)

KILL (id)

 

sp_lock

 

--找出產生Lock的源頭

--Find locked process

select open_tran,* from sys.sysprocesses where blocked>0

--Find suspected process

select * from sys.sysprocesses where status='sleeping' and waittype=0x0000 and open_tran>0

--Find original process locking others

IF EXISTS(SELECT * FROM master.sys.sysprocesses WHERE spid

    IN (SELECT blocked FROM master.sys.sysprocesses)) --Make sure there is locked process

    SELECT spid ,status , LoginUser=SUBSTRING(SUSER_SNAME(sid),1,30),

       Hostname, IsBlocked=CONVERT(char(3),blocked),

       DBName= SUBSTRING(DB_NAME(dbid),1,20),program_name, last_batch,cmd,waittype

    FROM master.sys.sysprocesses

    --List process whose blocked=0 but found in other process's blocked column

    WHERE spid IN (SELECT blocked FROM master.sys.sysprocesses)

    AND blocked=0

ELSE

    SELECT 'No Locked Process'

 

 

 

--查詢Lock情形

declare  @temp table

(spid int,dbid int,ObjId int,IndId int,Type varchar(3),Resouse varchar(20),Mode varchar(5),Status varchar(5))

INSERT @temp EXEC sp_lock  --@@spid

--select * from @temp

--For SQL2000

SELECT spid,dbname=db_name(dbid),objname=object_name(ObjId),

idxname=(SELECT name FROM sysindexes WHERE id=ObjId AND indid=t.IndId),

Type,Resouse,Mode,Status FROM @Temp t WHERE dbid>=5 and TYPE in ('TAB', 'KEY', 'RID') and object_name(ObjId) is not  null

ORDER BY dbid,objid,indid

 

--For SQL Server 2005; use sys.indexes 

SELECT spid,dbname=db_name(dbid),objname=object_name(ObjId),

Idxname=(SELECT name FROM sys.indexes WHERE object_id=ObjId AND index_id=t.IndId),

Type,Resouse,Mode,Status FROM @temp t WHERE dbid>=5 and TYPE in ('TAB', 'KEY', 'RID') and object_name(ObjId) is not null

ORDER BY dbid,objid,indid