Skip to content

Instantly share code, notes, and snippets.

@leppie
Created May 29, 2024 00:01
Show Gist options
  • Save leppie/c5014d8665db43621e53440cb3dac857 to your computer and use it in GitHub Desktop.
Save leppie/c5014d8665db43621e53440cb3dac857 to your computer and use it in GitHub Desktop.
sp_who3 - add some more info to sp_who2
CREATE OR ALTER procedure [dbo].[sp_who3]
as
begin
declare @who table(
SPID int,
Status varchar(20),
Login varchar(100),
Hostname varchar(50),
BlkBy varchar(20),
DBName varchar(50),
Command varchar(255),
CPUTime int,
DiskIO int,
LastBatch varchar(50),
ProgramName varchar(255),
FAKE int,
REQUESTID int);
insert into @who exec sp_who2
;with p as
(
select
p.session_id, p.request_id, p.sql_handle, p.plan_handle, count(1) as [OpCount], sum(p.row_count) as TotalRowCount,
Operators = STRING_AGG(CONCAT(p.node_id, ': ', p.physical_operator_name), ', ') WITHIN GROUP (ORDER BY p.node_id)
from sys.dm_exec_query_profiles p
group by p.session_id, p.request_id, p.sql_handle, p.plan_handle
)
select
w.SPID as session_id, w.REQUESTID as request_id,
w.Status, w.Login, w.Hostname, w.BlkBy, w.CPUTime, w.DiskIO, w.LastBatch, w.ProgramName,
p.[OpCount], p.Operators, p.TotalRowCount,
ST.text as "SQL", QP.query_plan as "Query plan",
p.sql_handle, p.plan_handle
from @who w
left join p p on w.SPID = p.session_id and w.REQUESTID = p.request_id
outer APPLY sys.dm_exec_sql_text(p.sql_handle) as ST
outer APPLY sys.dm_exec_query_plan(p.plan_handle) as QP
where w.Login <> 'sa'
order by LastBatch desc
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment