SlideShare a Scribd company logo
Contact: EliasBlake
prosperdatasystems@gmail.com
www.prosperidata.com
Using SQL Stored Procedures to automate performance checks
Code Sample from SQL Server Management Studio to demonstrate collecting wait statistics.
use YourDatabaseHere;
DECLARE @server nvarchar(100);
DECLARE @db nvarchar(100);
DECLARE @command nvarchar(4000);
DECLARE DBLINKS CURSOR FOR select SERVER,db from YourDatabaseHere.dbo.TableofLinkedServers
--Open the cursor.
OPEN DBLINKS;
-- Loop through the partitions.SQL_Latin1_General_CP1_CI_AS
WHILE (1=1)
BEGIN;
FETCH NEXT
FROM DBLINKS
INTO @server,@db;
IF @@FETCH_STATUS < 0 BREAK;
SET @command = N'INSERT INTO YourDatabaseHere.dbo.waits
(Server,session_id,task_state,wait_duration_ms,max_wait_time_ms,wait_type,waiting_tasks_count,stamp
)
select CASE when a3.session_id != null THEN'''+ @server + ''' END
server,a3.session_id,a3.task_state,a2.wait_duration_ms,a1.max_wait_time_ms,a1.wait_type,a1.waiting_
tasks_count,CASE when a3.session_id != null THEN getdate() ELSE getdate() END as [stamp]
from ' + '['+@server+ ']'+ '.['+@db+ N'].sys.dm_os_waiting_tasks a2 inner join sys.dm_os_tasks a3
on a2.session_id = a3.session_id
inner join sys.dm_os_wait_stats a1
on a2.wait_type = a1.wait_type collate SQL_Latin1_General_CP1_CI_AS
where a2.wait_type in (''CXPACKET'',''ASYNC_IO_COMPLETION'',''ASYNC_NETWORK_IO'')
OR a2.wait_type LIKE ''LCK%'' OR a2.wait_type like ''%LATCH%''
order by a2.wait_duration_ms desc,a2.session_id desc';
EXEC sp_executesql @command;
PRINT N'Executed: ' + @command;
END
CLOSE DBLINKS;
DEALLOCATE DBLINKS;
Thiscode sample assumesanenvironmentwithmultipleSQLServerInstancesbeyondthe 30 that can be monitored
usingthe UCP service (UtilityControl Point) introduced inSQLServer2008 R2 enterprise.Alsohave abackgroundin
Oracle thisis somewhatequivalenttotakingsnapshotsinAWR. AswithUCP there isa requirementfora“super”service
account withsysadmaccesson monitoredinstances butalsolinkedservers andservergroupsregisteredin management
studio. Thiswill notworkinenvironmentswherethe rpcand rpcoutare restricted. Itispossible to install otherinstances
to run UCP on a single serverbut UCPonlyprovidesawindow intothe hardware bydisplayinggrowthof datafiles, CPU
and memory.If more detail isneededforrootcause analysis inside the database andsp_whodoesn’tshedlight, the
waitstats fromthe example canprovide awindow into the processesand sessionID/usersthatcreate unsavory wait
types. Althoughthe SQLServerextendedeventsandProfilerService cancreate histories thisscriptcanbe a goodway to
target whatserversneed attention inacentral way withoutrandomlyrunningtracesandextendedsessionevents. Then
hopefullythe DBA can avoidthe performance impacts of collectingperformance metricswhere it’snotneeded. If using
SQL Server
Using SSMS to construct a wait loop or other looping script
The firststepis to putthe scriptintoa storedprocedure as shownina database;as withadventure worksinthe sample.
A SQL AgentJob(notmy preference)withappropriate“exec”permissions couldbe usedinsteadof astoredprocedure.
Althoughthe code can be ploppedintoSQLAgent thatadds a layerof additional permissionheadaches.Creatingthe
storedprocedure alsoallows automationusingsqlcmdfilesand scheduledtasksif youcan’tuse SQL Agent.(Another
article).
Set links and a dedicated domain user
Second addthe superuseraccount to all instancesthatwill be linked.Servergroupswill allow the additionof the super
account to SQL Serversandverificationof permissionsasshowninthe examples.
Note above the querywindowisopenonSQLGRP.
Belowthe helploginsextendedprocshowsthe new service accountwasadded.
The linksto remote databasesare authenticatedasthe “super”useror anothersysadmaccount as shownor usingthe
“current securitycontext”.
The last linkpermissionbelow “Be made usingthissecuritycontext”wouldbe usedtoauthenticate againstexternal
database accountsfor Oracle,MySQL,etc.
One the firstdatabase linkiscompletedandsaveditcanbe scriptedtoa querywindow (rightclick)andusingfindand
replace forthe each newSQL ServerInstance couldspeedupthe process. Alsousingawhile loopto pull servernames
fromthe a “MyLinksTable”asshownin the nextstep couldwork to “auto create”links.Thisstepis what allowsthe
creationof a single central table versestablesoneachinstance. Iwill lookmore atlinksandODBC connectorsforOracle
queries andPL/SQLanothertime.
Using Server Groups or Central Managed Server
Thirdusingyour registeredservergrouptocreate a querywithselect@@SERVERNAME + name from sys.databases,you
can populate atable or a tempdbtable tocreate a listof sql instances anddatabases.
If you don’twantlinksyoucan create a “waits”table ineach instance andqueryagainstthe servergroup. Alsoyoucould
add sp_configure commandto enable anddisable linkaccessatthe instance level.
Reference Table for links and database connect strings
The MyLinksTable will supplythe variables inthe storedprocto run the waitstats scriptagainstthe linkeddatabases
and insertdataintothe inMy in WaitsTable atthe “central” server. Before creatingthe storedprocbelowitisbestto
take the @command scriptSQL and attempta testinsertto the central table.Thishelpsavoidastray bracketor quote
and the testrows can thenbe truncatedif needed.
The excerptabove wouldbe tweakedbasedonsecuritycontrolsandpolicymanagementorfacetsthatmay restrict
remote functionsorsysadmaccess.It ispossible thateachinstance mayneeditsownwaitstable whichcouldbe
queriedlater.
SQL Agent and scheduling
Lastlyschedule SQLAgent,taskschedulerorpowershelltorun your storedproc. Manually runningthe storedprocusing
@spYourProcName inthe scriptwindowisagood final test. The resultswill show the following:
Thisprocess takessome doing initially butsetsthe stage forcollectingotherimportantmetrics withstoredprocstopull
fromDMV’s for databases like db_index_XXX_xxxx,db_missing_index_xxxx.Withsome modificationstoremove the
@db database variable serverlevelOSperformance metrics canbe collected fromdm_osviewsand
dm_io_virtual_file_stats views. Thistechniquecanbe valuable tokeepwait,memory,schedulerorIOtrendsovertime.
It has alsobeeninvaluable inindex reorg/rebuild,ADchecks,diskmovesandmore. Alsoif SQLServerstandard,express
or olderversionsare used, standardizingmonitoringwithstoredprocedurescancompensate forlackof enterprise
featuressuchas Resource Governor,BackupCompressionsandUCPand SQL Agent(use sqlcmd)

