针对SQL Server的SQL查询的执行日期时间

时间:2017-03-22 16:30:50

标签: sql sql-server

我有一个很好的查询,我曾经找到here

我想将查询的执行时间添加到以下查询中:

USE master
go

SELECT 
    sdest.DatabaseName, sdes.session_id,
    sdes.[host_name], sdes.[program_name],
    sdes.client_interface_name, 
    sdes.login_name, sdes.login_time,
    sdes.nt_domain, sdes.nt_user_name,
    sdec.client_net_address, sdec.local_net_address,
    sdest.ObjName, sdest.Query
FROM 
    sys.dm_exec_sessions AS sdes
INNER JOIN 
    sys.dm_exec_connections AS sdec ON sdec.session_id = sdes.session_id
CROSS APPLY 
    (SELECT 
         db_name(dbid) AS DatabaseName,
         object_id(objectid) AS ObjName,
         ISNULL((SELECT TEXT AS [processing-instruction(definition)]
                 FROM sys.dm_exec_sql_text(sdec.most_recent_sql_handle)
                 FOR XML PATH(''), TYPE), '') AS Query
     FROM 
         sys.dm_exec_sql_text(sdec.most_recent_sql_handle)
    ) sdest
WHERE
    sdes.session_id <> @@SPID 
    -- AND sdes.nt_user_name = '' -- Put the username here !
ORDER BY 
    sdec.session_id

有没有我可能不知道的专栏,我需要包含这些专栏来获得这个专栏?或者也许我需要加入另一张桌子?

1 个答案:

答案 0 :(得分:1)

你可以在sql_handle中找到很多关于查询执行的信息 sys.dm_exec_query_stats,包括: last_elapsed_time, max_elapsed_time, total_elapsed_time

我已经向sys.dm_exec_query_stats添加了一个左连接,并从中选择了所有字段。

USE master
go
SELECT sdest.DatabaseName 
    ,sdes.session_id
    ,sdes.[host_name]
    ,sdes.[program_name]
    ,sdes.client_interface_name
    ,sdes.login_name
    ,sdes.login_time
    ,sdes.nt_domain
    ,sdes.nt_user_name
    ,sdec.client_net_address
    ,sdec.local_net_address
    ,sdest.ObjName
    ,sdest.Query
    ,qst.*
FROM sys.dm_exec_sessions AS sdes
INNER JOIN sys.dm_exec_connections AS sdec ON sdec.session_id = sdes.session_id
CROSS APPLY (
    SELECT db_name(dbid) AS DatabaseName
        ,object_id(objectid) AS ObjName
        ,ISNULL((
                SELECT TEXT AS [processing-instruction(definition)]
                FROM sys.dm_exec_sql_text(sdec.most_recent_sql_handle)
                FOR XML PATH('')
                    ,TYPE
                ), '') AS Query

    FROM sys.dm_exec_sql_text(sdec.most_recent_sql_handle)
    ) sdest

LEFT OUTER JOIN sys.dm_exec_query_stats qst ON qst.sql_handle = sdec.most_recent_sql_handle
WHERE sdes.session_id <> @@SPID 
--and sdes.nt_user_name = '' -- Put the username here !
ORDER BY sdec.session_id