检索历史查询

时间:2014-08-05 13:38:47

标签: sql-server sql-server-2012

我使用以下查询来检索在服务器上运行的当前查询:

select *
from (
    select
    t1.session_id,
    t1.request_id,
    t3.hostname,
    t3.loginame,
    t3.login_time,
    cast(t3.waittime as bigint) / 60000  as wait_time,
    cast(t2.cpu_time as bigint) / 60000  as cpu_time,
    cast(t2.total_elapsed_time as bigint) / 60000 as total_elapsed_time,
    --t3.program_name,
    db_name (t3.dbid) as dbname,
    t1.task_alloc  * (8.0/1024.0) as Alocado_MB, --qtd de paginas
    t1.task_dealloc  * (8.0/1024.0)as Desalocado_MB, --qtd de paginas

        (SELECT SUBSTRING(text, t2.statement_start_offset/2 + 1,
              (CASE WHEN statement_end_offset = -1
                  THEN LEN(CONVERT(nvarchar(max),text)) * 2
                       ELSE statement_end_offset
                  END - t2.statement_start_offset)/2)
         FROM sys.dm_exec_sql_text(t2.sql_handle)) AS query_text,
    (SELECT query_plan from sys.dm_exec_query_plan(t2.plan_handle)) as query_plan
    from      (Select session_id, request_id,
    sum(internal_objects_alloc_page_count +   user_objects_alloc_page_count) as task_alloc,
    sum (internal_objects_dealloc_page_count + user_objects_dealloc_page_count) as task_dealloc
           from sys.dm_db_task_space_usage
           group by session_id, request_id) as t1,
           sys.dm_exec_requests as t2,
           sys.sysprocesses as t3
    where
        t3.loginame <> '' and
        t1.session_id = t2.session_id and
        (t1.request_id = t2.request_id) and
        t1.session_id = t3.spid and
        t1.session_id > 50
) A
order by loginame, total_elapsed_time DESC

有没有办法检索历史文件?

2 个答案:

答案 0 :(得分:2)

你可以试试这个:

SELECT  a.plan_handle ,
        a.sql_handle ,
        e.text    
FROM    sys.dm_exec_query_stats a
        CROSS APPLY sys.dm_exec_sql_text(a.plan_handle) AS e
WHERE text like '%somevalue%'  --If you want to filter some values

答案 1 :(得分:1)

一般来说,没有。一旦提交,编译和处理了查询,就是这样 - SQL本身不会记录提交的查询或运行的时间。

存储编译的计划 ,以防止提交相同的查询,从而避免并发症的成本。它们存储在过程高速缓存中,并根据使用和系统负载随着时间的推移而“老化”。您可以使用它们来查看现在的内容,但您永远不能假设这样可以全面了解您的系统在任何时间点运行的内容。 (此处的关键系统对象为sys.dm_exec_query_statssys.dm_exec_sql_text。)

SQL Profiler(或者更确切地说,SQL Traces)可以配置为跟踪实例运行的所有内容,但这会导致可能无法接受的性能损失。

免责声明:这适用于SQL 2008. SQL 2012+可能具有此类功能,但我对此表示怀疑。