More Related Content

What's hot

Time-Based Blind SQL Injection Using Heavy Queries
Time-Based Blind SQL Injection Using Heavy QueriesTime-Based Blind SQL Injection Using Heavy Queries
Time-Based Blind SQL Injection Using Heavy Queries
Chema Alonso
 
PostgreSQL High_Performance_Cheatsheet
PostgreSQL High_Performance_CheatsheetPostgreSQL High_Performance_Cheatsheet
PostgreSQL High_Performance_Cheatsheet
Lucian Oprea
 
1 extreme performance - part i
1   extreme performance - part i1   extreme performance - part i
1 extreme performance - part isqlserver.co.il
 
Get database properties using power shell in sql server 2008 techrepublic
Get database properties using power shell in sql server 2008   techrepublicGet database properties using power shell in sql server 2008   techrepublic
Get database properties using power shell in sql server 2008 techrepublicKaing Menglieng
 
Enable archivelod mode in oracle rac12cR1 with asm location
Enable archivelod mode  in oracle rac12cR1 with asm locationEnable archivelod mode  in oracle rac12cR1 with asm location
Enable archivelod mode in oracle rac12cR1 with asm location
Debasish Nayak
 
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academy
thewebsacademy
 
PHP tips by a MYSQL DBA
PHP tips by a MYSQL DBAPHP tips by a MYSQL DBA
PHP tips by a MYSQL DBA
Amit Kumar Singh
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
Vikash Sharma
 
