如何找出你性能最差的SQL Server查询 SQL Server 2014里的性能提升 sql server查询优化 SQL SERVER 的用户数,连接,连接池 license

    1. --查看sqlserver数据库版本
    2. SELECT @@VERSION
    3. --查询某个数据库的连接数
    4. select count(*) from Master.dbo.SysProcesses where dbid=db_id()
    5. --前10名其他等待类型
    6. SELECT TOP 10 * from sys.dm_os_wait_stats
    7. ORDER BY wait_time_ms DESC
    8. SELECT * FROM sys.dm_os_wait_stats
    9. WHERE wait_type like 'PAGELATCH%'
    10. OR wait_type like 'LAZYWRITER_SLEEP%'
    11. --CPU的压力
    12. SELECT scheduler_id, current_tasks_count, runnable_tasks_count
    13. FROM sys.dm_os_schedulers
    14. WHERE scheduler_id < 255
    15. --表现最差的前10名使用查询
    16. SELECT TOP 10 ProcedureName = t.text,
    17. ExecutionCount = s.execution_count,
    18. AvgExecutionTime = isnull ( s.total_elapsed_time / s.execution_count, 0 ),
    19. AvgWorkerTime = s.total_worker_time / s.execution_count,
    20. TotalWorkerTime = s.total_worker_time,
    21. MaxLogicalReads = s.max_logical_reads,
    22. MaxPhysicalReads = s.max_physical_reads,
    23. MaxLogicalWrites = s.max_logical_writes,
    24. CreationDateTime = s.creation_time,
    25. CallsPerSecond = isnull ( s.execution_count / datediff ( second , s.creation_time, getdate ()), 0 )
    26. FROM sys.dm_exec_query_stats s
    27. CROSS APPLY sys.dm_exec_sql_text( s.sql_handle ) t
    28. ORDER BY s.max_physical_reads DESC
    29. SELECT SUM(signal_wait_time_ms) AS total_signal_wait_time_ms总信号等待时间 ,
    30. SUM(wait_time_ms - signal_wait_time_ms) AS resource_wait_time_ms资源的等待时间,
    31. SUM(signal_wait_time_ms) * 1.0 / SUM (wait_time_ms) * 100 AS [signal_wait_percent信号等待%],
    32. SUM(wait_time_ms - signal_wait_time_ms) * 1.0 / SUM (wait_time_ms) * 100 AS [resource_wait_percent资源等待%]
    33. FROM sys.dm_os_wait_stats
    34. --一个信号等待时间过多对资源的等待时间那么你的CPU是目前的一个瓶颈。
    35. --查看进程所执行的SQL语句
    36. if (select COUNT(*) from master.dbo.sysprocesses) > 500
    37. begin
    38. select text,CROSS APPLY master.sys.dm_exec_sql_text(a.sql_handle) from master.sys.sysprocesses a
    39. end
    40. select text,a.* from master.sys.sysprocesses a
    41. CROSS APPLY master.sys.dm_exec_sql_text(a.sql_handle)
    42. where a.spid = '51'
    43. dbcc inputbuffer(53)
    44. with tb
    45. as
    46. (
    47. select blocking_session_id,
    48. session_id,db_name(database_id) as dbname,text from master.sys.dm_exec_requests a
    49. CROSS APPLY master.sys.dm_exec_sql_text(a.sql_handle)
    50. ),
    51. tb1 as
    52. (
    53. select a.,login_time,program_name,client_interface_name,login_name,cpu_time,memory_usage8 as 'memory_usage(KB)',
    54. total_scheduled_time,reads,writes,logical_reads
    55. from tb a inner join master.sys.dm_exec_sessions b
    56. on a.session_id=b.session_id
    57. )
    58. select a.*,connect_time,client_tcp_port,client_net_address from tb1 a inner join master.sys.dm_exec_connections b on a.session_id=b.session_id
    59. --当前进程数
    60. select * from master.dbo.sysprocesses
    61. order by cpu desc
    62. --查看当前活动的进程数
    63. sp_who active
    64. --查询是否由于连接没有释放引起CPU过高
    65. select * from master.dbo.sysprocesses
    66. where spid> 50
    67. and waittype = 0x0000
    68. and waittime = 0
    69. and status = 'sleeping '
    70. and last_batch < dateadd(minute, -10, getdate())
    71. and login_time < dateadd(minute, -10, getdate())
    72. --强行释放空连接
    73. select 'kill ' + rtrim(spid) from master.dbo.sysprocesses
    74. where spid> 50
    75. and waittype = 0x0000
    76. and waittime = 0
    77. and status = 'sleeping '
    78. and last_batch < dateadd(minute, -60, getdate())
    79. and login_time < dateadd(minute, -60, getdate())
    80. --查看当前占用 cpu 资源最高的会话和其中执行的语句(及时CPU)
    81. select spid,cmd,cpu,physical_io,memusage,
    82. (select top 1 [text] from ::fn_get_sql(sql_handle)) sql_text
    83. from master..sysprocesses order by cpu desc,physical_io desc
    84. --查看缓存中重用次数少,占用内存大的查询语句(当前缓存中未释放的)--全局
    85. SELECT TOP 100 usecounts, objtype, p.size_in_bytes,[sql].[text]
    86. FROM sys.dm_exec_cached_plans p
    87. OUTER APPLY sys.dm_exec_sql_text (p.plan_handle) sql
    88. ORDER BY usecounts,p.size_in_bytes desc
    89. SELECT top 25 qt.text,qs.plan_generation_num,qs.execution_count,dbid,objectid
    90. FROM sys.dm_exec_query_stats qs
    91. CROSS APPLY sys.dm_exec_sql_text(sql_handle) as qt
    92. WHERE plan_generation_num >1
    93. ORDER BY qs.plan_generation_num
    94. SELECT top 50 qt.text AS SQL_text ,
    95. SUM(qs.total_worker_time) AS total_cpu_time,
    96. SUM(qs.execution_count) AS total_execution_count,
    97. SUM(qs.total_worker_time)/SUM(qs.execution_count) AS avg_cpu_time,
    98. COUNT(*) AS number_of_statements
    99. FROM sys.dm_exec_query_stats qs
    100. CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) as qt
    101. GROUP BY qt.text
    102. ORDER BY total_cpu_time DESC --统计总的CPU时间
    103. --ORDER BY avg_cpu_time DESC --统计平均单次查询CPU时间
    104. -- 计算可运行状态下的工作进程数量
    105. SELECT COUNT(*) as workers_waiting_for_cpu,s.scheduler_id
    106. FROM sys.dm_os_workers AS o
    107. INNER JOIN sys.dm_os_schedulers AS s
    108. ON o.scheduler_address=s.scheduler_address AND s.scheduler_id<255
    109. WHERE o.state='RUNNABLE'
    110. GROUP BY s.scheduler_id
    111. --表空间大小查询
    112. create table #tb(表名 sysname,记录数 int,保留空间 varchar(100),使用空间 varchar(100),索引使用空间 varchar(100),未用空间 varchar(100))
    113. insert into #tb exec sp_MSForEachTable 'EXEC sp_spaceused ''?'''
    114. select * from #tb
    115. go
    116. SELECT
    117. 表名,
    118. 记录数,
    119. cast(ltrim(rtrim(replace(保留空间,'KB',''))) as int)/1024 保留空间MB,
    120. cast(ltrim(rtrim(replace(使用空间,'KB',''))) as int)/1024 使用空间MB,
    121. cast(ltrim(rtrim(replace(使用空间,'KB',''))) as int)/1024/1024.00 使用空间GB,
    122. cast(ltrim(rtrim(replace(索引使用空间,'KB',''))) as int)/1024 索引使用空间MB,
    123. cast(ltrim(rtrim(replace(未用空间,'KB',''))) as int)/1024 未用空间MB
    124. FROM #tb
    125. WHERE cast(ltrim(rtrim(replace(使用空间,'KB',''))) as int)/1024 > 0
    126. --order by 记录数 desc
    127. ORDER BY 使用空间MB DESC
    128. DROP TABLE #tb
    129. --查询是否由于连接没有释放引起CPU过高
    130. select * from master.dbo.sysprocesses
    131. where spid> 50
    132. and waittype = 0x0000
    133. and waittime = 0
    134. and status = 'sleeping '
    135. and last_batch < dateadd(minute, -10, getdate())
    136. and login_time < dateadd(minute, -10, getdate())
    137. --强行释放空连接
    138. select 'kill ' + rtrim(spid) from master.dbo.sysprocesses
    139. where spid> 50
    140. and waittype = 0x0000
    141. and waittime = 0
    142. and status = 'sleeping '
    143. and last_batch < dateadd(minute, -60, getdate())
    144. and login_time < dateadd(minute, -60, getdate())
    145. ----查看当前占用 cpu 资源最高的会话和其中执行的语句(及时CPU)
    146. select spid,cmd,cpu,physical_io,memusage,
    147. (select top 1 [text] from ::fn_get_sql(sql_handle)) sql_text
    148. from master..sysprocesses
    149. order by cpu desc,physical_io desc
    150. ----查看缓存中重用次数少,占用内存大的查询语句(当前缓存中未释放的)--全局
    151. SELECT TOP 100 usecounts, objtype, p.size_in_bytes,[sql].[text]
    152. FROM sys.dm_exec_cached_plans p
    153. OUTER APPLY sys.dm_exec_sql_text (p.plan_handle) sql
    154. ORDER BY usecounts,p.size_in_bytes desc
    155. SELECT top 25 qt.text,qs.plan_generation_num,qs.execution_count,dbid,objectid
    156. FROM sys.dm_exec_query_stats qs
    157. CROSS APPLY sys.dm_exec_sql_text(sql_handle) as qt
    158. WHERE plan_generation_num >1
    159. ORDER BY qs.plan_generation_num
    160. SELECT top 50 qt.text AS SQL_text,
    161. SUM(qs.total_worker_time) AS total_cpu_time,
    162. SUM(qs.execution_count) AS total_execution_count,
    163. SUM(qs.total_worker_time)/SUM(qs.execution_count) AS avg_cpu_time,
    164. COUNT(*) AS number_of_statements
    165. FROM sys.dm_exec_query_stats qs
    166. CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) as qt
    167. GROUP BY qt.text
    168. ORDER BY total_cpu_time DESC --统计总的CPU时间
    169. --ORDER BY avg_cpu_time DESC --统计平均单次查询CPU时间
    170. -- 计算可运行状态下的工作进程数量
    171. SELECT COUNT(*) as workers_waiting_for_cpu,s.scheduler_id
    172. FROM sys.dm_os_workers AS o
    173. INNER JOIN sys.dm_os_schedulers AS s ON o.scheduler_address=s.scheduler_address AND s.scheduler_id<255
    174. WHERE o.state='RUNNABLE'
    175. GROUP BY s.scheduler_id
    176. SELECT creation_time N'语句编译时间'
    177. , last_execution_time N'上次执行时间'
    178. , total_physical_reads N'物理读取总次数'
    179. , total_logical_reads/execution_count N'每次逻辑读次数'
    180. , total_logical_reads N'逻辑读取总次数'
    181. , total_logical_writes N'逻辑写入总次数'
    182. , execution_count N'执行次数'
    183. , total_worker_time/1000 N'所用的CPU总时间ms'
    184. , total_elapsed_time/1000 N'总花费时间ms'
    185. , (total_elapsed_time / execution_count)/1000 N'平均时间ms'
    186. , 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) N'执行语句'
    187. FROM sys.dm_exec_query_stats AS qs
    188. CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) st
    189. WHERE 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) not like '%fetch%'
    190. ORDER BY total_elapsed_time / execution_count DESC
    1. --查看当前连接的在线用户数
    2. select loginame,count(0) from sysprocesses
    3. group by loginame
    4. order by count(0) desc
    5. select nt_username,count(0) from sysprocesses
    6. group by nt_username
    7. order by count(0) desc
    8. --如果某个SQL Server用户名sa连接比较多,查看它来自的主机名:
    9. select hostname,count(0) from sysprocesses where loginame='sa'
    10. group by hostname
    11. order by count(0) desc
    12. --如果某个SQL Server用户名sa连接比较多,查看它最后一次操作的时间范围分组
    13. select convert(varchar,last_batch,111),count(0) from sysprocesses where loginame='sa'
    14. group by convert(varchar,last_batch,111)
    15. order by count(0) desc
    16. --如果从主机(DESKTOP-L8B71S9)来的连接比较多,可以查看它的进程详细情况
    17. select * from sysprocesses where hostname='DESKTOP-L8B71S9'
    18. --如果www机器主要提供网页服务,可能是asp程序处理连接时出了问题, 生成杀这些进程的SQL语句:
    19. select 'kill '+convert(varchar,spid) from sysprocesses where hostname='DESKTOP-L8B71S9'
    1. SELECT DB_ID(DB.dbid) '数据库名'
    2. , OBJECT_ID(db.objectid) '对象'
    3. , QS.creation_time '编译计划的时间'
    4. , QS.last_execution_time '上次执行计划的时间'
    5. , QS.execution_count '执行的次数'
    6. , QS.total_elapsed_time / 1000 '占用的总时间(秒)'
    7. , QS.total_physical_reads '物理读取总次数'
    8. , QS.total_worker_time / 1000 'CPU 时间总量(秒)'
    9. , QS.total_logical_writes '逻辑写入总次数'
    10. , QS.total_logical_reads N'逻辑读取总次数'
    11. , QS.total_elapsed_time / 1000 N'总花费时间(秒)'
    12. , SUBSTRING(ST.text, ( QS.statement_start_offset / 2 ) + 1,
    13. ( ( CASE statement_end_offset
    14. WHEN -1 THEN DATALENGTH(st.text)
    15. ELSE QS.statement_end_offset
    16. END - QS.statement_start_offset ) / 2 ) + 1) AS '执行语句'
    17. FROM sys.dm_exec_query_stats AS QS CROSS APPLY
    18. sys.dm_exec_sql_text(QS.sql_handle) AS ST INNER JOIN
    19. ( SELECT *
    20. FROM sys.dm_exec_cached_plans cp CROSS APPLY
    21. sys.dm_exec_query_plan(cp.plan_handle)
    22. ) DB
    23. ON QS.plan_handle = DB.plan_handle
    24. where SUBSTRING(st.text, ( qs.statement_start_offset / 2 ) + 1,
    25. ( ( CASE statement_end_offset
    26. WHEN -1 THEN DATALENGTH(st.text)
    27. ELSE qs.statement_end_offset
    28. END - qs.statement_start_offset ) / 2 ) + 1) not like '%fetch%'
    29. ORDER BY QS.total_elapsed_time / 1000 DESC
    1. SELECT spid,
    2. blocked,
    3. DB_NAME(sp.dbid) AS DBName,
    4. program_name as [应用程序名],
    5. waitresource,
    6. lastwaittype,
    7. sp.loginame as [登录名],
    8. sp.hostname as [客户端名称],
    9. a.[Text] AS [命令文本] --,
    10. --SUBSTRING(A.text, sp.stmt_start , 2)
    11. FROM sys.sysprocesses AS sp OUTER APPLY sys.dm_exec_sql_text (sp.sql_handle) AS A where a.text is not null
    12. SELECT spid,
    13. blocked,
    14. DB_NAME(sp.dbid) AS DBName,
    15. program_name,
    16. waitresource,
    17. lastwaittype,
    18. sp.loginame,
    19. sp.hostname,
    20. a.[Text] AS [TextData],
    21. SUBSTRING(A.text, sp.stmt_start / 2,
    22. (CASE WHEN sp.stmt_end = -1 THEN DATALENGTH(A.text) ELSE sp.stmt_end
    23. END - sp.stmt_start) / 2) AS [current_cmd]
    24. FROM sys.sysprocesses AS sp OUTER APPLY sys.dm_exec_sql_text (sp.sql_handle) AS A
    25. WHERE spid > 50
    26. ORDER BY blocked DESC, DB_NAME(sp.dbid) ASC, a.[text];
    1. --看一下各项指标是否正常,是否有阻塞,正常情况下搜索结果应该为空
    2. --会话中有多少个worker在等待
    3. SELECT TOP 10
    4. [session_id],
    5. [request_id],
    6. [start_time] AS '开始时间',
    7. [status] AS '状态',
    8. [command] AS '命令',
    9. dest.[text] AS 'sql语句',
    10. DB_NAME([database_id]) AS '数据库名',
    11. [blocking_session_id] AS '正在阻塞其他会话的会话ID',
    12. der.[wait_type] AS '等待资源类型',
    13. [wait_time] AS '等待时间',
    14. [wait_resource] AS '等待的资源',
    15. [dows].[waiting_tasks_count] AS '当前正在进行等待的任务数',
    16. [reads] AS '物理读次数',
    17. [writes] AS '写次数',
    18. [logical_reads] AS '逻辑读次数',
    19. [row_count] AS '返回结果行数'
    20. FROM sys.[dm_exec_requests] AS der
    21. INNER JOIN [sys].[dm_os_wait_stats] AS dows
    22. ON der.[wait_type]=[dows].[wait_type]
    23. CROSS APPLY
    24. sys.[dm_exec_sql_text](der.[sql_handle]) AS dest
    25. WHERE [session_id]>50
    26. ORDER BY [cpu_time] DESC
    1. --检查锁表情况语句
    2. --查询被锁表
    3. select request_session_id spid,OBJECT_NAME(resource_associated_entity_id) tableName
    4. from sys.dm_tran_locks where resource_type='OBJECT'