paraffin

GLENN

Feb 25th, 2016
401
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 61.94 KB | None | 0 0
  1.  
  2. -- SQL Server 2012 Diagnostic Information Queries
  3. -- Glenn Berry
  4. -- September 2014
  5. -- Last Modified: September 22, 2014
  6. -- http://sqlserverperformance.wordpress.com/
  7. -- http://sqlskills.com/blogs/glenn/
  8. -- Twitter: GlennAlanBerry
  9.  
  10. -- Listen to my Pluralsight courses
  11. -- http://pluralsight.com/training/Authors/Details/glenn-berry
  12.  
  13. -- Many of these queries will not work if you have databases in 80 compatibility mode
  14.  
  15. --******************************************************************************
  16. --* Copyright (C) 2014 Glenn Berry, SQLskills.com
  17. --* All rights reserved.
  18. --*
  19. --* For more scripts and sample code, check out
  20. --* http://sqlskills.com/blogs/glenn
  21. --*
  22. --* You may alter this code for your own *non-commercial* purposes. You may
  23. --* republish altered code as long as you include this copyright and give due credit.
  24. --*
  25. --*
  26. --* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF
  27. --* ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
  28. --* TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
  29. --* PARTICULAR PURPOSE.
  30. --*
  31. --******************************************************************************
  32.  
  33. -- Check the major product version to see if it is SQL Server 2012
  34. IF NOT EXISTS (SELECT * WHERE CONVERT(varchar(128), SERVERPROPERTY('ProductVersion')) LIKE '11%')
  35. BEGIN
  36. DECLARE @ProductVersion varchar(128) = CONVERT(varchar(128), SERVERPROPERTY('ProductVersion'));
  37. RAISERROR ('Script does not match the ProductVersion [%s] of this instance. Many of these queries may not work on this version.' , 18 , 16 , @ProductVersion);
  38. END
  39. ELSE
  40. PRINT N'You have the correct major version of SQL Server for this diagnostic information script';
  41.  
  42. -- Instance level queries *******************************
  43.  
  44. -- SQL and OS Version information for current instance (Query 1) (Version Info)
  45. SELECT @@SERVERNAME AS [Server Name], @@VERSION AS [SQL Server and OS Version Info];
  46.  
  47. -- SQL Server 2012 RTM Branch Builds SQL Server 2012 SP1 Branch Builds SQL Server 2012 SP2 Branch Builds
  48. -- Build Description Release Date Build Description Release Date Build Description Release Date
  49. -- 11.0.2100 RTM 3/6/2012
  50. -- 11.0.2316 RTM CU1 4/12/2012
  51. -- 11.0.2325 RTM CU2 6/18/2012 --> 11.0.3000 SP1 RTM 11/7/2012
  52. -- 11.0.2332 RTM CU3 8/31/2012
  53. -- 11.0.2376 RTM CU3 + QFE 10/9/2012
  54. -- 11.0.2383 RTM CU4 10/15/2012 --> 11.0.3321 SP1 CU1 11/20/2012
  55. -- 11.0.2395 RTM CU5 12/17/2012 --> 11.0.3339 SP1 CU2 1/21/2013
  56. -- 11.0.2401 RTM CU6 2/18/2013 --> 11.0.3349 SP1 CU3 3/18/2013
  57. -- 11.0.2405 RTM CU7 4/15/2013 --> 11.0 3368 SP1 CU4 5/30/2013
  58. -- 11.0.2410 RTM CU8 6/17/2013 --> 11.0.3373 SP1 CU5 7/15/2013
  59. -- 11.0.2419 RTM CU9 8/20/2013 --> 11.0.3381 SP1 CU6 9/16/2013
  60. -- 11.0.2420 RTM CU10 10/21/2013 --> 11.0.3393 SP1 CU7 11/18/2013
  61. -- 11.0.2424 RTM CU11 12/16/2003 --> 11.0.3401 SP1 CU8 1/20/2014
  62. -- 11.0.3412 SP1 CU9 3/17/2014 --> 11.0.5058 SP2 RTM 6/10/2014
  63. -- 11.0.3431 SP1 CU10 5/19/2014
  64. -- 11.0.3449 SP1 CU11 7/21/2014 --> 11.0.5532 SP2 CU1 7/23/2014
  65. -- 11.0.3470 SP1 CU12 9/15/2014 --> 11.0.5548 SP2 CU2 9/15/2014
  66.  
  67. -- The SQL Server 2012 builds that were released after SQL Server 2012 was released
  68. -- http://support.microsoft.com/kb/2692828
  69.  
  70. -- The SQL Server 2012 builds that were released after SQL Server 2012 Service Pack 1 was released
  71. -- http://support.microsoft.com/kb/2772858
  72.  
  73. -- SQL Server 2012 SP2 build versions (new format for the build list KB article)
  74. -- http://support.microsoft.com/kb/2983249
  75.  
  76.  
  77. -- When was SQL Server installed (Query 2) (SQL Server Install Date)
  78. SELECT @@SERVERNAME AS [Server Name], create_date AS [SQL Server Install Date]
  79. FROM sys.server_principals WITH (NOLOCK)
  80. WHERE name = N'NT AUTHORITY\SYSTEM'
  81. OR name = N'NT AUTHORITY\NETWORK SERVICE' OPTION (RECOMPILE);
  82.  
  83. -- Tells you the date and time that SQL Server was installed
  84. -- It is a good idea to know how old your instance is
  85.  
  86.  
  87. -- Get selected server properties (SQL Server 2012) (Query 3) (Server Properties)
  88. SELECT SERVERPROPERTY('MachineName') AS [MachineName], SERVERPROPERTY('ServerName') AS [ServerName],
  89. SERVERPROPERTY('InstanceName') AS [Instance], SERVERPROPERTY('IsClustered') AS [IsClustered],
  90. SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS [ComputerNamePhysicalNetBIOS],
  91. SERVERPROPERTY('Edition') AS [Edition], SERVERPROPERTY('ProductLevel') AS [ProductLevel],
  92. SERVERPROPERTY('ProductVersion') AS [ProductVersion], SERVERPROPERTY('ProcessID') AS [ProcessID],
  93. SERVERPROPERTY('Collation') AS [Collation], SERVERPROPERTY('IsFullTextInstalled') AS [IsFullTextInstalled],
  94. SERVERPROPERTY('IsIntegratedSecurityOnly') AS [IsIntegratedSecurityOnly],
  95. SERVERPROPERTY('IsHadrEnabled') AS [IsHadrEnabled], SERVERPROPERTY('HadrManagerStatus') AS [HadrManagerStatus];
  96.  
  97. -- This gives you a lot of useful information about your instance of SQL Server,
  98. -- such as the ProcessID for SQL Server and your collation
  99. -- The last two columns are new for SQL Server 2012
  100.  
  101.  
  102. -- Get SQL Server Agent jobs and Category information (Query 4) (SQL Server Agent Jobs)
  103. SELECT sj.name AS [JobName], sj.[description] AS [JobDescription], SUSER_SNAME(sj.owner_sid) AS [JobOwner],
  104. sj.date_created, sj.[enabled], sj.notify_email_operator_id, sc.name AS [CategoryName]
  105. FROM msdb.dbo.sysjobs AS sj WITH (NOLOCK)
  106. INNER JOIN msdb.dbo.syscategories AS sc WITH (NOLOCK)
  107. ON sj.category_id = sc.category_id
  108. ORDER BY sj.name OPTION (RECOMPILE);
  109.  
  110. -- Gives you some basic information about your SQL Server Agent jobs, who owns them and how they are configured
  111. -- Look for Agent jobs that are not owned by sa
  112. -- Look for jobs that don't have a notify_email_operator_id
  113.  
  114.  
  115. -- Get SQL Server Agent Alert Information (Query 5) (SQL Server Agent Alerts)
  116. SELECT name, event_source, message_id, severity, [enabled], has_notification,
  117. delay_between_responses, occurrence_count, last_occurrence_date, last_occurrence_time
  118. FROM msdb.dbo.sysalerts WITH (NOLOCK)
  119. ORDER BY name OPTION (RECOMPILE);
  120.  
  121. -- Gives you some basic information about your SQL Server Agent Alerts (which are different from SQL Server Agent jobs)
  122. -- Read more about Agent Alerts here: http://www.sqlskills.com/blogs/glenn/creating-sql-server-agent-alerts-for-critical-errors/
  123.  
  124.  
  125. -- Returns a list of all global trace flags that are enabled (Query 6) (Global Trace Flags)
  126. DBCC TRACESTATUS (-1);
  127.  
  128. -- If no global trace flags are enabled, no results will be returned.
  129. -- It is very useful to know what global trace flags are currently enabled as part of the diagnostic process.
  130.  
  131. -- Common trace flags that should be enabled in most cases
  132. -- TF 3226 - Supresses logging of successful database backup messages to the SQL Server Error Log
  133. -- TF 1118 - Helps alleviate allocation contention in tempdb (more important with older versions of SQL Server)
  134.  
  135.  
  136. -- Windows information (SQL Server 2012) (Query 7) (Windows Info)
  137. SELECT windows_release, windows_service_pack_level,
  138. windows_sku, os_language_version
  139. FROM sys.dm_os_windows_info WITH (NOLOCK) OPTION (RECOMPILE);
  140.  
  141. -- Gives you major OS version, Service Pack, Edition, and language info for the operating system
  142. -- 6.3 is either Windows 8.1 or Windows Server 2012 R2
  143. -- 6.2 is either Windows 8 or Windows Server 2012
  144. -- 6.1 is either Windows 7 or Windows Server 2008 R2
  145. -- 6.0 is either Windows Vista or Windows Server 2008
  146.  
  147. -- Windows SKU codes
  148. -- 4 is Enterprise Edition
  149. -- 7 is Standard Edition
  150. -- 48 is Professional Edition
  151.  
  152. -- 1033 for os_language_version is US-English
  153.  
  154. -- SQL Server 2012 requires Windows Server 2008 SP2 or newer
  155.  
  156. -- Hardware and Software Requirements for Installing SQL Server 2012
  157. -- http://msdn.microsoft.com/en-us/library/ms143506.aspx
  158.  
  159. -- Using SQL Server in Windows 8, Windows 8.1, Windows Server 2012 and Windows Server 2012 R2 environments
  160. -- http://support.microsoft.com/kb/2681562
  161.  
  162.  
  163. -- SQL Server Services information (SQL Server 2012) (Query 8) (SQL Server Services Info)
  164. SELECT servicename, process_id, startup_type_desc, status_desc,
  165. last_startup_time, service_account, is_clustered, cluster_nodename, [filename]
  166. FROM sys.dm_server_services WITH (NOLOCK) OPTION (RECOMPILE);
  167.  
  168. -- Tells you the account being used for the SQL Server Service and the SQL Agent Service
  169. -- Shows the processid, when they were last started, and their current status
  170. -- Shows whether you are running on a failover cluster instance
  171.  
  172.  
  173. -- SQL Server NUMA Node information (Query 9) (SQL Server NUMA Info)
  174. SELECT node_id, node_state_desc, memory_node_id, processor_group, online_scheduler_count,
  175. active_worker_count, avg_load_balance, resource_monitor_state
  176. FROM sys.dm_os_nodes WITH (NOLOCK)
  177. WHERE node_state_desc <> N'ONLINE DAC' OPTION (RECOMPILE);
  178.  
  179. -- Gives you some useful information about the composition
  180. -- and relative load on your NUMA nodes
  181.  
  182.  
  183. -- Hardware information from SQL Server 2012 (Query 10) (Hardware Info)
  184. -- (Cannot distinguish between HT and multi-core)
  185. SELECT cpu_count AS [Logical CPU Count], scheduler_count, hyperthread_ratio AS [Hyperthread Ratio],
  186. cpu_count/hyperthread_ratio AS [Physical CPU Count],
  187. physical_memory_kb/1024 AS [Physical Memory (MB)], committed_kb/1024 AS [Committed Memory (MB)],
  188. committed_target_kb/1024 AS [Committed Target Memory (MB)],
  189. max_workers_count AS [Max Workers Count], affinity_type_desc AS [Affinity Type],
  190. sqlserver_start_time AS [SQL Server Start Time], virtual_machine_type_desc AS [Virtual Machine Type]
  191. FROM sys.dm_os_sys_info WITH (NOLOCK) OPTION (RECOMPILE);
  192.  
  193. -- Gives you some good basic hardware information about your database server
  194. -- Note: virtual_machine_type_desc of HYPERVISOR does not automatically mean you are running SQL Server inside of a VM
  195. -- It merely indicates that you have a hypervisor running on your host
  196.  
  197.  
  198. -- Get System Manufacturer and model number from (Query 11) (System Manufacturer)
  199. -- SQL Server Error log. This query might take a few seconds
  200. -- if you have not recycled your error log recently
  201. EXEC xp_readerrorlog 0, 1, N'Manufacturer';
  202.  
  203. -- This can help you determine the capabilities
  204. -- and capacities of your database server
  205.  
  206. -- Get socket, physical core and logical core count from (Query 12) (Core Counts)
  207. -- SQL Server Error log. This query might take a few seconds
  208. -- if you have not recycled your error log recently
  209. EXEC sys.xp_readerrorlog 0, 1, N'detected', N'socket';
  210.  
  211. -- This can help you determine the exact core counts used by SQL Server
  212. -- and whether HT is enabled or not
  213.  
  214.  
  215. -- Get processor description from Windows Registry (Query 13) (Processor Description)
  216. EXEC xp_instance_regread N'HKEY_LOCAL_MACHINE', N'HARDWARE\DESCRIPTION\System\CentralProcessor\0', N'ProcessorNameString';
  217.  
  218. -- Gives you the model number and rated clock speed of your processor(s)
  219. -- Your processors may be running at less that the rated clock speed due
  220. -- to the Windows Power Plan or hardware power management
  221.  
  222.  
  223. -- Shows you where the SQL Server failover cluster diagnostic log is located and how it is configured (Query 14) (SQL Server Error Log)
  224. SELECT is_enabled, [path], max_size, max_files
  225. FROM sys.dm_os_server_diagnostics_log_configurations WITH (NOLOCK) OPTION (RECOMPILE);
  226.  
  227. -- Knowing this information is important for troubleshooting purposes
  228. -- Also shows you the location of other error and diagnostic log files
  229.  
  230.  
  231. -- Get information about your OS cluster (if your database server is in a cluster) (Query 15) (Cluster Properties)
  232. SELECT VerboseLogging, SqlDumperDumpFlags, SqlDumperDumpPath,
  233. SqlDumperDumpTimeOut, FailureConditionLevel, HealthCheckTimeout
  234. FROM sys.dm_os_cluster_properties WITH (NOLOCK) OPTION (RECOMPILE);
  235.  
  236. -- You will see no results if your instance is not clustered
  237.  
  238.  
  239. -- Get information about your cluster nodes and their status (Query 16) (Cluster Node Properties)
  240. -- (if your database server is in a failover cluster)
  241. SELECT NodeName, status_description, is_current_owner
  242. FROM sys.dm_os_cluster_nodes WITH (NOLOCK) OPTION (RECOMPILE);
  243.  
  244. -- Knowing which node owns the cluster resources is critical
  245. -- Especially when you are installing Windows or SQL Server updates
  246. -- You will see no results if your instance is not clustered
  247.  
  248.  
  249. -- Get information about any AlwaysOn AG cluster this instance is a part of (Query 17) (AlwaysOn AG Cluster)
  250. SELECT cluster_name, quorum_type_desc, quorum_state_desc
  251. FROM sys.dm_hadr_cluster WITH (NOLOCK) OPTION (RECOMPILE);
  252.  
  253. -- You will see no results if your instance is not using AlwaysOn AGs
  254.  
  255.  
  256. -- Get configuration values for instance (Query 18) (Configuration Values)
  257. SELECT name, value, value_in_use, minimum, maximum, [description], is_dynamic, is_advanced
  258. FROM sys.configurations WITH (NOLOCK)
  259. ORDER BY name OPTION (RECOMPILE);
  260.  
  261. -- Focus on
  262. -- backup compression default (should be 1 in most cases)
  263. -- cost threshold for parallelism
  264. -- clr enabled (only enable if it is needed)
  265. -- lightweight pooling (should be zero)
  266. -- max degree of parallelism
  267. -- max server memory (MB) (set to an appropriate value)
  268. -- optimize for ad hoc workloads (should be 1)
  269. -- priority boost (should be zero)
  270.  
  271.  
  272. -- Get information about TCP Listener for SQL Server (Query 19) (TCP Listener States)
  273. SELECT listener_id, ip_address, is_ipv4, port, type_desc, state_desc, start_time
  274. FROM sys.dm_tcp_listener_states WITH (NOLOCK)
  275. ORDER BY listener_id OPTION (RECOMPILE);
  276.  
  277. -- Helpful for network and connectivity troubleshooting
  278.  
  279.  
  280.  
  281. -- Get information on location, time and size of any memory dumps from SQL Server (Query 20) (Memory Dump Info)
  282. SELECT [filename], creation_time, size_in_bytes/1048576.0 AS [Size (MB)]
  283. FROM sys.dm_server_memory_dumps WITH (NOLOCK)
  284. ORDER BY creation_time DESC OPTION (RECOMPILE);
  285.  
  286. -- This will not return any rows if you have
  287. -- not had any memory dumps (which is a good thing)
  288.  
  289.  
  290. -- File names and paths for TempDB and all user databases in instance (Query 21) (Database Filenames and Paths)
  291. SELECT DB_NAME([database_id]) AS [Database Name],
  292. [file_id], name, physical_name, type_desc, state_desc,
  293. is_percent_growth, growth,
  294. CONVERT(bigint, growth/128.0) AS [Growth in MB],
  295. CONVERT(bigint, size/128.0) AS [Total Size in MB]
  296. FROM sys.master_files WITH (NOLOCK)
  297. WHERE [database_id] > 4
  298. AND [database_id] <> 32767
  299. OR [database_id] = 2
  300. ORDER BY DB_NAME([database_id]) OPTION (RECOMPILE);
  301.  
  302. -- Things to look at:
  303. -- Are data files and log files on different drives?
  304. -- Is everything on the C: drive?
  305. -- Is TempDB on dedicated drives?
  306. -- Is there only one TempDB data file?
  307. -- Are all of the TempDB data files the same size?
  308. -- Are there multiple data files for user databases?
  309. -- Is percent growth enabled for any files (which is bad)?
  310.  
  311.  
  312. -- Volume info for all LUNS that have database files on the current instance (SQL Server 2008 R2 SP1 or greater) (Query 22) (Volume Info)
  313. SELECT DISTINCT vs.volume_mount_point, vs.file_system_type,
  314. vs.logical_volume_name, CONVERT(DECIMAL(18,2),vs.total_bytes/1073741824.0) AS [Total Size (GB)],
  315. CONVERT(DECIMAL(18,2),vs.available_bytes/1073741824.0) AS [Available Size (GB)],
  316. CAST(CAST(vs.available_bytes AS FLOAT)/ CAST(vs.total_bytes AS FLOAT) AS DECIMAL(18,2)) * 100 AS [Space Free %]
  317. FROM sys.master_files AS f WITH (NOLOCK)
  318. CROSS APPLY sys.dm_os_volume_stats(f.database_id, f.[file_id]) AS vs OPTION (RECOMPILE);
  319.  
  320. --Shows you the total and free space on the LUNs where you have database files
  321.  
  322.  
  323. -- Look for I/O requests taking longer than 15 seconds in the five most recent SQL Server Error Logs (Query 23) (IO Warnings)
  324. CREATE TABLE #IOWarningResults(LogDate datetime, ProcessInfo sysname, LogText nvarchar(1000));
  325.  
  326. INSERT INTO #IOWarningResults
  327. EXEC xp_readerrorlog 0, 1, N'taking longer than 15 seconds';
  328.  
  329. INSERT INTO #IOWarningResults
  330. EXEC xp_readerrorlog 1, 1, N'taking longer than 15 seconds';
  331.  
  332. INSERT INTO #IOWarningResults
  333. EXEC xp_readerrorlog 2, 1, N'taking longer than 15 seconds';
  334.  
  335. INSERT INTO #IOWarningResults
  336. EXEC xp_readerrorlog 3, 1, N'taking longer than 15 seconds';
  337.  
  338. INSERT INTO #IOWarningResults
  339. EXEC xp_readerrorlog 4, 1, N'taking longer than 15 seconds';
  340.  
  341. SELECT LogDate, ProcessInfo, LogText
  342. FROM #IOWarningResults
  343. ORDER BY LogDate DESC;
  344.  
  345. DROP TABLE #IOWarningResults;
  346.  
  347. -- Finding 15 second I/O warnings in the SQL Server Error Log is useful evidence of
  348. -- poor I/O performance (which might have many different causes)
  349.  
  350.  
  351. -- Drive level latency information (Query 24) (Drive Level Latency)
  352. -- Based on code from Jimmy May
  353. SELECT [Drive],
  354. CASE
  355. WHEN num_of_reads = 0 THEN 0
  356. ELSE (io_stall_read_ms/num_of_reads)
  357. END AS [Read Latency],
  358. CASE
  359. WHEN io_stall_write_ms = 0 THEN 0
  360. ELSE (io_stall_write_ms/num_of_writes)
  361. END AS [Write Latency],
  362. CASE
  363. WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0
  364. ELSE (io_stall/(num_of_reads + num_of_writes))
  365. END AS [Overall Latency],
  366. CASE
  367. WHEN num_of_reads = 0 THEN 0
  368. ELSE (num_of_bytes_read/num_of_reads)
  369. END AS [Avg Bytes/Read],
  370. CASE
  371. WHEN io_stall_write_ms = 0 THEN 0
  372. ELSE (num_of_bytes_written/num_of_writes)
  373. END AS [Avg Bytes/Write],
  374. CASE
  375. WHEN (num_of_reads = 0 AND num_of_writes = 0) THEN 0
  376. ELSE ((num_of_bytes_read + num_of_bytes_written)/(num_of_reads + num_of_writes))
  377. END AS [Avg Bytes/Transfer]
  378. FROM (SELECT LEFT(UPPER(mf.physical_name), 2) AS Drive, SUM(num_of_reads) AS num_of_reads,
  379. SUM(io_stall_read_ms) AS io_stall_read_ms, SUM(num_of_writes) AS num_of_writes,
  380. SUM(io_stall_write_ms) AS io_stall_write_ms, SUM(num_of_bytes_read) AS num_of_bytes_read,
  381. SUM(num_of_bytes_written) AS num_of_bytes_written, SUM(io_stall) AS io_stall
  382. FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS vfs
  383. INNER JOIN sys.master_files AS mf WITH (NOLOCK)
  384. ON vfs.database_id = mf.database_id AND vfs.file_id = mf.file_id
  385. GROUP BY LEFT(UPPER(mf.physical_name), 2)) AS tab
  386. ORDER BY [Overall Latency] OPTION (RECOMPILE);
  387.  
  388. -- Shows you the drive-level latency for reads and writes, in milliseconds
  389. -- Latency above 20-25ms is usually a problem
  390.  
  391.  
  392. -- Calculates average stalls per read, per write, and per total input/output for each database file (Query 25) (IO Stalls by File)
  393. SELECT DB_NAME(fs.database_id) AS [Database Name], CAST(fs.io_stall_read_ms/(1.0 + fs.num_of_reads) AS NUMERIC(10,1)) AS [avg_read_stall_ms],
  394. CAST(fs.io_stall_write_ms/(1.0 + fs.num_of_writes) AS NUMERIC(10,1)) AS [avg_write_stall_ms],
  395. CAST((fs.io_stall_read_ms + fs.io_stall_write_ms)/(1.0 + fs.num_of_reads + fs.num_of_writes) AS NUMERIC(10,1)) AS [avg_io_stall_ms],
  396. CONVERT(DECIMAL(18,2), mf.size/128.0) AS [File Size (MB)], mf.physical_name, mf.type_desc, fs.io_stall_read_ms, fs.num_of_reads,
  397. fs.io_stall_write_ms, fs.num_of_writes, fs.io_stall_read_ms + fs.io_stall_write_ms AS [io_stalls], fs.num_of_reads + fs.num_of_writes AS [total_io]
  398. FROM sys.dm_io_virtual_file_stats(null,null) AS fs
  399. INNER JOIN sys.master_files AS mf WITH (NOLOCK)
  400. ON fs.database_id = mf.database_id
  401. AND fs.[file_id] = mf.[file_id]
  402. ORDER BY avg_io_stall_ms DESC OPTION (RECOMPILE);
  403.  
  404. -- Helps determine which database files on the entire instance have the most I/O bottlenecks
  405. -- This can help you decide whether certain LUNs are overloaded and whether you might
  406. -- want to move some files to a different location or perhaps improve your I/O performance
  407.  
  408.  
  409. -- Recovery model, log reuse wait description, log file size, log usage size (Query 26) (Database Properties)
  410. -- and compatibility level for all databases on instance
  411. SELECT db.[name] AS [Database Name], db.recovery_model_desc AS [Recovery Model], db.state_desc,
  412. db.log_reuse_wait_desc AS [Log Reuse Wait Description],
  413. CONVERT(DECIMAL(18,2), ls.cntr_value/1024.0) AS [Log Size (MB)], CONVERT(DECIMAL(18,2), lu.cntr_value/1024.0) AS [Log Used (MB)],
  414. CAST(CAST(lu.cntr_value AS FLOAT) / CAST(ls.cntr_value AS FLOAT)AS DECIMAL(18,2)) * 100 AS [Log Used %],
  415. db.[compatibility_level] AS [DB Compatibility Level],
  416. db.page_verify_option_desc AS [Page Verify Option], db.is_auto_create_stats_on, db.is_auto_update_stats_on,
  417. db.is_auto_update_stats_async_on, db.is_parameterization_forced,
  418. db.snapshot_isolation_state_desc, db.is_read_committed_snapshot_on,
  419. db.is_auto_close_on, db.is_auto_shrink_on, db.target_recovery_time_in_seconds, db.is_cdc_enabled
  420. FROM sys.databases AS db WITH (NOLOCK)
  421. INNER JOIN sys.dm_os_performance_counters AS lu WITH (NOLOCK)
  422. ON db.name = lu.instance_name
  423. INNER JOIN sys.dm_os_performance_counters AS ls WITH (NOLOCK)
  424. ON db.name = ls.instance_name
  425. WHERE lu.counter_name LIKE N'Log File(s) Used Size (KB)%'
  426. AND ls.counter_name LIKE N'Log File(s) Size (KB)%'
  427. AND ls.cntr_value > 0 OPTION (RECOMPILE);
  428.  
  429. -- Things to look at:
  430. -- How many databases are on the instance?
  431. -- What recovery models are they using?
  432. -- What is the log reuse wait description?
  433. -- How full are the transaction logs ?
  434. -- What compatibility level are the databases on?
  435. -- What is the Page Verify Option? (should be CHECKSUM)
  436. -- Is Auto Update Statistics Asynchronously enabled?
  437. -- Make sure auto_shrink and auto_close are not enabled!
  438.  
  439.  
  440.  
  441. -- Missing Indexes for all databases by Index Advantage (Query 27) (Missing Indexes All Databases)
  442. SELECT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage],
  443. migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
  444. mid.equality_columns, mid.inequality_columns, mid.included_columns,
  445. migs.unique_compiles, migs.user_seeks, migs.avg_total_user_cost, migs.avg_user_impact
  446. FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
  447. INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
  448. ON migs.group_handle = mig.index_group_handle
  449. INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
  450. ON mig.index_handle = mid.index_handle
  451. ORDER BY index_advantage DESC OPTION (RECOMPILE);
  452.  
  453. -- Getting missing index information for all of the databases on the instance is very useful
  454. -- Look at last user seek time, number of user seeks to help determine source and importance
  455. -- Also look at avg_user_impact and avg_total_user_cost to help determine importance
  456. -- SQL Server is overly eager to add included columns, so beware
  457. -- Do not just blindly add indexes that show up from this query!!!
  458.  
  459.  
  460.  
  461. -- Get VLF Counts for all databases on the instance (Query 28) (VLF Counts)
  462. -- (adapted from Michelle Ufford)
  463. CREATE TABLE #VLFInfo (RecoveryUnitID int, FileID int,
  464. FileSize bigint, StartOffset bigint,
  465. FSeqNo bigint, [Status] bigint,
  466. Parity bigint, CreateLSN numeric(38));
  467.  
  468. CREATE TABLE #VLFCountResults(DatabaseName sysname, VLFCount int);
  469.  
  470. EXEC sp_MSforeachdb N'Use [?];
  471.  
  472. INSERT INTO #VLFInfo
  473. EXEC sp_executesql N''DBCC LOGINFO([?])'';
  474.  
  475. INSERT INTO #VLFCountResults
  476. SELECT DB_NAME(), COUNT(*)
  477. FROM #VLFInfo;
  478.  
  479. TRUNCATE TABLE #VLFInfo;'
  480.  
  481. SELECT DatabaseName, VLFCount
  482. FROM #VLFCountResults
  483. ORDER BY VLFCount DESC;
  484.  
  485. DROP TABLE #VLFInfo;
  486. DROP TABLE #VLFCountResults;
  487.  
  488. -- High VLF counts can affect write performance
  489. -- and they can make database restores and recovery take much longer
  490. -- Try to keep your VLF counts under 200 in most cases
  491.  
  492.  
  493.  
  494. -- Get CPU utilization by database (Query 29) (CPU Usage by Database)
  495. WITH DB_CPU_Stats
  496. AS
  497. (SELECT DatabaseID, DB_Name(DatabaseID) AS [Database Name], SUM(total_worker_time) AS [CPU_Time_Ms]
  498. FROM sys.dm_exec_query_stats AS qs
  499. CROSS APPLY (SELECT CONVERT(int, value) AS [DatabaseID]
  500. FROM sys.dm_exec_plan_attributes(qs.plan_handle)
  501. WHERE attribute = N'dbid') AS F_DB
  502. GROUP BY DatabaseID)
  503. SELECT ROW_NUMBER() OVER(ORDER BY [CPU_Time_Ms] DESC) AS [CPU Rank],
  504. [Database Name], [CPU_Time_Ms] AS [CPU Time (ms)],
  505. CAST([CPU_Time_Ms] * 1.0 / SUM([CPU_Time_Ms]) OVER() * 100.0 AS DECIMAL(5, 2)) AS [CPU Percent]
  506. FROM DB_CPU_Stats
  507. WHERE DatabaseID <> 32767 -- ResourceDB
  508. ORDER BY [CPU Rank] OPTION (RECOMPILE);
  509.  
  510. -- Helps determine which database is using the most CPU resources on the instance
  511.  
  512.  
  513. -- Get I/O utilization by database (Query 30) (IO Usage By Database)
  514. WITH Aggregate_IO_Statistics
  515. AS
  516. (SELECT DB_NAME(database_id) AS [Database Name],
  517. CAST(SUM(num_of_bytes_read + num_of_bytes_written)/1048576 AS DECIMAL(12, 2)) AS io_in_mb
  518. FROM sys.dm_io_virtual_file_stats(NULL, NULL) AS [DM_IO_STATS]
  519. GROUP BY database_id)
  520. SELECT ROW_NUMBER() OVER(ORDER BY io_in_mb DESC) AS [I/O Rank], [Database Name], io_in_mb AS [Total I/O (MB)],
  521. CAST(io_in_mb/ SUM(io_in_mb) OVER() * 100.0 AS DECIMAL(5,2)) AS [I/O Percent]
  522. FROM Aggregate_IO_Statistics
  523. ORDER BY [I/O Rank] OPTION (RECOMPILE);
  524.  
  525. -- Helps determine which database is using the most I/O resources on the instance
  526.  
  527.  
  528. -- Get total buffer usage by database for current instance (Query 31) (Total Buffer Usage by Database)
  529. -- This make take some time to run on a busy instance
  530. WITH AggregateBufferPoolUsage
  531. AS
  532. (SELECT DB_NAME(database_id) AS [Database Name],
  533. CAST(COUNT(*) * 8/1024.0 AS DECIMAL (10,2)) AS [CachedSize]
  534. FROM sys.dm_os_buffer_descriptors WITH (NOLOCK)
  535. WHERE database_id <> 32767 -- ResourceDB
  536. GROUP BY DB_NAME(database_id))
  537. SELECT ROW_NUMBER() OVER(ORDER BY CachedSize DESC) AS [Buffer Pool Rank], [Database Name], CachedSize AS [Cached Size (MB)],
  538. CAST(CachedSize / SUM(CachedSize) OVER() * 100.0 AS DECIMAL(5,2)) AS [Buffer Pool Percent]
  539. FROM AggregateBufferPoolUsage
  540. ORDER BY [Buffer Pool Rank] OPTION (RECOMPILE);
  541.  
  542. -- Tells you how much memory (in the buffer pool)
  543. -- is being used by each database on the instance
  544.  
  545.  
  546. -- Clear Wait Stats with this command
  547. -- DBCC SQLPERF('sys.dm_os_wait_stats', CLEAR);
  548.  
  549. -- Isolate top waits for server instance since last restart or wait statistics clear (Query 32) (Top Waits)
  550. WITH [Waits]
  551. AS (SELECT wait_type, wait_time_ms/ 1000.0 AS [WaitS],
  552. (wait_time_ms - signal_wait_time_ms) / 1000.0 AS [ResourceS],
  553. signal_wait_time_ms / 1000.0 AS [SignalS],
  554. waiting_tasks_count AS [WaitCount],
  555. 100.0 * wait_time_ms / SUM (wait_time_ms) OVER() AS [Percentage],
  556. ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS [RowNum]
  557. FROM sys.dm_os_wait_stats WITH (NOLOCK)
  558. WHERE [wait_type] NOT IN (
  559. N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
  560. N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
  561. N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE',
  562. N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
  563. N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
  564. N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
  565. N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT',
  566. N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
  567. N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', N'ONDEMAND_TASK_QUEUE',
  568. N'PWAIT_ALL_COMPONENTS_INITIALIZED', N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
  569. N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'REQUEST_FOR_DEADLOCK_SEARCH',
  570. N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
  571. N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
  572. N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
  573. N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',
  574. N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
  575. N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
  576. N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'XE_DISPATCHER_JOIN',
  577. N'XE_DISPATCHER_WAIT', N'XE_TIMER_EVENT')
  578. AND waiting_tasks_count > 0)
  579. SELECT
  580. MAX (W1.wait_type) AS [WaitType],
  581. CAST (MAX (W1.WaitS) AS DECIMAL (16,2)) AS [Wait_Sec],
  582. CAST (MAX (W1.ResourceS) AS DECIMAL (16,2)) AS [Resource_Sec],
  583. CAST (MAX (W1.SignalS) AS DECIMAL (16,2)) AS [Signal_Sec],
  584. MAX (W1.WaitCount) AS [Wait Count],
  585. CAST (MAX (W1.Percentage) AS DECIMAL (5,2)) AS [Wait Percentage],
  586. CAST ((MAX (W1.WaitS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgWait_Sec],
  587. CAST ((MAX (W1.ResourceS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgRes_Sec],
  588. CAST ((MAX (W1.SignalS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS [AvgSig_Sec]
  589. FROM Waits AS W1
  590. INNER JOIN Waits AS W2
  591. ON W2.RowNum <= W1.RowNum
  592. GROUP BY W1.RowNum
  593. HAVING SUM (W2.Percentage) - MAX (W1.Percentage) < 99 -- percentage threshold
  594. OPTION (RECOMPILE);
  595.  
  596.  
  597. -- The SQL Server Wait Type Repository
  598. -- http://blogs.msdn.com/b/psssql/archive/2009/11/03/the-sql-server-wait-type-repository.aspx
  599.  
  600. -- Wait statistics, or please tell me where it hurts
  601. -- http://www.sqlskills.com/blogs/paul/wait-statistics-or-please-tell-me-where-it-hurts/
  602.  
  603. -- SQL Server 2005 Performance Tuning using the Waits and Queues
  604. -- http://technet.microsoft.com/en-us/library/cc966413.aspx
  605.  
  606. -- sys.dm_os_wait_stats (Transact-SQL)
  607. -- http://msdn.microsoft.com/en-us/library/ms179984(v=sql.120).aspx
  608.  
  609.  
  610.  
  611. -- Signal Waits for instance (Query 33) (Signal Waits)
  612. SELECT CAST(100.0 * SUM(signal_wait_time_ms) / SUM (wait_time_ms) AS NUMERIC(20,2)) AS [% Signal (CPU) Waits],
  613. CAST(100.0 * SUM(wait_time_ms - signal_wait_time_ms) / SUM (wait_time_ms) AS NUMERIC(20,2)) AS [% Resource Waits]
  614. FROM sys.dm_os_wait_stats WITH (NOLOCK)
  615. WHERE wait_type NOT IN (
  616. N'BROKER_EVENTHANDLER', N'BROKER_RECEIVE_WAITFOR', N'BROKER_TASK_STOP',
  617. N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER', N'CHECKPOINT_QUEUE',
  618. N'CHKPT', N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT', N'CLR_SEMAPHORE',
  619. N'DBMIRROR_DBM_EVENT', N'DBMIRROR_EVENTS_QUEUE', N'DBMIRROR_WORKER_QUEUE',
  620. N'DBMIRRORING_CMD', N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',
  621. N'EXECSYNC', N'FSAGENT', N'FT_IFTS_SCHEDULER_IDLE_WAIT', N'FT_IFTSHC_MUTEX',
  622. N'HADR_CLUSAPI_CALL', N'HADR_FILESTREAM_IOMGR_IOCOMPLETION', N'HADR_LOGCAPTURE_WAIT',
  623. N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK', N'HADR_WORK_QUEUE',
  624. N'KSOURCE_WAKEUP', N'LAZYWRITER_SLEEP', N'LOGMGR_QUEUE', N'ONDEMAND_TASK_QUEUE',
  625. N'PWAIT_ALL_COMPONENTS_INITIALIZED', N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP',
  626. N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP', N'REQUEST_FOR_DEADLOCK_SEARCH',
  627. N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK', N'SLEEP_BPOOL_FLUSH', N'SLEEP_DBSTARTUP',
  628. N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY', N'SLEEP_MASTERMDREADY',
  629. N'SLEEP_MASTERUPGRADED', N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK', N'SLEEP_TASK',
  630. N'SLEEP_TEMPDBSTARTUP', N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',
  631. N'SQLTRACE_BUFFER_FLUSH', N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',
  632. N'WAIT_FOR_RESULTS', N'WAITFOR', N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',
  633. N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG', N'WAIT_XTP_CKPT_CLOSE', N'XE_DISPATCHER_JOIN',
  634. N'XE_DISPATCHER_WAIT', N'XE_TIMER_EVENT') OPTION (RECOMPILE);
  635.  
  636. -- Signal Waits above 10-15% is usually a confirming sign of CPU pressure
  637. -- Cumulative wait stats are not as useful on an idle instance that is not under load or performance pressure
  638. -- Resource waits are non-CPU related waits
  639.  
  640.  
  641.  
  642. -- Get logins that are connected and how many sessions they have (Query 34) (Connection Counts)
  643. SELECT login_name, [program_name], COUNT(session_id) AS [session_count]
  644. FROM sys.dm_exec_sessions WITH (NOLOCK)
  645. GROUP BY login_name, [program_name]
  646. ORDER BY COUNT(session_id) DESC OPTION (RECOMPILE);
  647.  
  648. -- This can help characterize your workload and
  649. -- determine whether you are seeing a normal level of activity
  650.  
  651.  
  652. -- Get a count of SQL connections by IP address (Query 35) (Connection Counts by IP Address)
  653. SELECT ec.client_net_address, es.[program_name], es.[host_name], es.login_name,
  654. COUNT(ec.session_id) AS [connection count]
  655. FROM sys.dm_exec_sessions AS es WITH (NOLOCK)
  656. INNER JOIN sys.dm_exec_connections AS ec WITH (NOLOCK)
  657. ON es.session_id = ec.session_id
  658. GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name
  659. ORDER BY ec.client_net_address, es.[program_name] OPTION (RECOMPILE);
  660.  
  661. -- This helps you figure where your database load is coming from
  662. -- and verifies connectivity from other machines
  663.  
  664.  
  665. -- Get Average Task Counts (run multiple times) (Query 36) (Avg Task Counts)
  666. SELECT AVG(current_tasks_count) AS [Avg Task Count],
  667. AVG(runnable_tasks_count) AS [Avg Runnable Task Count],
  668. AVG(pending_disk_io_count) AS [Avg Pending DiskIO Count]
  669. FROM sys.dm_os_schedulers WITH (NOLOCK)
  670. WHERE scheduler_id < 255 OPTION (RECOMPILE);
  671.  
  672. -- Sustained values above 10 suggest further investigation in that area
  673. -- High Avg Task Counts are often caused by blocking/deadlocking or other resource contention
  674.  
  675. -- Sustained values above 1 suggest further investigation in that area
  676. -- High Avg Runnable Task Counts are a good sign of CPU pressure
  677. -- High Avg Pending DiskIO Counts are a sign of disk pressure
  678.  
  679.  
  680. -- Get CPU Utilization History for last 256 minutes (in one minute intervals) (Query 37) (CPU Utilization History)
  681. -- This version works with SQL Server 2012
  682. DECLARE @ts_now bigint = (SELECT cpu_ticks/(cpu_ticks/ms_ticks) FROM sys.dm_os_sys_info WITH (NOLOCK));
  683.  
  684. SELECT TOP(256) SQLProcessUtilization AS [SQL Server Process CPU Utilization],
  685. SystemIdle AS [System Idle Process],
  686. 100 - SystemIdle - SQLProcessUtilization AS [Other Process CPU Utilization],
  687. DATEADD(ms, -1 * (@ts_now - [timestamp]), GETDATE()) AS [Event Time]
  688. FROM (
  689. SELECT record.value('(./Record/@id)[1]', 'int') AS record_id,
  690. record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)[1]', 'int')
  691. AS [SystemIdle],
  692. record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)[1]',
  693. 'int')
  694. AS [SQLProcessUtilization], [timestamp]
  695. FROM (
  696. SELECT [timestamp], CONVERT(xml, record) AS [record]
  697. FROM sys.dm_os_ring_buffers WITH (NOLOCK)
  698. WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR'
  699. AND record LIKE N'%<SystemHealth>%') AS x
  700. ) AS y
  701. ORDER BY record_id DESC OPTION (RECOMPILE);
  702.  
  703. -- Look at the trend over the entire period.
  704. -- Also look at high sustained Other Process CPU Utilization values
  705.  
  706.  
  707.  
  708. -- Get top total worker time queries for entire instance (Query 38) (Top Worker Time Queries)
  709. SELECT TOP(50) DB_NAME(t.[dbid]) AS [Database Name], t.[text] AS [Query Text],
  710. qs.total_worker_time AS [Total Worker Time], qs.min_worker_time AS [Min Worker Time],
  711. qs.total_worker_time/qs.execution_count AS [Avg Worker Time],
  712. qs.max_worker_time AS [Max Worker Time], qs.execution_count AS [Execution Count],
  713. qs.total_elapsed_time/qs.execution_count AS [Avg Elapsed Time],
  714. qs.total_logical_reads/qs.execution_count AS [Avg Logical Reads],
  715. qs.total_physical_reads/qs.execution_count AS [Avg Physical Reads],
  716. qp.query_plan AS [Query Plan], qs.creation_time AS [Creation Time]
  717. FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
  718. CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
  719. CROSS APPLY sys.dm_exec_query_plan(plan_handle) AS qp
  720. ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
  721.  
  722. -- Helps you find the most expensive queries from a CPU perspective across the entire instance
  723.  
  724.  
  725. -- Good basic information about OS memory amounts and state (Query 39) (System Memory)
  726. SELECT total_physical_memory_kb/1024 AS [Physical Memory (MB)],
  727. available_physical_memory_kb/1024 AS [Available Memory (MB)],
  728. total_page_file_kb/1024 AS [Total Page File (MB)],
  729. available_page_file_kb/1024 AS [Available Page File (MB)],
  730. system_cache_kb/1024 AS [System Cache (MB)],
  731. system_memory_state_desc AS [System Memory State]
  732. FROM sys.dm_os_sys_memory WITH (NOLOCK) OPTION (RECOMPILE);
  733.  
  734. -- You want to see "Available physical memory is high"
  735. -- This indicates that you are not under external memory pressure
  736.  
  737.  
  738. -- SQL Server Process Address space info (Query 40) (Process Memory)
  739. -- (shows whether locked pages is enabled, among other things)
  740. SELECT physical_memory_in_use_kb/1024 AS [SQL Server Memory Usage (MB)],
  741. large_page_allocations_kb, locked_page_allocations_kb, page_fault_count,
  742. memory_utilization_percentage, available_commit_limit_kb,
  743. process_physical_memory_low, process_virtual_memory_low
  744. FROM sys.dm_os_process_memory WITH (NOLOCK) OPTION (RECOMPILE);
  745.  
  746. -- You want to see 0 for process_physical_memory_low
  747. -- You want to see 0 for process_virtual_memory_low
  748. -- This indicates that you are not under internal memory pressure
  749.  
  750.  
  751. -- Page Life Expectancy (PLE) value for each NUMA node in current instance (Query 41) (PLE by NUMA Node)
  752. SELECT @@SERVERNAME AS [Server Name], [object_name], instance_name, cntr_value AS [Page Life Expectancy]
  753. FROM sys.dm_os_performance_counters WITH (NOLOCK)
  754. WHERE [object_name] LIKE N'%Buffer Node%' -- Handles named instances
  755. AND counter_name = N'Page life expectancy' OPTION (RECOMPILE);
  756.  
  757. -- PLE is a good measurement of memory pressure.
  758. -- Higher PLE is better. Watch the trend over time, not the absolute value.
  759. -- This will only return one row for non-NUMA systems.
  760.  
  761.  
  762. -- Memory Grants Pending value for current instance (Query 42) (Memory Grants Pending)
  763. SELECT @@SERVERNAME AS [Server Name], [object_name], cntr_value AS [Memory Grants Pending]
  764. FROM sys.dm_os_performance_counters WITH (NOLOCK)
  765. WHERE [object_name] LIKE N'%Memory Manager%' -- Handles named instances
  766. AND counter_name = N'Memory Grants Pending' OPTION (RECOMPILE);
  767.  
  768. -- Memory Grants Pending above zero for a sustained period is a very strong indicator of memory pressure
  769.  
  770.  
  771. -- Memory Clerk Usage for instance (Query 43) (Memory Clerk Usage)
  772. -- Look for high value for CACHESTORE_SQLCP (Ad-hoc query plans)
  773. SELECT TOP(10) mc.[type] AS [Memory Clerk Type],
  774. CAST((SUM(mc.pages_kb)/1024.0) AS DECIMAL (15,2)) AS [Memory Usage (MB)]
  775. FROM sys.dm_os_memory_clerks AS mc WITH (NOLOCK)
  776. GROUP BY mc.[type]
  777. ORDER BY SUM(mc.pages_kb) DESC OPTION (RECOMPILE);
  778.  
  779. -- MEMORYCLERK_SQLBUFFERPOOL is new for SQL Server 2012. It should be your highest consumer of memory
  780.  
  781. -- CACHESTORE_SQLCP SQL Plans
  782. -- These are cached SQL statements or batches that aren't in stored procedures, functions and triggers
  783. -- Watch out for high values for CACHESTORE_SQLCP
  784.  
  785. -- CACHESTORE_OBJCP Object Plans
  786. -- These are compiled plans for stored procedures, functions and triggers
  787.  
  788.  
  789.  
  790.  
  791. -- Find single-use, ad-hoc and prepared queries that are bloating the plan cache (Query 44) (Ad hoc Queries)
  792. SELECT TOP(50) [text] AS [QueryText], cp.cacheobjtype, cp.objtype, cp.size_in_bytes/1024 AS [Plan Size in KB]
  793. FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
  794. CROSS APPLY sys.dm_exec_sql_text(plan_handle)
  795. WHERE cp.cacheobjtype = N'Compiled Plan'
  796. AND cp.objtype IN (N'Adhoc', N'Prepared')
  797. AND cp.usecounts = 1
  798. ORDER BY cp.size_in_bytes DESC OPTION (RECOMPILE);
  799.  
  800. -- Gives you the text, type and size of single-use ad-hoc and prepared queries that waste space in the plan cache
  801. -- Enabling 'optimize for ad hoc workloads' for the instance can help (SQL Server 2008 and above only)
  802. -- Running DBCC FREESYSTEMCACHE ('SQL Plans') periodically may be required to better control this.
  803. -- Enabling forced parameterization for the database can help, but test first!
  804.  
  805.  
  806. -- Database specific queries *****************************************************************
  807.  
  808. -- **** Switch to a user database *****
  809. USE YourDatabaseName;
  810. GO
  811.  
  812. -- Individual File Sizes and space available for current database (Query 45) (File Sizes and Space)
  813. SELECT f.name AS [File Name] , f.physical_name AS [Physical Name],
  814. CAST((f.size/128.0) AS DECIMAL(15,2)) AS [Total Size in MB],
  815. CAST(f.size/128.0 - CAST(FILEPROPERTY(f.name, 'SpaceUsed') AS int)/128.0 AS DECIMAL(15,2))
  816. AS [Available Space In MB], [file_id], fg.name AS [Filegroup Name]
  817. FROM sys.database_files AS f WITH (NOLOCK)
  818. LEFT OUTER JOIN sys.data_spaces AS fg WITH (NOLOCK)
  819. ON f.data_space_id = fg.data_space_id OPTION (RECOMPILE);
  820.  
  821. -- Look at how large and how full the files are and where they are located
  822. -- Make sure the transaction log is not full!!
  823.  
  824.  
  825.  
  826. -- I/O Statistics by file for the current database (Query 46) (IO Stats By File)
  827. SELECT DB_NAME(DB_ID()) AS [Database Name], df.name AS [Logical Name], vfs.[file_id],
  828. df.physical_name AS [Physical Name], vfs.num_of_reads, vfs.num_of_writes, vfs.io_stall_read_ms, vfs.io_stall_write_ms,
  829. CAST(100. * vfs.io_stall_read_ms/(vfs.io_stall_read_ms + vfs.io_stall_write_ms) AS DECIMAL(10,1)) AS [IO Stall Reads Pct],
  830. CAST(100. * vfs.io_stall_write_ms/(vfs.io_stall_write_ms + vfs.io_stall_read_ms) AS DECIMAL(10,1)) AS [IO Stall Writes Pct],
  831. (vfs.num_of_reads + vfs.num_of_writes) AS [Writes + Reads],
  832. CAST(vfs.num_of_bytes_read/1048576.0 AS DECIMAL(10, 2)) AS [MB Read],
  833. CAST(vfs.num_of_bytes_written/1048576.0 AS DECIMAL(10, 2)) AS [MB Written],
  834. CAST(100. * vfs.num_of_reads/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(10,1)) AS [# Reads Pct],
  835. CAST(100. * vfs.num_of_writes/(vfs.num_of_reads + vfs.num_of_writes) AS DECIMAL(10,1)) AS [# Write Pct],
  836. CAST(100. * vfs.num_of_bytes_read/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(10,1)) AS [Read Bytes Pct],
  837. CAST(100. * vfs.num_of_bytes_written/(vfs.num_of_bytes_read + vfs.num_of_bytes_written) AS DECIMAL(10,1)) AS [Written Bytes Pct]
  838. FROM sys.dm_io_virtual_file_stats(DB_ID(), NULL) AS vfs
  839. INNER JOIN sys.database_files AS df WITH (NOLOCK)
  840. ON vfs.[file_id]= df.[file_id] OPTION (RECOMPILE);
  841.  
  842. -- This helps you characterize your workload better from an I/O perspective for this database
  843. -- It helps you determine whether you has an OLTP or DW/DSS type of workload
  844.  
  845.  
  846.  
  847. -- Top cached queries by Execution Count (SQL Server 2012) (Query 47) (Query Execution Counts)
  848. SELECT TOP (100) qs.execution_count, qs.total_rows, qs.last_rows, qs.min_rows, qs.max_rows,
  849. qs.last_elapsed_time, qs.min_elapsed_time, qs.max_elapsed_time,
  850. total_worker_time, total_logical_reads,
  851. SUBSTRING(qt.TEXT,qs.statement_start_offset/2 +1,
  852. (CASE WHEN qs.statement_end_offset = -1
  853. THEN LEN(CONVERT(NVARCHAR(MAX), qt.TEXT)) * 2
  854. ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) AS query_text
  855. FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
  856. CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
  857. ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
  858.  
  859. -- Uses several new rows returned columns to help troubleshoot performance problems
  860.  
  861.  
  862. -- Top Cached SPs By Execution Count (SQL Server 2012) (Query 48) (SP Execution Counts)
  863. SELECT TOP(100) p.name AS [SP Name], qs.execution_count,
  864. ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
  865. qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.total_worker_time AS [TotalWorkerTime],
  866. qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
  867. qs.cached_time
  868. FROM sys.procedures AS p WITH (NOLOCK)
  869. INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
  870. ON p.[object_id] = qs.[object_id]
  871. WHERE qs.database_id = DB_ID()
  872. ORDER BY qs.execution_count DESC OPTION (RECOMPILE);
  873.  
  874. -- Tells you which cached stored procedures are called the most often
  875. -- This helps you characterize and baseline your workload
  876.  
  877.  
  878. -- Top Cached SPs By Avg Elapsed Time (SQL Server 2012) (Query 49) (SP Avg Elapsed Time)
  879. SELECT TOP(25) p.name AS [SP Name], qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
  880. qs.total_elapsed_time, qs.execution_count, ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time,
  881. GETDATE()), 0) AS [Calls/Minute], qs.total_worker_time/qs.execution_count AS [AvgWorkerTime],
  882. qs.total_worker_time AS [TotalWorkerTime], qs.cached_time
  883. FROM sys.procedures AS p WITH (NOLOCK)
  884. INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
  885. ON p.[object_id] = qs.[object_id]
  886. WHERE qs.database_id = DB_ID()
  887. ORDER BY avg_elapsed_time DESC OPTION (RECOMPILE);
  888.  
  889. -- This helps you find long-running cached stored procedures that
  890. -- may be easy to optimize with standard query tuning techniques
  891.  
  892.  
  893. -- Top Cached SPs By Avg Elapsed Time with execution time variability (SQL Server 2012) (Query 50) (SP Avg Elapsed Variable Time)
  894. SELECT TOP(25) p.name AS [SP Name], qs.execution_count, qs.min_elapsed_time,
  895. qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
  896. qs.max_elapsed_time, qs.last_elapsed_time, qs.cached_time
  897. FROM sys.procedures AS p WITH (NOLOCK)
  898. INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
  899. ON p.[object_id] = qs.[object_id]
  900. WHERE qs.database_id = DB_ID()
  901. ORDER BY avg_elapsed_time DESC OPTION (RECOMPILE);
  902.  
  903. -- This gives you some interesting information about the variability in the
  904. -- execution time of your cached stored procedures, which is useful for tuning
  905.  
  906.  
  907. -- Top Cached SPs By Total Worker time (SQL Server 2012). Worker time relates to CPU cost (Query 51) (SP Worker Time)
  908. SELECT TOP(25) p.name AS [SP Name], qs.total_worker_time AS [TotalWorkerTime],
  909. qs.total_worker_time/qs.execution_count AS [AvgWorkerTime], qs.execution_count,
  910. ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
  911. qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count
  912. AS [avg_elapsed_time], qs.cached_time
  913. FROM sys.procedures AS p WITH (NOLOCK)
  914. INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
  915. ON p.[object_id] = qs.[object_id]
  916. WHERE qs.database_id = DB_ID()
  917. ORDER BY qs.total_worker_time DESC OPTION (RECOMPILE);
  918.  
  919. -- This helps you find the most expensive cached stored procedures from a CPU perspective
  920. -- You should look at this if you see signs of CPU pressure
  921.  
  922.  
  923. -- Top Cached SPs By Total Logical Reads (SQL Server 2012). Logical reads relate to memory pressure (Query 52) (SP Logical Reads)
  924. SELECT TOP(25) p.name AS [SP Name], qs.total_logical_reads AS [TotalLogicalReads],
  925. qs.total_logical_reads/qs.execution_count AS [AvgLogicalReads],qs.execution_count,
  926. ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
  927. qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count
  928. AS [avg_elapsed_time], qs.cached_time
  929. FROM sys.procedures AS p WITH (NOLOCK)
  930. INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
  931. ON p.[object_id] = qs.[object_id]
  932. WHERE qs.database_id = DB_ID()
  933. ORDER BY qs.total_logical_reads DESC OPTION (RECOMPILE);
  934.  
  935. -- This helps you find the most expensive cached stored procedures from a memory perspective
  936. -- You should look at this if you see signs of memory pressure
  937.  
  938.  
  939. -- Top Cached SPs By Total Physical Reads (SQL Server 2012). Physical reads relate to disk I/O pressure (Query 53) (SP Physical Reads)
  940. SELECT TOP(25) p.name AS [SP Name],qs.total_physical_reads AS [TotalPhysicalReads],
  941. qs.total_physical_reads/qs.execution_count AS [AvgPhysicalReads], qs.execution_count,
  942. qs.total_logical_reads,qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count
  943. AS [avg_elapsed_time], qs.cached_time
  944. FROM sys.procedures AS p WITH (NOLOCK)
  945. INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
  946. ON p.[object_id] = qs.[object_id]
  947. WHERE qs.database_id = DB_ID()
  948. AND qs.total_physical_reads > 0
  949. ORDER BY qs.total_physical_reads DESC, qs.total_logical_reads DESC OPTION (RECOMPILE);
  950.  
  951. -- This helps you find the most expensive cached stored procedures from a read I/O perspective
  952. -- You should look at this if you see signs of I/O pressure or of memory pressure
  953.  
  954. -- Top Cached SPs By Total Logical Writes (SQL Server 2012) (Query 54) (SP Logical Writes)
  955. -- Logical writes relate to both memory and disk I/O pressure
  956. SELECT TOP(25) p.name AS [SP Name], qs.total_logical_writes AS [TotalLogicalWrites],
  957. qs.total_logical_writes/qs.execution_count AS [AvgLogicalWrites], qs.execution_count,
  958. ISNULL(qs.execution_count/DATEDIFF(Minute, qs.cached_time, GETDATE()), 0) AS [Calls/Minute],
  959. qs.total_elapsed_time, qs.total_elapsed_time/qs.execution_count AS [avg_elapsed_time],
  960. qs.cached_time
  961. FROM sys.procedures AS p WITH (NOLOCK)
  962. INNER JOIN sys.dm_exec_procedure_stats AS qs WITH (NOLOCK)
  963. ON p.[object_id] = qs.[object_id]
  964. WHERE qs.database_id = DB_ID()
  965. AND qs.total_logical_writes > 0
  966. ORDER BY qs.total_logical_writes DESC OPTION (RECOMPILE);
  967.  
  968. -- This helps you find the most expensive cached stored procedures from a write I/O perspective
  969. -- You should look at this if you see signs of I/O pressure or of memory pressure
  970.  
  971.  
  972. -- Lists the top statements by average input/output usage for the current database (Query 55) (Top IO Statements)
  973. SELECT TOP(50) OBJECT_NAME(qt.objectid, dbid) AS [SP Name],
  974. (qs.total_logical_reads + qs.total_logical_writes) /qs.execution_count AS [Avg IO], qs.execution_count AS [Execution Count],
  975. SUBSTRING(qt.[text],qs.statement_start_offset/2,
  976. (CASE
  977. WHEN qs.statement_end_offset = -1
  978. THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2
  979. ELSE qs.statement_end_offset
  980. END - qs.statement_start_offset)/2) AS [Query Text]
  981. FROM sys.dm_exec_query_stats AS qs WITH (NOLOCK)
  982. CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
  983. WHERE qt.[dbid] = DB_ID()
  984. ORDER BY [Avg IO] DESC OPTION (RECOMPILE);
  985.  
  986. -- Helps you find the most expensive statements for I/O by SP
  987.  
  988.  
  989.  
  990. -- Possible Bad NC Indexes (writes > reads) (Query 56) (Bad NC Indexes)
  991. SELECT OBJECT_NAME(s.[object_id]) AS [Table Name], i.name AS [Index Name], i.index_id,
  992. i.is_disabled, i.is_hypothetical, i.has_filter, i.fill_factor,
  993. user_updates AS [Total Writes], user_seeks + user_scans + user_lookups AS [Total Reads],
  994. user_updates - (user_seeks + user_scans + user_lookups) AS [Difference]
  995. FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
  996. INNER JOIN sys.indexes AS i WITH (NOLOCK)
  997. ON s.[object_id] = i.[object_id]
  998. AND i.index_id = s.index_id
  999. WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
  1000. AND s.database_id = DB_ID()
  1001. AND user_updates > (user_seeks + user_scans + user_lookups)
  1002. AND i.index_id > 1
  1003. ORDER BY [Difference] DESC, [Total Writes] DESC, [Total Reads] ASC OPTION (RECOMPILE);
  1004.  
  1005. -- Look for indexes with high numbers of writes and zero or very low numbers of reads
  1006. -- Consider your complete workload, and how long your instance has been running
  1007. -- Investigate further before dropping an index!
  1008.  
  1009.  
  1010. -- Missing Indexes for current database by Index Advantage (Query 57) (Missing Indexes)
  1011. SELECT DISTINCT CONVERT(decimal(18,2), user_seeks * avg_total_user_cost * (avg_user_impact * 0.01)) AS [index_advantage],
  1012. migs.last_user_seek, mid.[statement] AS [Database.Schema.Table],
  1013. mid.equality_columns, mid.inequality_columns, mid.included_columns,
  1014. migs.unique_compiles, migs.user_seeks, migs.avg_total_user_cost, migs.avg_user_impact,
  1015. OBJECT_NAME(mid.[object_id]) AS [Table Name], p.rows AS [Table Rows]
  1016. FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK)
  1017. INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK)
  1018. ON migs.group_handle = mig.index_group_handle
  1019. INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK)
  1020. ON mig.index_handle = mid.index_handle
  1021. INNER JOIN sys.partitions AS p WITH (NOLOCK)
  1022. ON p.[object_id] = mid.[object_id]
  1023. WHERE mid.database_id = DB_ID()
  1024. ORDER BY index_advantage DESC OPTION (RECOMPILE);
  1025.  
  1026. -- Look at index advantage, last user seek time, number of user seeks to help determine source and importance
  1027. -- SQL Server is overly eager to add included columns, so beware
  1028. -- Do not just blindly add indexes that show up from this query!!!
  1029.  
  1030.  
  1031. -- Find missing index warnings for cached plans in the current database (Query 58) (Missing Index Warnings)
  1032. -- Note: This query could take some time on a busy instance
  1033. SELECT TOP(25) OBJECT_NAME(objectid) AS [ObjectName],
  1034. query_plan, cp.objtype, cp.usecounts
  1035. FROM sys.dm_exec_cached_plans AS cp WITH (NOLOCK)
  1036. CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp
  1037. WHERE CAST(query_plan AS NVARCHAR(MAX)) LIKE N'%MissingIndex%'
  1038. AND dbid = DB_ID()
  1039. ORDER BY cp.usecounts DESC OPTION (RECOMPILE);
  1040.  
  1041. -- Helps you connect missing indexes to specific stored procedures
  1042. -- This can help you decide whether to add them or not
  1043.  
  1044.  
  1045. -- Breaks down buffers used by current database by object (table, index) in the buffer cache (Query 59) (Buffer Usage)
  1046. -- Note: This query could take some time on a busy instance
  1047. SELECT OBJECT_NAME(p.[object_id]) AS [Object Name], p.index_id,
  1048. CAST(COUNT(*)/128.0 AS DECIMAL(10, 2)) AS [Buffer size(MB)],
  1049. COUNT(*) AS [BufferCount], p.Rows AS [Row Count],
  1050. p.data_compression_desc AS [Compression Type]
  1051. FROM sys.allocation_units AS a WITH (NOLOCK)
  1052. INNER JOIN sys.dm_os_buffer_descriptors AS b WITH (NOLOCK)
  1053. ON a.allocation_unit_id = b.allocation_unit_id
  1054. INNER JOIN sys.partitions AS p WITH (NOLOCK)
  1055. ON a.container_id = p.hobt_id
  1056. WHERE b.database_id = CONVERT(int,DB_ID())
  1057. AND p.[object_id] > 100
  1058. GROUP BY p.[object_id], p.index_id, p.data_compression_desc, p.[Rows]
  1059. ORDER BY [BufferCount] DESC OPTION (RECOMPILE);
  1060.  
  1061. -- Tells you what tables and indexes are using the most memory in the buffer cache
  1062. -- It can help identify possible candidates for data compression
  1063.  
  1064.  
  1065. -- Get Table names, row counts, and compression status for clustered index or heap (Query 60) (Table Sizes)
  1066. SELECT OBJECT_NAME(object_id) AS [ObjectName],
  1067. SUM(Rows) AS [RowCount], data_compression_desc AS [CompressionType]
  1068. FROM sys.partitions WITH (NOLOCK)
  1069. WHERE index_id < 2 --ignore the partitions from the non-clustered index if any
  1070. AND OBJECT_NAME(object_id) NOT LIKE N'sys%'
  1071. AND OBJECT_NAME(object_id) NOT LIKE N'queue_%'
  1072. AND OBJECT_NAME(object_id) NOT LIKE N'filestream_tombstone%'
  1073. AND OBJECT_NAME(object_id) NOT LIKE N'fulltext%'
  1074. AND OBJECT_NAME(object_id) NOT LIKE N'ifts_comp_fragment%'
  1075. AND OBJECT_NAME(object_id) NOT LIKE N'filetable_updates%'
  1076. AND OBJECT_NAME(object_id) NOT LIKE N'xml_index_nodes%'
  1077. GROUP BY object_id, data_compression_desc
  1078. ORDER BY SUM(Rows) DESC OPTION (RECOMPILE);
  1079.  
  1080. -- Gives you an idea of table sizes, and possible data compression opportunities
  1081.  
  1082.  
  1083.  
  1084. -- Get some key table properties (Query 61) (Table Properties)
  1085. SELECT [name], create_date, lock_on_bulk_load, is_replicated, has_replication_filter,
  1086. is_tracked_by_cdc, lock_escalation_desc
  1087. FROM sys.tables WITH (NOLOCK)
  1088. ORDER BY [name] OPTION (RECOMPILE);
  1089.  
  1090. -- Gives you some good information about your tables
  1091.  
  1092.  
  1093. -- Detect blocking (run multiple times) (Query 62) (Detect Blocking)
  1094. SELECT t1.resource_type AS [lock type], DB_NAME(resource_database_id) AS [database],
  1095. t1.resource_associated_entity_id AS [blk object],t1.request_mode AS [lock req], --- lock requested
  1096. t1.request_session_id AS [waiter sid], t2.wait_duration_ms AS [wait time], -- spid of waiter
  1097. (SELECT [text] FROM sys.dm_exec_requests AS r WITH (NOLOCK) -- get sql for waiter
  1098. CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle])
  1099. WHERE r.session_id = t1.request_session_id) AS [waiter_batch],
  1100. (SELECT SUBSTRING(qt.[text],r.statement_start_offset/2,
  1101. (CASE WHEN r.statement_end_offset = -1
  1102. THEN LEN(CONVERT(nvarchar(max), qt.[text])) * 2
  1103. ELSE r.statement_end_offset END - r.statement_start_offset)/2)
  1104. FROM sys.dm_exec_requests AS r WITH (NOLOCK)
  1105. CROSS APPLY sys.dm_exec_sql_text(r.[sql_handle]) AS qt
  1106. WHERE r.session_id = t1.request_session_id) AS [waiter_stmt], -- statement blocked
  1107. t2.blocking_session_id AS [blocker sid], -- spid of blocker
  1108. (SELECT [text] FROM sys.sysprocesses AS p -- get sql for blocker
  1109. CROSS APPLY sys.dm_exec_sql_text(p.[sql_handle])
  1110. WHERE p.spid = t2.blocking_session_id) AS [blocker_stmt]
  1111. FROM sys.dm_tran_locks AS t1 WITH (NOLOCK)
  1112. INNER JOIN sys.dm_os_waiting_tasks AS t2 WITH (NOLOCK)
  1113. ON t1.lock_owner_address = t2.resource_address OPTION (RECOMPILE);
  1114.  
  1115. -- Helps troubleshoot blocking and deadlocking issues
  1116. -- The results will change from second to second on a busy system
  1117. -- You should run this query multiple times when you see signs of blocking
  1118.  
  1119.  
  1120. -- When were Statistics last updated on all indexes? (Query 63) (Statistics Update)
  1121. SELECT SCHEMA_NAME(o.Schema_ID) + N'.' + o.NAME AS [Object Name], o.type_desc AS [Object Type],
  1122. i.name AS [Index Name], STATS_DATE(i.[object_id], i.index_id) AS [Statistics Date],
  1123. s.auto_created, s.no_recompute, s.user_created, st.row_count, st.used_page_count
  1124. FROM sys.objects AS o WITH (NOLOCK)
  1125. INNER JOIN sys.indexes AS i WITH (NOLOCK)
  1126. ON o.[object_id] = i.[object_id]
  1127. INNER JOIN sys.stats AS s WITH (NOLOCK)
  1128. ON i.[object_id] = s.[object_id]
  1129. AND i.index_id = s.stats_id
  1130. INNER JOIN sys.dm_db_partition_stats AS st WITH (NOLOCK)
  1131. ON o.[object_id] = st.[object_id]
  1132. AND i.[index_id] = st.[index_id]
  1133. WHERE o.[type] IN ('U', 'V')
  1134. AND st.row_count > 0
  1135. ORDER BY STATS_DATE(i.[object_id], i.index_id) DESC OPTION (RECOMPILE);
  1136.  
  1137. -- Helps discover possible problems with out-of-date statistics
  1138. -- Also gives you an idea which indexes are the most active
  1139.  
  1140.  
  1141.  
  1142. -- Look at most frequently modified indexes and statistics (Query 64) (Volatile Indexes)
  1143. SELECT o.name AS [Object Name], o.[object_id], o.type_desc, s.name AS [Statistics Name],
  1144. s.stats_id, s.no_recompute, s.auto_created,
  1145. sp.modification_counter, sp.rows, sp.rows_sampled, sp.last_updated
  1146. FROM sys.objects AS o WITH (NOLOCK)
  1147. INNER JOIN sys.stats AS s WITH (NOLOCK)
  1148. ON s.object_id = o.object_id
  1149. CROSS APPLY sys.dm_db_stats_properties(s.object_id, s.stats_id) AS sp
  1150. WHERE o.type_desc NOT IN (N'SYSTEM_TABLE', N'INTERNAL_TABLE')
  1151. AND sp.modification_counter > 0
  1152. ORDER BY sp.modification_counter DESC, o.name OPTION (RECOMPILE);
  1153.  
  1154.  
  1155.  
  1156.  
  1157. -- Get fragmentation info for all indexes above a certain size in the current database (Query 65) (Index Fragmentation)
  1158. -- Note: This query could take some time on a very large database
  1159. SELECT DB_NAME(ps.database_id) AS [Database Name], OBJECT_NAME(ps.OBJECT_ID) AS [Object Name],
  1160. i.name AS [Index Name], ps.index_id, ps.index_type_desc, ps.avg_fragmentation_in_percent,
  1161. ps.fragment_count, ps.page_count, i.fill_factor, i.has_filter, i.filter_definition
  1162. FROM sys.dm_db_index_physical_stats(DB_ID(),NULL, NULL, NULL , N'LIMITED') AS ps
  1163. INNER JOIN sys.indexes AS i WITH (NOLOCK)
  1164. ON ps.[object_id] = i.[object_id]
  1165. AND ps.index_id = i.index_id
  1166. WHERE ps.database_id = DB_ID()
  1167. AND ps.page_count > 2500
  1168. ORDER BY ps.avg_fragmentation_in_percent DESC OPTION (RECOMPILE);
  1169.  
  1170. -- Helps determine whether you have framentation in your relational indexes
  1171. -- and how effective your index maintenance strategy is
  1172.  
  1173.  
  1174. --- Index Read/Write stats (all tables in current DB) ordered by Reads (Query 66) (Overall Index Usage - Reads)
  1175. SELECT OBJECT_NAME(s.[object_id]) AS [ObjectName], i.name AS [IndexName], i.index_id,
  1176. user_seeks + user_scans + user_lookups AS [Reads], s.user_updates AS [Writes],
  1177. i.type_desc AS [IndexType], i.fill_factor AS [FillFactor], i.has_filter, i.filter_definition,
  1178. s.last_user_scan, s.last_user_lookup, s.last_user_seek
  1179. FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
  1180. INNER JOIN sys.indexes AS i WITH (NOLOCK)
  1181. ON s.[object_id] = i.[object_id]
  1182. WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
  1183. AND i.index_id = s.index_id
  1184. AND s.database_id = DB_ID()
  1185. ORDER BY user_seeks + user_scans + user_lookups DESC OPTION (RECOMPILE); -- Order by reads
  1186.  
  1187.  
  1188. -- Show which indexes in the current database are most active for Reads
  1189.  
  1190.  
  1191. --- Index Read/Write stats (all tables in current DB) ordered by Writes (Query 67) (Overall Index Usage - Writes)
  1192. SELECT OBJECT_NAME(s.[object_id]) AS [ObjectName], i.name AS [IndexName], i.index_id,
  1193. s.user_updates AS [Writes], user_seeks + user_scans + user_lookups AS [Reads],
  1194. i.type_desc AS [IndexType], i.fill_factor AS [FillFactor], i.has_filter, i.filter_definition,
  1195. s.last_system_update, s.last_user_update
  1196. FROM sys.dm_db_index_usage_stats AS s WITH (NOLOCK)
  1197. INNER JOIN sys.indexes AS i WITH (NOLOCK)
  1198. ON s.[object_id] = i.[object_id]
  1199. WHERE OBJECTPROPERTY(s.[object_id],'IsUserTable') = 1
  1200. AND i.index_id = s.index_id
  1201. AND s.database_id = DB_ID()
  1202. ORDER BY s.user_updates DESC OPTION (RECOMPILE); -- Order by writes
  1203.  
  1204. -- Show which indexes in the current database are most active for Writes
  1205.  
  1206.  
  1207. -- Get lock waits for current database (Query 68) (Lock Waits)
  1208. SELECT o.name AS [table_name], i.name AS [index_name], ios.index_id, ios.partition_number,
  1209. SUM(ios.row_lock_wait_count) AS [total_row_lock_waits],
  1210. SUM(ios.row_lock_wait_in_ms) AS [total_row_lock_wait_in_ms],
  1211. SUM(ios.page_lock_wait_count) AS [total_page_lock_waits],
  1212. SUM(ios.page_lock_wait_in_ms) AS [total_page_lock_wait_in_ms],
  1213. SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) AS [total_lock_wait_in_ms]
  1214. FROM sys.dm_db_index_operational_stats(DB_ID(), NULL, NULL, NULL) AS ios
  1215. INNER JOIN sys.objects AS o WITH (NOLOCK)
  1216. ON ios.[object_id] = o.[object_id]
  1217. INNER JOIN sys.indexes AS i WITH (NOLOCK)
  1218. ON ios.[object_id] = i.[object_id]
  1219. AND ios.index_id = i.index_id
  1220. WHERE o.[object_id] > 100
  1221. GROUP BY o.name, i.name, ios.index_id, ios.partition_number
  1222. HAVING SUM(ios.page_lock_wait_in_ms)+ SUM(row_lock_wait_in_ms) > 0
  1223. ORDER BY total_lock_wait_in_ms DESC OPTION (RECOMPILE);
  1224.  
  1225. -- This query is helpful for troubleshooting blocking and deadlocking issues
  1226.  
  1227.  
  1228. -- Look at recent Full backups for the current database (Query 69) (Recent Full Backups)
  1229. SELECT TOP (30) bs.machine_name, bs.server_name, bs.database_name AS [Database Name], bs.recovery_model,
  1230. CONVERT (BIGINT, bs.backup_size / 1048576 ) AS [Uncompressed Backup Size (MB)],
  1231. CONVERT (BIGINT, bs.compressed_backup_size / 1048576 ) AS [Compressed Backup Size (MB)],
  1232. CONVERT (NUMERIC (20,2), (CONVERT (FLOAT, bs.backup_size) /
  1233. CONVERT (FLOAT, bs.compressed_backup_size))) AS [Compression Ratio],
  1234. DATEDIFF (SECOND, bs.backup_start_date, bs.backup_finish_date) AS [Backup Elapsed Time (sec)],
  1235. bs.backup_finish_date AS [Backup Finish Date]
  1236. FROM msdb.dbo.backupset AS bs WITH (NOLOCK)
  1237. WHERE DATEDIFF (SECOND, bs.backup_start_date, bs.backup_finish_date) > 0
  1238. AND bs.backup_size > 0
  1239. AND bs.type = 'D' -- Change to L if you want Log backups
  1240. AND database_name = DB_NAME(DB_ID())
  1241. ORDER BY bs.backup_finish_date DESC OPTION (RECOMPILE);
  1242.  
  1243. -- Are your backup sizes and times changing over time?
Advertisement
Add Comment
Please, Sign In to add comment