Managing Oracle Streams Using Enterprise Manager Grid Control
Managing Oracle Streams Using Enterprise Manager Grid ControlManaging Oracle Streams Using Enterprise Manager Grid Control
Managing Oracle Streams Using Enterprise Manager Grid Control
scottb411
 
Using triggers in my sql database
Using triggers in my sql databaseUsing triggers in my sql database
Using triggers in my sql database
Kimera Richard
 
Sql Server 2016 Always Encrypted
Sql Server 2016 Always EncryptedSql Server 2016 Always Encrypted
Sql Server 2016 Always Encrypted
Duncan Greaves PhD
 
Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...
Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...
Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...djkucera
 
Cassandra v3.0 at Rakuten meet-up on 12/2/2015
Cassandra v3.0 at Rakuten meet-up on 12/2/2015Cassandra v3.0 at Rakuten meet-up on 12/2/2015
Cassandra v3.0 at Rakuten meet-up on 12/2/2015
datastaxjp
 
Sql saturday oc 2019
Sql saturday oc 2019Sql saturday oc 2019
Sql saturday oc 2019
SitotpalSarkar
 
Intro to tsql unit 12
Intro to tsql   unit 12Intro to tsql   unit 12
Intro to tsql unit 12Syed Asrarali
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainers
Naresha K
 
Time-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy QueriesTime-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy Queries
Chema Alonso
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
Zianed Hou
 

What's hot (18)

Time-Based Blind SQL Injection Using Heavy Queries
Time-Based Blind SQL Injection Using Heavy QueriesTime-Based Blind SQL Injection Using Heavy Queries
Time-Based Blind SQL Injection Using Heavy Queries
 
PostgreSQL High_Performance_Cheatsheet
PostgreSQL High_Performance_CheatsheetPostgreSQL High_Performance_Cheatsheet
PostgreSQL High_Performance_Cheatsheet
 
1 extreme performance - part i
1   extreme performance - part i1   extreme performance - part i
1 extreme performance - part i
 
Get database properties using power shell in sql server 2008 techrepublic
Get database properties using power shell in sql server 2008   techrepublicGet database properties using power shell in sql server 2008   techrepublic
Get database properties using power shell in sql server 2008 techrepublic
 
Enable archivelod mode in oracle rac12cR1 with asm location
Enable archivelod mode  in oracle rac12cR1 with asm locationEnable archivelod mode  in oracle rac12cR1 with asm location
Enable archivelod mode in oracle rac12cR1 with asm location
 
MySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs AcademyMySql Triggers Tutorial - The Webs Academy
MySql Triggers Tutorial - The Webs Academy
 
PHP tips by a MYSQL DBA
PHP tips by a MYSQL DBAPHP tips by a MYSQL DBA
PHP tips by a MYSQL DBA
 
Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
 
Managing Oracle Streams Using Enterprise Manager Grid Control
Managing Oracle Streams Using Enterprise Manager Grid ControlManaging Oracle Streams Using Enterprise Manager Grid Control
Managing Oracle Streams Using Enterprise Manager Grid Control
 
Using triggers in my sql database
Using triggers in my sql databaseUsing triggers in my sql database
Using triggers in my sql database
 
Sql Server 2016 Always Encrypted
Sql Server 2016 Always EncryptedSql Server 2016 Always Encrypted
Sql Server 2016 Always Encrypted
 
Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...
Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...
Collaborate 2011– Leveraging and Enriching the Capabilities of Oracle Databas...
 
Cassandra v3.0 at Rakuten meet-up on 12/2/2015
Cassandra v3.0 at Rakuten meet-up on 12/2/2015Cassandra v3.0 at Rakuten meet-up on 12/2/2015
Cassandra v3.0 at Rakuten meet-up on 12/2/2015
 
Sql saturday oc 2019
Sql saturday oc 2019Sql saturday oc 2019
Sql saturday oc 2019
 
Intro to tsql unit 12
Intro to tsql   unit 12Intro to tsql   unit 12
Intro to tsql unit 12
 
Take Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainersTake Control of your Integration Testing with TestContainers
Take Control of your Integration Testing with TestContainers
 
Time-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy QueriesTime-Based Blind SQL Injection using Heavy Queries
Time-Based Blind SQL Injection using Heavy Queries
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 

