/*============================================================================
  File:     2a_Baseline_WaitStats_Setup.sql

  Summary:  This script creates the table to hold
			Wait Stats data, and the statement to use
			in a scheduled job to snapshot Wait Stats 
			regularly.


  Date:     October 2014

  SQL Server Version: 2005/2008/2008R2/2012/2014
------------------------------------------------------------------------------
  Written by Erin Stellato, SQLskills.com

  (c) 2014, SQLskills.com. All rights reserved.

  For more scripts and sample code, check out 
    http://www.SQLskills.com

  You may alter this code for your own *non-commercial* purposes. You may
  republish altered code as long as you include this copyright and give due
  credit, but you must obtain prior permission before blogging this code.
  
  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF 
  ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED 
  TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
  PARTICULAR PURPOSE.
============================================================================*/


USE [BaselineData];
GO

IF NOT EXISTS ( SELECT  *
                FROM    [sys].[tables]
                WHERE   [name] = N'WaitStats'
                        AND [type] = N'U' ) 
	CREATE TABLE [dbo].[SQLskills_WaitStats](
		[RowNum] [bigint] IDENTITY(1,1) NOT NULL,
		[CaptureDate] [datetime] NULL,
		[WaitType] [nvarchar](120) NULL,
		[Wait_S] [decimal](14, 2) NULL,
		[Resource_S] [decimal](14, 2) NULL,
		[Signal_S] [decimal](14, 2) NULL,
		[WaitCount] [bigint] NULL,
		[Percentage] [decimal](4, 2) NULL,
		[AvgWait_S] [decimal](14, 4) NULL,
		[AvgRes_S] [decimal](14, 4) NULL,
		[AvgSig_S] [decimal](14, 4) NULL
		);
	GO


CREATE CLUSTERED INDEX [CI_SQLskills_WaitStats] ON [dbo].[SQLskills_WaitStats] ([CaptureDate],[RowNum]);
GO


/*
	Query to use in scheduled job
*/

INSERT  INTO dbo.SQLskills_WaitStats
        ( [WaitType]
         )
VALUES  ( 'Wait Statistics for ' + CAST(GETDATE() AS NVARCHAR(19))
         );

