#统计某类sql执行次数,并按总体cpu消耗时间降序排序
with a as
(
select er.session_id,db_name(er.database_id) as DBNAME,sy.last_batch AS '最后执行时间',
er.cpu_time ,er.total_elapsed_time/1000 as sum_elapsed_time_s,
CAST(csql.text AS varchar(8000)) AS CallingSQL ,sy.cmd as cmd,sy.status as status,sy.lastwaittype,sy.loginame as loginame,sy.hostname as hostname,
client_net_address as client_ip,local_net_address '服务器的IP',er.reads,er.writes,er.row_count,
'kill '+cast(er.session_id as varchar(200)) AS 'KILL-SQL'
from master.sys.dm_exec_requests er WITH (NOLOCK)CROSS APPLY fn_get_sql (er.sql_handle) csql
left join sysprocesses sy on er.session_id =sy.spid
left join sys.dm_exec_connections dec on dec.session_id=sy.spid
where er.session_id >50
-- AND er.session_id ='56'
and loginame <>'' and CAST(csql.text AS varchar(8000)) like '%%'
)
select DBNAME,a.CallingSQL,count(*) cnt,sum(cpu_time) as sum_cpu_time,sum(sum_elapsed_time_s) as sum_elapsed_time_s,avg(cpu_time) as avg_cpu_time,avg(sum_elapsed_time_s) as avg_elapsed_time_s,
max(cmd) as cmd,max(status) as status,max(loginame) as loginname,max(hostname) as hostname,max(client_ip) as client_ip
from a
where a.CallingSQL not like '%select er.session_id,db_name(er.database_id) as DBNAME%'
group by a.CallingSQL,a.DBNAME
order by sum_cpu_time desc
输出结果示例: