Get last command in SQL Server without DBCC INPUTBUFFER

Neil Weicher picture Neil Weicher · Oct 16, 2013 · Viewed 8.6k times · Source

Is there a way to get the last executed SQL Server command without the use of DBCC INPUTBUFFER?

For example, is there a System View or Catalog that contains this information?

Thanks.

Answer

M.Ali picture M.Ali · Oct 16, 2013

You can pass your SPID (SQL Process ID) to the following:

DECLARE @sql_handle VARBINARY(128);

SELECT @sql_handle = sql_handle
FROM sys.sysprocesses
WHERE spid = @@SPID; --you can pass a different SPID here

SELECT [text]
FROM sys.dm_exec_sql_text(@sql_handle);