sp_who2
This procedure can be used to find information on current SQL server sessions. Since it is a procedure, it's often helpful to store the results into a temporary table or table variable so one can order, filter, and transform the results as needed.
The below can be used for a queryable version of sp_who2
:
-- Create a variable table to hold the results of sp_who2 for querying purposes
DECLARE @who2 TABLE (
SPID INT NULL,
Status VARCHAR(1000) NULL,
Login SYSNAME NULL,
HostName SYSNAME NULL,
BlkBy SYSNAME NULL,
DBName SYSNAME NULL,
Command VARCHAR(8000) NULL,
CPUTime INT NULL,
DiskIO INT NULL,
LastBatch VARCHAR(250) NULL,
ProgramName VARCHAR(250) NULL,
SPID2 INT NULL, -- a second SPID for some reason...?
REQUESTID INT NULL
)
INSERT INTO @who2
EXEC sp_who2
SELECT *
FROM @who2 w
WHERE 1=1
Examples:
-- Find specific user sessions:
SELECT *
FROM @who2 w
WHERE 1=1
and login = 'userName'
-- Find longest CPUTime queries:
SELECT top 5 *
FROM @who2 w
WHERE 1=1
order by CPUTime desc