Technical Article

Simple script to list out SPID, Program_name and login details

,

To Execute the procedure, first find out any database against which you want to extract the SPIDs.

To find the dbid, use the below script:

select spid,dbid,status from sys.sysprocesses
where spid> 50
Let's say, you want to find out all the sessions running against the dbid = 60 and you want to see few other additional details, for e.g, SPID, app_program_name, loginame.
exec find_session @dbid = 60

You get a quick answer.

The best part of the script is, it's not using CURSOR and also very handy way to get only the required details as extracting each time the SPID and then feeding into the DBCC INPUTBUFFER(SPID) is a time consuming and boring approach.

Hope this helps everyone.

use Tempdb
go
alter procedure find_session (@dbid int)
as
declare @spid int
declare @sql nvarchar(max)
declare @spidcnt int
declare @i int=0

CREATE TABLE #get_SPID
(
      id int identity(1,1),
      SPID INT,
      app_program_name varchar(300),
      loginame varchar(200),
      inputbuf varchar(4000) null
)

INSERT INTO #get_SPID (SPID, app_program_name, loginame)
select spid,[program_name],loginame from sys.sysprocesses where dbid = @dbid

SELECT @spidcnt = count(*) FROM #get_SPID

WHILE (@i < @spidcnt)
BEGIN
DECLARE @output_tbl TABLE (EventType varchar(200), Params int, EventInfo varchar(4000))
select @spid = spid from #get_SPID where id = @i
    PRINT 'DBCC Results for SPID ' + Cast(@spid as varchar(5)) 
    PRINT '-----------------------------------'
    PRINT ''
SET @sql = 'DBCC INPUTBUFFER(' + CAST(@spid AS NVARCHAR) + ')'
INSERT INTO @output_tbl EXEC (@sql)
UPDATE #get_SPID set inputbuf = (SELECT EventInfo FROM @output_tbl) WHERE id = @i
DELETE FROM @output_tbl
SET @i+=1
END

SELECT * FROM #get_SPID
go

Rate

3 (4)

You rated this post out of 5. Change rating

Share

Share

Rate

3 (4)

You rated this post out of 5. Change rating