Similar to SSMS-waitstats

Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Ontico
 
SafePeak - How to configure SQL Server agent in a safepeak deployment
SafePeak - How to configure SQL Server agent in a safepeak deploymentSafePeak - How to configure SQL Server agent in a safepeak deployment
SafePeak - How to configure SQL Server agent in a safepeak deployment
Vladi Vexler
 
Sherlock holmes for dba’s
Sherlock holmes for dba’sSherlock holmes for dba’s
Sherlock holmes for dba’s
Kellyn Pot'Vin-Gorman
 
Useful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesUseful PL/SQL Supplied Packages
Useful PL/SQL Supplied Packages
Maria Colgan
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
Alex Zaballa
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
Alex Zaballa
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
Alex Zaballa
 
Azure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best PracticesAzure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best Practices
Jose Manuel Jurado Diaz
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Netwebhostingguy
 
Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersScaling asp.net websites to millions of users
Scaling asp.net websites to millions of users
oazabir
 
common_schema, DBA's framework for MySQL
common_schema, DBA's framework for MySQLcommon_schema, DBA's framework for MySQL
common_schema, DBA's framework for MySQL
Shlomi Noach
 
TROOPERS 20 - SQL Server Hacking Tips for Active Directory Environments
TROOPERS 20 - SQL Server Hacking Tips for Active Directory EnvironmentsTROOPERS 20 - SQL Server Hacking Tips for Active Directory Environments
TROOPERS 20 - SQL Server Hacking Tips for Active Directory Environments
Scott Sutherland
 
Database Mirror for the exceptional DBA – David Izahk
Database Mirror for the exceptional DBA – David IzahkDatabase Mirror for the exceptional DBA – David Izahk
Database Mirror for the exceptional DBA – David Izahksqlserver.co.il
 
SQLite in Adobe AIR
SQLite in Adobe AIRSQLite in Adobe AIR
SQLite in Adobe AIRPeter Elst
 
ProxySQL and the Tricks Up Its Sleeve - Percona Live 2022.pdf
ProxySQL and the Tricks Up Its Sleeve - Percona Live 2022.pdfProxySQL and the Tricks Up Its Sleeve - Percona Live 2022.pdf
ProxySQL and the Tricks Up Its Sleeve - Percona Live 2022.pdf
Jesmar Cannao'
 
Microsoft SQL Azure - Developing And Deploying With SQL Azure Whitepaper
Microsoft SQL Azure - Developing And Deploying With SQL Azure WhitepaperMicrosoft SQL Azure - Developing And Deploying With SQL Azure Whitepaper
Microsoft SQL Azure - Developing And Deploying With SQL Azure Whitepaper
Microsoft Private Cloud
 
Database versioning with liquibase
Database versioning with liquibaseDatabase versioning with liquibase
Database versioning with liquibase
Return on Intelligence
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
Jürgen Ambrosi
 

Similar to SSMS-waitstats (20)

Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
 
SafePeak - How to configure SQL Server agent in a safepeak deployment
SafePeak - How to configure SQL Server agent in a safepeak deploymentSafePeak - How to configure SQL Server agent in a safepeak deployment
SafePeak - How to configure SQL Server agent in a safepeak deployment
 
Sherlock holmes for dba’s
Sherlock holmes for dba’sSherlock holmes for dba’s
Sherlock holmes for dba’s
 
Useful PL/SQL Supplied Packages
Useful PL/SQL Supplied PackagesUseful PL/SQL Supplied Packages
Useful PL/SQL Supplied Packages
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should KnowDBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
DBA Brasil 1.0 - DBA Commands and Concepts That Every Developer Should Know
 
SQL Injection
SQL InjectionSQL Injection
SQL Injection
 
Azure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best PracticesAzure SQL Database - Connectivity Best Practices
Azure SQL Database - Connectivity Best Practices
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
 
Scaling asp.net websites to millions of users
Scaling asp.net websites to millions of usersScaling asp.net websites to millions of users
Scaling asp.net websites to millions of users
 
common_schema, DBA's framework for MySQL
common_schema, DBA's framework for MySQLcommon_schema, DBA's framework for MySQL
common_schema, DBA's framework for MySQL
 
