Get last command in SQL Server without DBCC INPUTBUFFER

我的梦境 提交于 2020-02-21 16:43:13

问题


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.


回答1:


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);



回答2:


Yes, from SQL Server 2014 SP4 and newer, you can use the following DMV:

IF OBJECT_ID('sys.dm_exec_input_buffer') IS NOT NULL --we are running SQL 2014 SP4 or newer!
BEGIN
    SELECT b.*
    FROM sys.dm_exec_input_buffer(@@SPID, NULL) b;
END
ELSE --we are running SQL 2014 SP3 or older...
BEGIN
    CREATE TABLE #TraceInfo (
        EventType NVARCHAR(255)
        ,parameters INTEGER
        ,event_info NVARCHAR(4000)
        );

    INSERT INTO #TraceInfo
    EXEC ('DBCC INPUTBUFFER(@@SPID) WITH NO_INFOMSGS');

    SELECT t.*
    FROM #TraceInfo t;
END


来源:https://stackoverflow.com/questions/19397828/get-last-command-in-sql-server-without-dbcc-inputbuffer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!