SQL Server: Filter output of sp_who2

后端 未结 13 2081
长情又很酷
长情又很酷 2020-12-02 03:49

Under SQL Server, is there an easy way to filter the output of sp_who2? Say I wanted to just show rows for a certain database, for example.

13条回答
  •  春和景丽
    2020-12-02 04:37

    I am writing here for future use of my own. It uses sp_who2 and insert into table variable instead of temp table because Temp table cannot be used twice if you do not drop it. And shows blocked and blocker at the same line.

    --blocked: waiting becaused blocked by blocker
    --blocker: caused blocking
    declare @sp_who2 table(
        SPID int,
        Status varchar(max),
        Login varchar(max),
        HostName varchar(max),
        BlkBy varchar(max),
        DBName varchar(max),
        Command varchar(max),
        CPUTime int,
        DiskIO int,
        LastBatch varchar(max),
        ProgramName varchar(max),
        SPID_2 int,
        REQUESTID int
    )
    insert into @sp_who2 exec sp_who2
    select  w.SPID blocked_spid, w.BlkBy blocker_spid, tblocked.text blocked_text, tblocker.text blocker_text
    from    @sp_who2 w
            inner join sys.sysprocesses pblocked on w.SPID = pblocked.spid
            cross apply sys.dm_exec_sql_text(pblocked.sql_handle) tblocked
            inner join sys.sysprocesses pblocker on case when w.BlkBy = '  .' then 0 else cast(w.BlkBy as int) end = pblocker.spid
            cross apply sys.dm_exec_sql_text(pblocker.sql_handle) tblocker
    where   pblocked.Status = 'SUSPENDED'
    

提交回复
热议问题