Sql Server性能优化方法备忘录

  1. 30分钟内耗时最长20个Sql语句:
    SELECT TOP 20
    SUBSTRING(st.text, (qs.statement_start_offset/2) + 1,
    ((CASE statement_end_offset
    WHEN -1 THEN DATALENGTH(st.text)
    ELSE qs.statement_end_offset END
    - qs.statement_start_offset)/2) + 1) as SQL_Part --统计对应的部分语句

    , CAST( ((qs.total_elapsed_time / 1000000.0)/qs.execution_count) AS DECIMAL(28,2) ) AS [平均消耗秒数]
    , CAST(qs.last_elapsed_time / 1000000.0 AS DECIMAL(28, 2)) AS [最后完成消耗秒数]
    , qs.last_execution_time AS [最后执行时间]
    , CAST(qs.min_elapsed_time / 1000000.0 AS DECIMAL(28, 2)) AS [最小消耗秒数]
    , CAST(qs.max_elapsed_time / 1000000.0 AS DECIMAL(28, 2)) AS [最大消耗秒数]
    , CAST(qs.total_elapsed_time / 1000000.0 AS DECIMAL(28, 2)) AS [总消耗秒数]
    , (qs.execution_count) AS [总执行次数]
    , creation_time AS [编译计划的时间]
    , CAST(qs.last_worker_time / 1000000.0 AS DECIMAL(28, 2)) AS [最后完成占用CPU秒数]
    , qp.query_plan
    
    , st.text AS SQL_Full                                       --父级完整语句
    

    from sys.dm_exec_query_stats qs
    CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS st
    CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp

WHERE qs.last_execution_time>DATEADD(n,-30,GETDATE()) -- 30分钟内
ORDER BY qs.last_worker_time DESC

  1. 查看 当前所有Session 及最后sql

    SELECT A.session_id, b.host_name,
    Db_Name(s.dbid) AS [database],
    DateDiff(MINUTE, A.connect_time, GetDate()) AS [Connected (mins)],
    num_reads, num_writes, login_name, q.text

    FROM sys.dm_exec_connections AS A
    INNER JOIN sys.dm_exec_sessions AS B ON A.session_id = B.session_id
    INNER JOIN sys.sysprocesses AS s ON s.spid = A.session_id
    cross APPLY sys.dm_exec_sql_text(sql_handle) q

注:当前活动对象
会话 sys.dm_exec_Session:
进程 sys.sysprocesses : 跟session一样, 向后兼容用
连接 sys.dm_exec_connections: 底层tcp连接
请求 sys.dm_exec_requests


统计对象 sys.dm_exec_query_stats
sql语句 sys.dm_exec_sql_text(sql_handle)

上一篇:3GPP协议学习-TS 38.211-NR;物理信道与调制


下一篇:达梦数据库修改数据文件路径