TSQL:获取最后查询

时间:2010-08-26 20:10:20

标签: sql tsql history

有没有办法获取最后几个查询的SQL文本?

我正在使用Microsoft SQL Server 2005

4 个答案:

答案 0 :(得分:104)

是的,看看,这将为您提供最近执行的50条SQL语句

仅限sql 2005

SELECT TOP 50 * FROM(SELECT COALESCE(OBJECT_NAME(s2.objectid),'Ad-Hoc') AS ProcName,
  execution_count,s2.objectid,
    (SELECT TOP 1 SUBSTRING(s2.TEXT,statement_start_offset / 2+1 ,
      ( (CASE WHEN statement_end_offset = -1
  THEN (LEN(CONVERT(NVARCHAR(MAX),s2.TEXT)) * 2)
ELSE statement_end_offset END)- statement_start_offset) / 2+1)) AS sql_statement,
       last_execution_time
FROM sys.dm_exec_query_stats AS s1
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS s2 ) x
WHERE sql_statement NOT like 'SELECT TOP 50 * FROM(SELECT %'
--and OBJECTPROPERTYEX(x.objectid,'IsProcedure') = 1
ORDER BY last_execution_time DESC

答案 1 :(得分:26)

如果使用SQL Server 2005 +:

SELECT deqs.last_execution_time AS [Time], dest.TEXT AS [Query]
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY deqs.last_execution_time DESC

来自SQLAuthority的精彩提示!

答案 2 :(得分:1)

我唯一知道的方法是让SQL Server Profiler运行。不幸的是,这需要在执行查询之前启动,因此如果您希望捕获在“临时”基础上发生的事情,那么它将不合适。如果您正在尝试跟踪一段代码正在执行的操作并希望捕获它执行的查询,那么它应该是一种享受。

答案 3 :(得分:0)

如果您需要检查参数值,则此附加操作会返回<ParameterList> XML

SELECT TOP 50 * FROM(SELECT COALESCE(OBJECT_NAME(s2.objectid),'Ad-Hoc') AS ProcName,
  execution_count,s2.objectid,
    (SELECT TOP 1 SUBSTRING(s2.TEXT,statement_start_offset / 2+1 ,
      ( (CASE WHEN statement_end_offset = -1
  THEN (LEN(CONVERT(NVARCHAR(MAX),s2.TEXT)) * 2)
ELSE statement_end_offset END)- statement_start_offset) / 2+1)) AS sql_statement,
  SUBSTRING(
    s3.query_plan,CHARINDEX('<ParameterList>',s3.query_plan),
    CHARINDEX('</ParameterList>',s3.query_plan) + LEN('</ParameterList>') - CHARINDEX('<ParameterList>',s3.query_plan)
  ) AS Parameters,
  last_execution_time
FROM sys.dm_exec_query_stats AS s1
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS s2
CROSS APPLY sys.dm_exec_text_query_plan(s1.plan_handle, s1.statement_start_offset,
  s1.statement_end_offset) AS s3
) x
WHERE sql_statement NOT like 'SELECT TOP 50 * FROM(SELECT %'
ORDER BY last_execution_time DESC

Prettified version