TROOPERS 20 - SQL Server Hacking Tips for Active Directory Environments
TROOPERS 20 - SQL Server Hacking Tips for Active Directory EnvironmentsTROOPERS 20 - SQL Server Hacking Tips for Active Directory Environments
TROOPERS 20 - SQL Server Hacking Tips for Active Directory Environments
 
Database Mirror for the exceptional DBA – David Izahk
Database Mirror for the exceptional DBA – David IzahkDatabase Mirror for the exceptional DBA – David Izahk
Database Mirror for the exceptional DBA – David Izahk
 
SQLite in Adobe AIR
SQLite in Adobe AIRSQLite in Adobe AIR
SQLite in Adobe AIR
 
ProxySQL and the Tricks Up Its Sleeve - Percona Live 2022.pdf
ProxySQL and the Tricks Up Its Sleeve - Percona Live 2022.pdfProxySQL and the Tricks Up Its Sleeve - Percona Live 2022.pdf
ProxySQL and the Tricks Up Its Sleeve - Percona Live 2022.pdf
 
Microsoft SQL Azure - Developing And Deploying With SQL Azure Whitepaper
Microsoft SQL Azure - Developing And Deploying With SQL Azure WhitepaperMicrosoft SQL Azure - Developing And Deploying With SQL Azure Whitepaper
Microsoft SQL Azure - Developing And Deploying With SQL Azure Whitepaper
 
Mysql
MysqlMysql
Mysql
 
Database versioning with liquibase
Database versioning with liquibaseDatabase versioning with liquibase
Database versioning with liquibase
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
 