INSERT  INTO dbo.SQLskills_WaitStats
        ( [CaptureDate] ,
          [WaitType] ,
          [Wait_S] ,
          [Resource_S] ,
          [Signal_S] ,
          [WaitCount] ,
          [Percentage] ,
          [AvgWait_S] ,
          [AvgRes_S] ,
          [AvgSig_S] 
         )
        EXEC
            ( '
      WITH [Waits] AS
         (SELECT
            [wait_type],
            [wait_time_ms] / 1000.0 AS [WaitS],
            ([wait_time_ms] - [signal_wait_time_ms]) / 1000.0
                                         AS [ResourceS],
            [signal_wait_time_ms] / 1000.0 AS [SignalS],
            [waiting_tasks_count] AS [WaitCount],
            100.0 * [wait_time_ms] / SUM ([wait_time_ms]) OVER()
                                         AS [Percentage],
            ROW_NUMBER() OVER(ORDER BY [wait_time_ms] DESC) AS [RowNum]
         FROM sys.dm_os_wait_stats
         WHERE [wait_type] NOT IN (
        N''BROKER_EVENTHANDLER'', N''BROKER_RECEIVE_WAITFOR'', N''BROKER_TASK_STOP'',
		N''BROKER_TO_FLUSH'', N''BROKER_TRANSMITTER'', N''CHECKPOINT_QUEUE'',
        N''CHKPT'', N''CLR_AUTO_EVENT'', N''CLR_MANUAL_EVENT'', N''CLR_SEMAPHORE'',
        N''DBMIRROR_DBM_EVENT'', N''DBMIRROR_EVENTS_QUEUE'', N''DBMIRROR_WORKER_QUEUE'',
		N''DBMIRRORING_CMD'', N''DIRTY_PAGE_POLL'', N''DISPATCHER_QUEUE_SEMAPHORE'',
        N''EXECSYNC'', N''FSAGENT'', N''FT_IFTS_SCHEDULER_IDLE_WAIT'', N''FT_IFTSHC_MUTEX'',
        N''HADR_CLUSAPI_CALL'', N''HADR_FILESTREAM_IOMGR_IOCOMPLETION'', N''HADR_LOGCAPTURE_WAIT'', 
		N''HADR_NOTIFICATION_DEQUEUE'', N''HADR_TIMER_TASK'', N''HADR_WORK_QUEUE'',
        N''KSOURCE_WAKEUP'', N''LAZYWRITER_SLEEP'', N''LOGMGR_QUEUE'', N''ONDEMAND_TASK_QUEUE'',
        N''PWAIT_ALL_COMPONENTS_INITIALIZED'', N''QDS_PERSIST_TASK_MAIN_LOOP_SLEEP'',
        N''QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP'', N''REQUEST_FOR_DEADLOCK_SEARCH'',
		N''RESOURCE_QUEUE'', N''SERVER_IDLE_CHECK'', N''SLEEP_BPOOL_FLUSH'', N''SLEEP_DBSTARTUP'',
		N''SLEEP_DCOMSTARTUP'', N''SLEEP_MASTERDBREADY'', N''SLEEP_MASTERMDREADY'',
        N''SLEEP_MASTERUPGRADED'', N''SLEEP_MSDBSTARTUP'', N''SLEEP_SYSTEMTASK'', N''SLEEP_TASK'',
        N''SLEEP_TEMPDBSTARTUP'', N''SNI_HTTP_ACCEPT'', N''SP_SERVER_DIAGNOSTICS_SLEEP'',
		N''SQLTRACE_BUFFER_FLUSH'', N''SQLTRACE_INCREMENTAL_FLUSH_SLEEP'', N''SQLTRACE_WAIT_ENTRIES'',
		N''WAIT_FOR_RESULTS'', N''WAITFOR'', N''WAITFOR_TASKSHUTDOWN'', N''WAIT_XTP_HOST_WAIT'',
		N''WAIT_XTP_OFFLINE_CKPT_NEW_LOG'', N''WAIT_XTP_CKPT_CLOSE'', N''XE_DISPATCHER_JOIN'',
        N''XE_DISPATCHER_WAIT'', N''XE_TIMER_EVENT'')
         )
      SELECT
         GETDATE(),
         [W1].[wait_type] AS [WaitType], 
         CAST ([W1].[WaitS] AS DECIMAL(14, 2)) AS [Wait_S],
         CAST ([W1].[ResourceS] AS DECIMAL(14, 2)) AS [Resource_S],
         CAST ([W1].[SignalS] AS DECIMAL(14, 2)) AS [Signal_S],
         [W1].[WaitCount] AS [WaitCount],
         CAST ([W1].[Percentage] AS DECIMAL(4, 2)) AS [Percentage],
         CAST (([W1].[WaitS] / [W1].[WaitCount]) AS DECIMAL (14, 4))
                                                       AS [AvgWait_S],
         CAST (([W1].[ResourceS] / [W1].[WaitCount]) AS DECIMAL (14, 4))
                                                        AS [AvgRes_S],
         CAST (([W1].[SignalS] / [W1].[WaitCount]) AS DECIMAL (14, 4))
                                                      AS [AvgSig_S]
      FROM [Waits] AS [W1]
      INNER JOIN [Waits] AS [W2]
         ON [W2].[RowNum] <= [W1].[RowNum]
      GROUP BY [W1].[RowNum], [W1].[wait_type], [W1].[WaitS], 
         [W1].[ResourceS], [W1].[SignalS], [W1].[WaitCount],
          [W1].[Percentage]
      HAVING SUM ([W2].[Percentage]) - [W1].[Percentage] < 95;'
            );
END
