Friday, 27 May 2016

Get Last Running Query Based on SPID

Query 1-

To know which sessions are running currently, run the following command:
SELECT @@SPID
GO
get the latest run query in our input buffer
DBCC INPUTBUFFER(61)--61 is the output of above query
GO


Query 2- 

DECLARE @sqltext VARBINARY(128)
SELECT @sqltext = sql_handle
FROM sys.sysprocesses
WHERE spid = 61 -- get from
SELECT @@SPID 
SELECT TEXT
FROM
sys.dm_exec_sql_text(@sqltext)
GO
 
Please note that in any session there may be multiple running queries, but the buffer only saves the last query and that is what we will be able to retrieve.

No comments:

Post a Comment

Table Partitioning in SQL Server

  Table Partitioning in SQL Server – Step by Step Partitioning in SQL Server task is divided into four steps: Create a File Group Add Files ...