SSMS-waitstats

  • 1. Contact: EliasBlake prosperdatasystems@gmail.com www.prosperidata.com Using SQL Stored Procedures to automate performance checks Code Sample from SQL Server Management Studio to demonstrate collecting wait statistics. use YourDatabaseHere; DECLARE @server nvarchar(100); DECLARE @db nvarchar(100); DECLARE @command nvarchar(4000); DECLARE DBLINKS CURSOR FOR select SERVER,db from YourDatabaseHere.dbo.TableofLinkedServers --Open the cursor. OPEN DBLINKS; -- Loop through the partitions.SQL_Latin1_General_CP1_CI_AS WHILE (1=1) BEGIN; FETCH NEXT FROM DBLINKS INTO @server,@db; IF @@FETCH_STATUS < 0 BREAK; SET @command = N'INSERT INTO YourDatabaseHere.dbo.waits (Server,session_id,task_state,wait_duration_ms,max_wait_time_ms,wait_type,waiting_tasks_count,stamp ) select CASE when a3.session_id != null THEN'''+ @server + ''' END server,a3.session_id,a3.task_state,a2.wait_duration_ms,a1.max_wait_time_ms,a1.wait_type,a1.waiting_ tasks_count,CASE when a3.session_id != null THEN getdate() ELSE getdate() END as [stamp] from ' + '['+@server+ ']'+ '.['+@db+ N'].sys.dm_os_waiting_tasks a2 inner join sys.dm_os_tasks a3 on a2.session_id = a3.session_id inner join sys.dm_os_wait_stats a1 on a2.wait_type = a1.wait_type collate SQL_Latin1_General_CP1_CI_AS where a2.wait_type in (''CXPACKET'',''ASYNC_IO_COMPLETION'',''ASYNC_NETWORK_IO'') OR a2.wait_type LIKE ''LCK%'' OR a2.wait_type like ''%LATCH%'' order by a2.wait_duration_ms desc,a2.session_id desc'; EXEC sp_executesql @command; PRINT N'Executed: ' + @command; END CLOSE DBLINKS; DEALLOCATE DBLINKS; Thiscode sample assumesanenvironmentwithmultipleSQLServerInstancesbeyondthe 30 that can be monitored usingthe UCP service (UtilityControl Point) introduced inSQLServer2008 R2 enterprise.Alsohave abackgroundin Oracle thisis somewhatequivalenttotakingsnapshotsinAWR. AswithUCP there isa requirementfora“super”service account withsysadmaccesson monitoredinstances butalsolinkedservers andservergroupsregisteredin management studio. Thiswill notworkinenvironmentswherethe rpcand rpcoutare restricted. Itispossible to install otherinstances to run UCP on a single serverbut UCPonlyprovidesawindow intothe hardware bydisplayinggrowthof datafiles, CPU and memory.If more detail isneededforrootcause analysis inside the database andsp_whodoesn’tshedlight, the waitstats fromthe example canprovide awindow into the processesand sessionID/usersthatcreate unsavory wait types. Althoughthe SQLServerextendedeventsandProfilerService cancreate histories thisscriptcanbe a goodway to target whatserversneed attention inacentral way withoutrandomlyrunningtracesandextendedsessionevents. Then hopefullythe DBA can avoidthe performance impacts of collectingperformance metricswhere it’snotneeded. If using SQL Server
  • 2. Using SSMS to construct a wait loop or other looping script The firststepis to putthe scriptintoa storedprocedure as shownina database;as withadventure worksinthe sample. A SQL AgentJob(notmy preference)withappropriate“exec”permissions couldbe usedinsteadof astoredprocedure. Althoughthe code can be ploppedintoSQLAgent thatadds a layerof additional permissionheadaches.Creatingthe storedprocedure alsoallows automationusingsqlcmdfilesand scheduledtasksif youcan’tuse SQL Agent.(Another article). Set links and a dedicated domain user Second addthe superuseraccount to all instancesthatwill be linked.Servergroupswill allow the additionof the super account to SQL Serversandverificationof permissionsasshowninthe examples. Note above the querywindowisopenonSQLGRP.
  • 3. Belowthe helploginsextendedprocshowsthe new service accountwasadded. The linksto remote databasesare authenticatedasthe “super”useror anothersysadmaccount as shownor usingthe “current securitycontext”. The last linkpermissionbelow “Be made usingthissecuritycontext”wouldbe usedtoauthenticate againstexternal database accountsfor Oracle,MySQL,etc. One the firstdatabase linkiscompletedandsaveditcanbe scriptedtoa querywindow (rightclick)andusingfindand replace forthe each newSQL ServerInstance couldspeedupthe process. Alsousingawhile loopto pull servernames fromthe a “MyLinksTable”asshownin the nextstep couldwork to “auto create”links.Thisstepis what allowsthe creationof a single central table versestablesoneachinstance. Iwill lookmore atlinksandODBC connectorsforOracle queries andPL/SQLanothertime.
  • 4. Using Server Groups or Central Managed Server Thirdusingyour registeredservergrouptocreate a querywithselect@@SERVERNAME + name from sys.databases,you can populate atable or a tempdbtable tocreate a listof sql instances anddatabases. If you don’twantlinksyoucan create a “waits”table ineach instance andqueryagainstthe servergroup. Alsoyoucould add sp_configure commandto enable anddisable linkaccessatthe instance level.
  • 5. Reference Table for links and database connect strings The MyLinksTable will supplythe variables inthe storedprocto run the waitstats scriptagainstthe linkeddatabases and insertdataintothe inMy in WaitsTable atthe “central” server. Before creatingthe storedprocbelowitisbestto take the @command scriptSQL and attempta testinsertto the central table.Thishelpsavoidastray bracketor quote and the testrows can thenbe truncatedif needed. The excerptabove wouldbe tweakedbasedonsecuritycontrolsandpolicymanagementorfacetsthatmay restrict remote functionsorsysadmaccess.It ispossible thateachinstance mayneeditsownwaitstable whichcouldbe queriedlater.
  • 6. SQL Agent and scheduling Lastlyschedule SQLAgent,taskschedulerorpowershelltorun your storedproc. Manually runningthe storedprocusing @spYourProcName inthe scriptwindowisagood final test. The resultswill show the following: Thisprocess takessome doing initially butsetsthe stage forcollectingotherimportantmetrics withstoredprocstopull fromDMV’s for databases like db_index_XXX_xxxx,db_missing_index_xxxx.Withsome modificationstoremove the @db database variable serverlevelOSperformance metrics canbe collected fromdm_osviewsand dm_io_virtual_file_stats views. Thistechniquecanbe valuable tokeepwait,memory,schedulerorIOtrendsovertime. It has alsobeeninvaluable inindex reorg/rebuild,ADchecks,diskmovesandmore. Alsoif SQLServerstandard,express or olderversionsare used, standardizingmonitoringwithstoredprocedurescancompensate forlackof enterprise featuressuchas Resource Governor,BackupCompressionsandUCPand SQL Agent(use sqlcmd)