Add files via upload
c227e925
KristineVog
authored and
GitHub
committed
13 changed files
sqlmi
030_MaintenanceSolution.sql
/Deployment/030_MaintenanceSolution.sql+9104
/Deployment/030_MaintenanceSolution.sql
Add comment 1 Plus  /*
Add comment 2 Plus  
Add comment 3 Plus  SQL Server Maintenance Solution - SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, SQL Server 2019, and SQL Server 2022
Add comment 4 Plus  
Add comment 5 Plus  Backup: https://ola.hallengren.com/sql-server-backup.html
Add comment 6 Plus  Integrity Check: https://ola.hallengren.com/sql-server-integrity-check.html
Add comment 7 Plus  Index and Statistics Maintenance: https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html
Add comment 8 Plus  
Add comment 9 Plus  License: https://ola.hallengren.com/license.html
Add comment 10 Plus  
Add comment 11 Plus  GitHub: https://github.com/olahallengren/sql-server-maintenance-solution
Add comment 12 Plus  
Add comment 13 Plus  Version: 2022-12-03 17:23:44
Add comment 14 Plus  
Add comment 15 Plus  You can contact me by e-mail at ola@hallengren.com.
Add comment 16 Plus  
Add comment 17 Plus  Ola Hallengren
Add comment 18 Plus  https://ola.hallengren.com
Add comment 19 Plus  
Add comment 20 Plus  */
Add comment 21 Plus  
Add comment 22 Plus  USE [IF_SysMan] -- Specify the database in which the objects will be created.
Add comment 23 Plus  
Add comment 24 Plus  SET NOCOUNT ON
Add comment 25 Plus  
Add comment 26 Plus  DECLARE @CreateJobs nvarchar(max) = 'Y' -- Specify whether jobs should be created.
Add comment 27 Plus  DECLARE @BackupDirectory nvarchar(max) = NULL -- Specify the backup root directory. If no directory is specified, the default backup directory is used.
Add comment 28 Plus  DECLARE @CleanupTime int = NULL -- Time in hours, after which backup files are deleted. If no time is specified, then no backup files are deleted.
Add comment 29 Plus  DECLARE @OutputFileDirectory nvarchar(max) = NULL -- Specify the output file directory. If no directory is specified, then the SQL Server error log directory is used.
Add comment 30 Plus  DECLARE @LogToTable nvarchar(max) = 'Y' -- Log commands to a table.
Add comment 31 Plus  
Add comment 32 Plus  DECLARE @ErrorMessage nvarchar(max)
Add comment 33 Plus  
Add comment 34 Plus  IF IS_SRVROLEMEMBER('sysadmin') = 0 AND NOT (DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa')
Add comment 35 Plus  BEGIN
Add comment 36 Plus   SET @ErrorMessage = 'You need to be a member of the SysAdmin server role to install the SQL Server Maintenance Solution.'
Add comment 37 Plus   RAISERROR(@ErrorMessage,16,1) WITH NOWAIT
Add comment 38 Plus  END
Add comment 39 Plus  
Add comment 40 Plus  IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90
Add comment 41 Plus  BEGIN
Add comment 42 Plus   SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.'
Add comment 43 Plus   RAISERROR(@ErrorMessage,16,1) WITH NOWAIT
Add comment 44 Plus  END
Add comment 45 Plus  
Add comment 46 Plus  IF OBJECT_ID('tempdb..#Config') IS NOT NULL DROP TABLE #Config
Add comment 47 Plus  
Add comment 48 Plus  CREATE TABLE #Config ([Name] nvarchar(max),
Add comment 49 Plus   [Value] nvarchar(max))
Add comment 50 Plus  
Add comment 51 Plus  INSERT INTO #Config ([Name], [Value]) VALUES('CreateJobs', @CreateJobs)
Add comment 52 Plus  INSERT INTO #Config ([Name], [Value]) VALUES('BackupDirectory', @BackupDirectory)
Add comment 53 Plus  INSERT INTO #Config ([Name], [Value]) VALUES('CleanupTime', @CleanupTime)
Add comment 54 Plus  INSERT INTO #Config ([Name], [Value]) VALUES('OutputFileDirectory', @OutputFileDirectory)
Add comment 55 Plus  INSERT INTO #Config ([Name], [Value]) VALUES('LogToTable', @LogToTable)
Add comment 56 Plus  INSERT INTO #Config ([Name], [Value]) VALUES('DatabaseName', DB_NAME(DB_ID()))
Add comment 57 Plus  GO
Add comment 58 Plus  SET ANSI_NULLS ON
Add comment 59 Plus  GO
Add comment 60 Plus  SET QUOTED_IDENTIFIER ON
Add comment 61 Plus  GO
Add comment 62 Plus  IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CommandLog]') AND type in (N'U'))
Add comment 63 Plus  BEGIN
Add comment 64 Plus  CREATE TABLE [dbo].[CommandLog](
Add comment 65 Plus   [ID] [int] IDENTITY(1,1) NOT NULL,
Add comment 66 Plus   [DatabaseName] [sysname] NULL,
Add comment 67 Plus   [SchemaName] [sysname] NULL,
Add comment 68 Plus   [ObjectName] [sysname] NULL,
Add comment 69 Plus   [ObjectType] [char](2) NULL,
Add comment 70 Plus   [IndexName] [sysname] NULL,
Add comment 71 Plus   [IndexType] [tinyint] NULL,
Add comment 72 Plus   [StatisticsName] [sysname] NULL,
Add comment 73 Plus   [PartitionNumber] [int] NULL,
Add comment 74 Plus   [ExtendedInfo] [xml] NULL,
Add comment 75 Plus   [Command] [nvarchar](max) NOT NULL,
Add comment 76 Plus   [CommandType] [nvarchar](60) NOT NULL,
Add comment 77 Plus   [StartTime] [datetime2](7) NOT NULL,
Add comment 78 Plus   [EndTime] [datetime2](7) NULL,
Add comment 79 Plus   [ErrorNumber] [int] NULL,
Add comment 80 Plus   [ErrorMessage] [nvarchar](max) NULL,
Add comment 81 Plus   CONSTRAINT [PK_CommandLog] PRIMARY KEY CLUSTERED
Add comment 82 Plus  (
Add comment 83 Plus   [ID] ASC
Add comment 84 Plus  )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
Add comment 85 Plus  )
Add comment 86 Plus  END
Add comment 87 Plus  GO
Add comment 88 Plus  SET ANSI_NULLS ON
Add comment 89 Plus  GO
Add comment 90 Plus  SET QUOTED_IDENTIFIER ON
Add comment 91 Plus  GO
Add comment 92 Plus  IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CommandExecute]') AND type in (N'P', N'PC'))
Add comment 93 Plus  BEGIN
Add comment 94 Plus  EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[CommandExecute] AS'
Add comment 95 Plus  END
Add comment 96 Plus  GO
Add comment 97 Plus  ALTER PROCEDURE [dbo].[CommandExecute]
Add comment 98 Plus  
Add comment 99 Plus  @DatabaseContext nvarchar(max),
Add comment 100 Plus  @Command nvarchar(max),
Add comment 101 Plus  @CommandType nvarchar(max),
Add comment 102 Plus  @Mode int,
Add comment 103 Plus  @Comment nvarchar(max) = NULL,
Add comment 104 Plus  @DatabaseName nvarchar(max) = NULL,
Add comment 105 Plus  @SchemaName nvarchar(max) = NULL,
Add comment 106 Plus  @ObjectName nvarchar(max) = NULL,
Add comment 107 Plus  @ObjectType nvarchar(max) = NULL,
Add comment 108 Plus  @IndexName nvarchar(max) = NULL,
Add comment 109 Plus  @IndexType int = NULL,
Add comment 110 Plus  @StatisticsName nvarchar(max) = NULL,
Add comment 111 Plus  @PartitionNumber int = NULL,
Add comment 112 Plus  @ExtendedInfo xml = NULL,
Add comment 113 Plus  @LockMessageSeverity int = 16,
Add comment 114 Plus  @ExecuteAsUser nvarchar(max) = NULL,
Add comment 115 Plus  @LogToTable nvarchar(max),
Add comment 116 Plus  @Execute nvarchar(max)
Add comment 117 Plus  
Add comment 118 Plus  AS
Add comment 119 Plus  
Add comment 120 Plus  BEGIN
Add comment 121 Plus  
Add comment 122 Plus   ----------------------------------------------------------------------------------------------------
Add comment 123 Plus   --// Source: https://ola.hallengren.com //--
Add comment 124 Plus   --// License: https://ola.hallengren.com/license.html //--
Add comment 125 Plus   --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //--
Add comment 126 Plus   --// Version: 2022-12-03 17:23:44 //--
Add comment 127 Plus   ----------------------------------------------------------------------------------------------------
Add comment 128 Plus  
Add comment 129 Plus   SET NOCOUNT ON
Add comment 130 Plus  
Add comment 131 Plus   DECLARE @StartMessage nvarchar(max)
Add comment 132 Plus   DECLARE @EndMessage nvarchar(max)
Add comment 133 Plus   DECLARE @ErrorMessage nvarchar(max)
Add comment 134 Plus   DECLARE @ErrorMessageOriginal nvarchar(max)
Add comment 135 Plus   DECLARE @Severity int
Add comment 136 Plus  
Add comment 137 Plus   DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY,
Add comment 138 Plus   [Message] nvarchar(max) NOT NULL,
Add comment 139 Plus   Severity int NOT NULL,
Add comment 140 Plus   [State] int)
Add comment 141 Plus  
Add comment 142 Plus   DECLARE @CurrentMessage nvarchar(max)
Add comment 143 Plus   DECLARE @CurrentSeverity int
Add comment 144 Plus   DECLARE @CurrentState int
Add comment 145 Plus  
Add comment 146 Plus   DECLARE @sp_executesql nvarchar(max) = QUOTENAME(@DatabaseContext) + '.sys.sp_executesql'
Add comment 147 Plus  
Add comment 148 Plus   DECLARE @StartTime datetime2
Add comment 149 Plus   DECLARE @EndTime datetime2
Add comment 150 Plus  
Add comment 151 Plus   DECLARE @ID int
Add comment 152 Plus  
Add comment 153 Plus   DECLARE @Error int = 0
Add comment 154 Plus   DECLARE @ReturnCode int = 0
Add comment 155 Plus  
Add comment 156 Plus   DECLARE @EmptyLine nvarchar(max) = CHAR(9)
Add comment 157 Plus  
Add comment 158 Plus   DECLARE @RevertCommand nvarchar(max)
Add comment 159 Plus  
Add comment 160 Plus   ----------------------------------------------------------------------------------------------------
Add comment 161 Plus   --// Check core requirements //--
Add comment 162 Plus   ----------------------------------------------------------------------------------------------------
Add comment 163 Plus  
Add comment 164 Plus   IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90
Add comment 165 Plus   BEGIN
Add comment 166 Plus   INSERT INTO @Errors ([Message], Severity, [State])
Add comment 167 Plus   SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16, 1
Add comment 168 Plus   END
Add comment 169 Plus  
Add comment 170 Plus   IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1
Add comment 171 Plus   BEGIN
Add comment 172 Plus   INSERT INTO @Errors ([Message], Severity, [State])
Add comment 173 Plus   SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1
Add comment 174 Plus   END
Add comment 175 Plus  
Add comment 176 Plus   IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1
Add comment 177 Plus   BEGIN
Add comment 178 Plus   INSERT INTO @Errors ([Message], Severity, [State])
Add comment 179 Plus   SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1
Add comment 180 Plus   END
Add comment 181 Plus  
Add comment 182 Plus   IF @LogToTable = 'Y' AND NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'U' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandLog')
Add comment 183 Plus   BEGIN
Add comment 184 Plus   INSERT INTO @Errors ([Message], Severity, [State])
Add comment 185 Plus   SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1
Add comment 186 Plus   END
Add comment 187 Plus  
Add comment 188 Plus   ----------------------------------------------------------------------------------------------------
Add comment 189 Plus   --// Check input parameters //--
Add comment 190 Plus   ----------------------------------------------------------------------------------------------------
Add comment 191 Plus  
Add comment 192 Plus   IF @DatabaseContext IS NULL OR NOT EXISTS (SELECT * FROM sys.databases WHERE name = @DatabaseContext)
Add comment 193 Plus   BEGIN
Add comment 194 Plus   INSERT INTO @Errors ([Message], Severity, [State])
Add comment 195 Plus   SELECT 'The value for the parameter @DatabaseContext is not supported.', 16, 1
Add comment 196 Plus   END
Add comment 197 Plus  
Add comment 198 Plus   IF @Command IS NULL OR @Command = ''
Add comment 199 Plus   BEGIN
Add comment 200 Plus   INSERT INTO @Errors ([Message], Severity, [State])
Add comment 201 Plus   SELECT 'The value for the parameter @Command is not supported.', 16, 1
Add comment 202 Plus   END
Add comment 203 Plus  
Add comment 204 Plus   IF @CommandType IS NULL OR @CommandType = '' OR LEN(@CommandType) > 60
Add comment 205 Plus   BEGIN
Add comment 206 Plus   INSERT INTO @Errors ([Message], Severity, [State])
Add comment 207 Plus   SELECT 'The value for the parameter @CommandType is not supported.', 16, 1
Add comment 208 Plus   END
Add comment 209 Plus  
Add comment 210 Plus   IF @Mode NOT IN(1,2) OR @Mode IS NULL
Add comment 211 Plus   BEGIN
Add comment 212 Plus   INSERT INTO @Errors ([Message], Severity, [State])
Add comment 213 Plus   SELECT 'The value for the parameter @Mode is not supported.', 16, 1
Add comment 214 Plus   END
Add comment 215 Plus  
Add comment 216 Plus   IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL
Add comment 217 Plus   BEGIN
Add comment 218 Plus   INSERT INTO @Errors ([Message], Severity, [State])
Add comment 219 Plus   SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1
Add comment 220 Plus   END
Add comment 221 Plus  
Add comment 222 Plus   IF LEN(@ExecuteAsUser) > 128
Add comment 223 Plus   BEGIN
Add comment 224 Plus   INSERT INTO @Errors ([Message], Severity, [State])
Add comment 225 Plus   SELECT 'The value for the parameter @ExecuteAsUser is not supported.', 16, 1
Add comment 226 Plus   END
Add comment 227 Plus  
Add comment 228 Plus   IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL
Add comment 229 Plus   BEGIN
Add comment 230 Plus   INSERT INTO @Errors ([Message], Severity, [State])
Add comment 231 Plus   SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1
Add comment 232 Plus   END
Add comment 233 Plus  
Add comment 234 Plus   IF @Execute NOT IN('Y','N') OR @Execute IS NULL
Add comment 235 Plus   BEGIN
Add comment 236 Plus   INSERT INTO @Errors ([Message], Severity, [State])
Add comment 237 Plus   SELECT 'The value for the parameter @Execute is not supported.', 16, 1
Add comment 238 Plus   END
Add comment 239 Plus  
Add comment 240 Plus   ----------------------------------------------------------------------------------------------------
Add comment 241 Plus   --// Raise errors //--
Add comment 242 Plus   ----------------------------------------------------------------------------------------------------
Add comment 243 Plus  
Add comment 244 Plus   DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC
Add comment 245 Plus  
Add comment 246 Plus   OPEN ErrorCursor
Add comment 247 Plus  
Add comment 248 Plus   FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState
Add comment 249 Plus  
Add comment 250 Plus   WHILE @@FETCH_STATUS = 0
Add comment 251 Plus   BEGIN
Add comment 252 Plus   RAISERROR('%s', @CurrentSeverity, @CurrentState, @CurrentMessage) WITH NOWAIT
Add comment 253 Plus   RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT
Add comment 254 Plus  
Add comment 255 Plus   FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState
Add comment 256 Plus   END
Add comment 257 Plus  
Add comment 258 Plus   CLOSE ErrorCursor
Add comment 259 Plus  
Add comment 260 Plus   DEALLOCATE ErrorCursor
Add comment 261 Plus  
Add comment 262 Plus   IF EXISTS (SELECT * FROM @Errors WHERE Severity >= 16)
Add comment 263 Plus   BEGIN
Add comment 264 Plus   SET @ReturnCode = 50000
Add comment 265 Plus   GOTO ReturnCode
Add comment 266 Plus   END
Add comment 267 Plus  
Add comment 268 Plus   ----------------------------------------------------------------------------------------------------
Add comment 269 Plus   --// Execute as user //--
Add comment 270 Plus   ----------------------------------------------------------------------------------------------------
Add comment 271 Plus  
Add comment 272 Plus   IF @ExecuteAsUser IS NOT NULL
Add comment 273 Plus   BEGIN
Add comment 274 Plus   SET @Command = 'EXECUTE AS USER = ''' + REPLACE(@ExecuteAsUser,'''','''''') + '''; ' + @Command + '; REVERT;'
Add comment 275 Plus  
Add comment 276 Plus   SET @RevertCommand = 'REVERT'
Add comment 277 Plus   END
Add comment 278 Plus  
Add comment 279 Plus   ----------------------------------------------------------------------------------------------------
Add comment 280 Plus   --// Log initial information //--
Add comment 281 Plus   ----------------------------------------------------------------------------------------------------
Add comment 282 Plus  
Add comment 283 Plus   SET @StartTime = SYSDATETIME()
Add comment 284 Plus  
Add comment 285 Plus   SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120)
Add comment 286 Plus   RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT
Add comment 287 Plus  
Add comment 288 Plus   SET @StartMessage = 'Database context: ' + QUOTENAME(@DatabaseContext)
Add comment 289 Plus   RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT
Add comment 290 Plus  
Add comment 291 Plus   SET @StartMessage = 'Command: ' + @Command
Add comment 292 Plus   RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT
Add comment 293 Plus  
Add comment 294 Plus   IF @Comment IS NOT NULL
Add comment 295 Plus   BEGIN
Add comment 296 Plus   SET @StartMessage = 'Comment: ' + @Comment
Add comment 297 Plus   RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT
Add comment 298 Plus   END
Add comment 299 Plus  
Add comment 300 Plus   IF @LogToTable = 'Y'
Add comment 301 Plus   BEGIN
Add comment 302 Plus   INSERT INTO dbo.CommandLog (DatabaseName, SchemaName, ObjectName, ObjectType, IndexName, IndexType, StatisticsName, PartitionNumber, ExtendedInfo, CommandType, Command, StartTime)
Add comment 303 Plus   VALUES (@DatabaseName, @SchemaName, @ObjectName, @ObjectType, @IndexName, @IndexType, @StatisticsName, @PartitionNumber, @ExtendedInfo, @CommandType, @Command, @StartTime)
Add comment 304 Plus   END
Add comment 305 Plus  
Add comment 306 Plus   SET @ID = SCOPE_IDENTITY()
Add comment 307 Plus  
Add comment 308 Plus   ----------------------------------------------------------------------------------------------------
Add comment 309 Plus   --// Execute command //--
Add comment 310 Plus   ----------------------------------------------------------------------------------------------------
Add comment 311 Plus  
Add comment 312 Plus   IF @Mode = 1 AND @Execute = 'Y'
Add comment 313 Plus   BEGIN
Add comment 314 Plus   EXECUTE @sp_executesql @stmt = @Command
Add comment 315 Plus   SET @Error = @@ERROR
Add comment 316 Plus   SET @ReturnCode = @Error
Add comment 317 Plus   END
Add comment 318 Plus  
Add comment 319 Plus   IF @Mode = 2 AND @Execute = 'Y'
Add comment 320 Plus   BEGIN
Add comment 321 Plus   BEGIN TRY
Add comment 322 Plus   EXECUTE @sp_executesql @stmt = @Command
Add comment 323 Plus   END TRY
Add comment 324 Plus   BEGIN CATCH
Add comment 325 Plus   SET @Error = ERROR_NUMBER()
Add comment 326 Plus   SET @ErrorMessageOriginal = ERROR_MESSAGE()
Add comment 327 Plus  
Add comment 328 Plus   SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'')
Add comment 329 Plus   SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END
Add comment 330 Plus   RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT
Add comment 331 Plus  
Add comment 332 Plus   IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10)
Add comment 333 Plus   BEGIN
Add comment 334 Plus   SET @ReturnCode = ERROR_NUMBER()
Add comment 335 Plus   END
Add comment 336 Plus  
Add comment 337 Plus   IF @ExecuteAsUser IS NOT NULL
Add comment 338 Plus   BEGIN
Add comment 339 Plus   EXECUTE @sp_executesql @RevertCommand
Add comment 340 Plus   END
Add comment 341 Plus   END CATCH
Add comment 342 Plus   END
Add comment 343 Plus  
Add comment 344 Plus   ----------------------------------------------------------------------------------------------------
Add comment 345 Plus   --// Log completing information //--
Add comment 346 Plus   ----------------------------------------------------------------------------------------------------
Add comment 347 Plus  
Add comment 348 Plus   SET @EndTime = SYSDATETIME()
Add comment 349 Plus  
Add comment 350 Plus   SET @EndMessage = 'Outcome: ' + CASE WHEN @Execute = 'N' THEN 'Not Executed' WHEN @Error = 0 THEN 'Succeeded' ELSE 'Failed' END
Add comment 351 Plus   RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT
Add comment 352 Plus  
Add comment 353 Plus   SET @EndMessage = 'Duration: ' + CASE WHEN (DATEDIFF(SECOND,@StartTime,@EndTime) / (24 * 3600)) > 0 THEN CAST((DATEDIFF(SECOND,@StartTime,@EndTime) / (24 * 3600)) AS nvarchar) + '.' ELSE '' END + CONVERT(nvarchar,DATEADD(SECOND,DATEDIFF(SECOND,@StartTime,@EndTime),'1900-01-01'),108)
Add comment 354 Plus   RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT
Add comment 355 Plus  
Add comment 356 Plus   SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTime,120)
Add comment 357 Plus   RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT
Add comment 358 Plus  
Add comment 359 Plus   RAISERROR(@EmptyLine,10,1) WITH NOWAIT
Add comment 360 Plus  
Add comment 361 Plus   IF @LogToTable = 'Y'
Add comment 362 Plus   BEGIN
Add comment 363 Plus   UPDATE dbo.CommandLog
Add comment 364 Plus   SET EndTime = @EndTime,
Add comment 365 Plus   ErrorNumber = CASE WHEN @Execute = 'N' THEN NULL ELSE @Error END,
Add comment 366 Plus   ErrorMessage = @ErrorMessageOriginal
Add comment 367 Plus   WHERE ID = @ID
Add comment 368 Plus   END
Add comment 369 Plus  
Add comment 370 Plus   ReturnCode:
Add comment 371 Plus   IF @ReturnCode <> 0
Add comment 372 Plus   BEGIN
Add comment 373 Plus   RETURN @ReturnCode
Add comment 374 Plus   END
Add comment 375 Plus  
Add comment 376 Plus   ----------------------------------------------------------------------------------------------------
Add comment 377 Plus  
Add comment 378 Plus  END
Add comment 379 Plus  GO
Add comment 380 Plus  SET ANSI_NULLS ON
Add comment 381 Plus  GO
Add comment 382 Plus  SET QUOTED_IDENTIFIER ON
Add comment 383 Plus  GO
Add comment 384 Plus  IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DatabaseBackup]') AND type in (N'P', N'PC'))
Add comment 385 Plus  BEGIN
Add comment 386 Plus  EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[DatabaseBackup] AS'
Add comment 387 Plus  END
Add comment 388 Plus  GO
Add comment 389 Plus  ALTER PROCEDURE [dbo].[DatabaseBackup]
Add comment 390 Plus  
Add comment 391 Plus  @Databases nvarchar(max) = NULL,
Add comment 392 Plus  @Directory nvarchar(max) = NULL,
Add comment 393 Plus  @BackupType nvarchar(max),
Add comment 394 Plus  @Verify nvarchar(max) = 'N',
Add comment 395 Plus  @CleanupTime int = NULL,
Add comment 396 Plus  @CleanupMode nvarchar(max) = 'AFTER_BACKUP',
Add comment 397 Plus  @Compress nvarchar(max) = NULL,
Add comment 398 Plus  @CopyOnly nvarchar(max) = 'N',
Add comment 399 Plus  @ChangeBackupType nvarchar(max) = 'N',
Add comment 400 Plus  @BackupSoftware nvarchar(max) = NULL,
Add comment 401 Plus  @CheckSum nvarchar(max) = 'N',
Add comment 402 Plus  @BlockSize int = NULL,
Add comment 403 Plus  @BufferCount int = NULL,
Add comment 404 Plus  @MaxTransferSize int = NULL,
Add comment 405 Plus  @NumberOfFiles int = NULL,
Add comment 406 Plus  @MinBackupSizeForMultipleFiles int = NULL,
Add comment 407 Plus  @MaxFileSize int = NULL,
Add comment 408 Plus  @CompressionLevel int = NULL,
Add comment 409 Plus  @Description nvarchar(max) = NULL,
Add comment 410 Plus  @Threads int = NULL,
Add comment 411 Plus  @Throttle int = NULL,
Add comment 412 Plus  @Encrypt nvarchar(max) = 'N',
Add comment 413 Plus  @EncryptionAlgorithm nvarchar(max) = NULL,
Add comment 414 Plus  @ServerCertificate nvarchar(max) = NULL,
Add comment 415 Plus  @ServerAsymmetricKey nvarchar(max) = NULL,
Add comment 416 Plus  @EncryptionKey nvarchar(max) = NULL,
Add comment 417 Plus  @ReadWriteFileGroups nvarchar(max) = 'N',
Add comment 418 Plus  @OverrideBackupPreference nvarchar(max) = 'N',
Add comment 419 Plus  @NoRecovery nvarchar(max) = 'N',
Add comment 420 Plus  @URL nvarchar(max) = NULL,
Add comment 421 Plus  @Credential nvarchar(max) = NULL,
Add comment 422 Plus  @MirrorDirectory nvarchar(max) = NULL,
Add comment 423 Plus  @MirrorCleanupTime int = NULL,
Add comment 424 Plus  @MirrorCleanupMode nvarchar(max) = 'AFTER_BACKUP',
Add comment 425 Plus  @MirrorURL nvarchar(max) = NULL,
Add comment 426 Plus  @AvailabilityGroups nvarchar(max) = NULL,
Add comment 427 Plus  @Updateability nvarchar(max) = 'ALL',
Add comment 428 Plus  @AdaptiveCompression nvarchar(max) = NULL,
Add comment 429 Plus  @ModificationLevel int = NULL,
Add comment 430 Plus  @LogSizeSinceLastLogBackup int = NULL,
Add comment 431 Plus  @TimeSinceLastLogBackup int = NULL,
Add comment 432 Plus  @DataDomainBoostHost nvarchar(max) = NULL,
Add comment 433 Plus  @DataDomainBoostUser nvarchar(max) = NULL,
Add comment 434 Plus  @DataDomainBoostDevicePath nvarchar(max) = NULL,
Add comment 435 Plus  @DataDomainBoostLockboxPath nvarchar(max) = NULL,
Add comment 436 Plus  @DirectoryStructure nvarchar(max) = '{ServerName}${InstanceName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}',
Add comment 437 Plus  @AvailabilityGroupDirectoryStructure nvarchar(max) = '{ClusterName}${AvailabilityGroupName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}',
Add comment 438 Plus  @FileName nvarchar(max) = '{ServerName}${InstanceName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension}',
Add comment 439 Plus  @AvailabilityGroupFileName nvarchar(max) = '{ClusterName}${AvailabilityGroupName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension}',
Add comment 440 Plus  @FileExtensionFull nvarchar(max) = NULL,
Add comment 441 Plus  @FileExtensionDiff nvarchar(max) = NULL,
Add comment 442 Plus  @FileExtensionLog nvarchar(max) = NULL,
Add comment 443 Plus  @Init nvarchar(max) = 'N',
Add comment 444 Plus  @Format nvarchar(max) = 'N',
Add comment 445 Plus  @ObjectLevelRecoveryMap nvarchar(max) = 'N',
Add comment 446 Plus  @ExcludeLogShippedFromLogBackup nvarchar(max) = 'Y',
Add comment 447 Plus  @DirectoryCheck nvarchar(max) = 'Y',
Add comment 448 Plus  @StringDelimiter nvarchar(max) = ',',
Add comment 449 Plus  @DatabaseOrder nvarchar(max) = NULL,
Add comment 450 Plus  @DatabasesInParallel nvarchar(max) = 'N',
Add comment 451 Plus  @LogToTable nvarchar(max) = 'N',
Add comment 452 Plus  @Execute nvarchar(max) = 'Y'
Add comment 453 Plus  
Add comment 454 Plus  AS
Add comment 455 Plus  
Add comment 456 Plus  BEGIN
Add comment 457 Plus  
Add comment 458 Plus   ----------------------------------------------------------------------------------------------------
Add comment 459 Plus   --// Source: https://ola.hallengren.com //--
Add comment 460 Plus   --// License: https://ola.hallengren.com/license.html //--
Add comment 461 Plus   --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //--
Add comment 462 Plus   --// Version: 2022-12-03 17:23:44 //--
Add comment 463 Plus   ----------------------------------------------------------------------------------------------------
Add comment 464 Plus  
Add comment 465 Plus   SET NOCOUNT ON
Add comment 466 Plus  
Add comment 467 Plus   DECLARE @StartMessage nvarchar(max)
Add comment 468 Plus   DECLARE @EndMessage nvarchar(max)
Add comment 469 Plus   DECLARE @DatabaseMessage nvarchar(max)
Add comment 470 Plus   DECLARE @ErrorMessage nvarchar(max)
Add comment 471 Plus  
Add comment 472 Plus   DECLARE @StartTime datetime2 = SYSDATETIME()
Add comment 473 Plus   DECLARE @SchemaName nvarchar(max) = OBJECT_SCHEMA_NAME(@@PROCID)
Add comment 474 Plus   DECLARE @ObjectName nvarchar(max) = OBJECT_NAME(@@PROCID)
Add comment 475 Plus   DECLARE @VersionTimestamp nvarchar(max) = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19)
Add comment 476 Plus   DECLARE @Parameters nvarchar(max)
Add comment 477 Plus  
Add comment 478 Plus   DECLARE @HostPlatform nvarchar(max)
Add comment 479 Plus   DECLARE @DirectorySeparator nvarchar(max)
Add comment 480 Plus  
Add comment 481 Plus   DECLARE @Updated bit
Add comment 482 Plus  
Add comment 483 Plus   DECLARE @Cluster nvarchar(max)
Add comment 484 Plus  
Add comment 485 Plus   DECLARE @DefaultDirectory nvarchar(4000)
Add comment 486 Plus  
Add comment 487 Plus   DECLARE @QueueID int
Add comment 488 Plus   DECLARE @QueueStartTime datetime2
Add comment 489 Plus  
Add comment 490 Plus   DECLARE @CurrentRootDirectoryID int
Add comment 491 Plus   DECLARE @CurrentRootDirectoryPath nvarchar(4000)
Add comment 492 Plus  
Add comment 493 Plus   DECLARE @CurrentDBID int
Add comment 494 Plus   DECLARE @CurrentDatabaseName nvarchar(max)
Add comment 495 Plus  
Add comment 496 Plus   DECLARE @CurrentDatabase_sp_executesql nvarchar(max)
Add comment 497 Plus  
Add comment 498 Plus   DECLARE @CurrentUserAccess nvarchar(max)
Add comment 499 Plus   DECLARE @CurrentIsReadOnly bit
031_IndexOptimize.sql
/Deployment/031_IndexOptimize.sql+189
/Deployment/031_IndexOptimize.sql
Add comment 1 Plus  use [msdb]
Add comment 2 Plus  GO
Add comment 3 Plus  BEGIN TRANSACTION
Add comment 4 Plus  DECLARE @ReturnCode INT
Add comment 5 Plus  SELECT @ReturnCode = 0
Add comment 6 Plus  /*
Add comment 7 Plus   Updating 'IndexOptimize - USER_DATABASES' job step parameters
Add comment 8 Plus  */
Add comment 9 Plus  --dummy step2
Add comment 10 Plus  IF NOT EXISTS (select step_id from msdb.dbo.sysjobs j join msdb.dbo.sysjobsteps s on j.job_id = s.job_id where j.name=N'IndexOptimize - USER_DATABASES' and s.step_name='PushLogTo_IfSysman_onfailure')
Add comment 11 Plus  BEGIN
Add comment 12 Plus   EXEC @ReturnCode = sp_add_jobstep
Add comment 13 Plus   @step_id=2,
Add comment 14 Plus   @job_name = N'IndexOptimize - USER_DATABASES',
Add comment 15 Plus   @step_name = N'PushLogTo_IfSysman_onfailure',
Add comment 16 Plus   @subsystem = N'TSQL',
Add comment 17 Plus   @command = N'this is dummy and will be replaced'
Add comment 18 Plus  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 19 Plus  END
Add comment 20 Plus  --dummy step3
Add comment 21 Plus  IF NOT EXISTS (select step_id from msdb.dbo.sysjobs j join msdb.dbo.sysjobsteps s on j.job_id = s.job_id where j.name=N'IndexOptimize - USER_DATABASES' and s.step_name='PushLogTo_IfSysman_onsuccess')
Add comment 22 Plus  BEGIN
Add comment 23 Plus   EXEC @ReturnCode = sp_add_jobstep
Add comment 24 Plus   @step_id=3,
Add comment 25 Plus   @job_name = N'IndexOptimize - USER_DATABASES',
Add comment 26 Plus   @step_name = N'PushLogTo_IfSysman_onsuccess',
Add comment 27 Plus   @subsystem = N'TSQL',
Add comment 28 Plus   @command = N'this is dummy and will be replaced'
Add comment 29 Plus  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 30 Plus  END
Add comment 31 Plus  
Add comment 32 Plus  --step1
Add comment 33 Plus  DECLARE @pathtolog NVARCHAR(1000)
Add comment 34 Plus  select @pathtolog=LEFT(filename, CHARINDEX('\work\data', filename)) + 'temp\IndexOptimizeLog.txt' from tempdb.sys.sysfiles where name='templog'
Add comment 35 Plus  EXEC @ReturnCode = msdb.dbo.sp_update_jobstep
Add comment 36 Plus   @job_name=N'IndexOptimize - USER_DATABASES',
Add comment 37 Plus   @step_id=1 ,
Add comment 38 Plus   @on_success_action=4,
Add comment 39 Plus   @on_success_step_id=3,
Add comment 40 Plus   @on_fail_action=4,
Add comment 41 Plus   @on_fail_step_id=2,
Add comment 42 Plus   @subsystem=N'TSQL',
Add comment 43 Plus   @command=N'
Add comment 44 Plus   USE [IF_SysMan]
Add comment 45 Plus   GO
Add comment 46 Plus   EXECUTE dbo.IndexOptimize
Add comment 47 Plus   @Databases = ''USER_DATABASES'',
Add comment 48 Plus   @FragmentationLow = NULL,
Add comment 49 Plus   @FragmentationMedium = ''INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE'',
Add comment 50 Plus   @FragmentationHigh = ''INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE'',
Add comment 51 Plus   @FragmentationLevel1 = 5,
Add comment 52 Plus   @FragmentationLevel2 = 30,
Add comment 53 Plus   @MinNumberOfPages = 1000,
Add comment 54 Plus   @MaxNumberOfPages = NULL,
Add comment 55 Plus   @SortInTempdb = ''Y'',
Add comment 56 Plus   @MaxDOP = NULL,
Add comment 57 Plus   @FillFactor = 100,
Add comment 58 Plus   @PadIndex = NULL,
Add comment 59 Plus   @LOBCompaction = ''Y'',
Add comment 60 Plus   @UpdateStatistics = ''ALL'',
Add comment 61 Plus   @OnlyModifiedStatistics = ''Y'',
Add comment 62 Plus   @StatisticsModificationLevel = NULL,
Add comment 63 Plus   @StatisticsSample = NULL,
Add comment 64 Plus   @StatisticsResample = ''N'',
Add comment 65 Plus   @PartitionLevel = ''Y'',
Add comment 66 Plus   @MSShippedObjects = ''N'',
Add comment 67 Plus   @Indexes = ''ALL_INDEXES'',
Add comment 68 Plus   @TimeLimit = NULL,
Add comment 69 Plus   @Delay = NULL,
Add comment 70 Plus   @WaitAtLowPriorityMaxDuration = NULL,
Add comment 71 Plus   @WaitAtLowPriorityAbortAfterWait = NULL,
Add comment 72 Plus   @Resumable = ''N'',
Add comment 73 Plus   @AvailabilityGroups = NULL,
Add comment 74 Plus   @LockTimeout = 600,
Add comment 75 Plus   @LockMessageSeverity = 10,
Add comment 76 Plus   @DatabaseOrder = NULL,
Add comment 77 Plus   @DatabasesInParallel = ''N'',
Add comment 78 Plus   @LogToTable = ''Y'',
Add comment 79 Plus   @Execute = ''Y''',
Add comment 80 Plus   @database_name=N'IF_SysMan',
Add comment 81 Plus   @output_file_name=@pathtolog
Add comment 82 Plus  
Add comment 83 Plus  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 84 Plus  
Add comment 85 Plus  --step2
Add comment 86 Plus  DECLARE @cmdstepf varchar(max) = N'IF OBJECT_ID(''dbo.SqlMiJobLog'') IS NULL
Add comment 87 Plus  CREATE TABLE [dbo].[SqlMiJobLog](
Add comment 88 Plus   [ID] [int] IDENTITY(1,1) NOT NULL,
Add comment 89 Plus   [JobName] [nvarchar] (100) NOT NULL,
Add comment 90 Plus   [CollectTime] [datetime] NOT NULL,
Add comment 91 Plus   [Content] [nvarchar](max) NULL,
Add comment 92 Plus   ) ON [PRIMARY]
Add comment 93 Plus  GO
Add comment 94 Plus  DECLARE @pathtolog NVARCHAR(1000)
Add comment 95 Plus  select @pathtolog=LEFT(filename, CHARINDEX(''\work\data'', filename)) + ''temp\IndexOptimizeLog.txt'' from tempdb.sys.sysfiles where name=''templog''
Add comment 96 Plus  DECLARE @sql varchar(max)
Add comment 97 Plus  set @sql = ''CREATE TABLE #demo(Content NVARCHAR(1000));
Add comment 98 Plus  BULK INSERT #demo
Add comment 99 Plus   FROM ''''''+@pathtolog+''''''
Add comment 100 Plus   WITH (ROWTERMINATOR =''''\n'''', DATAFILETYPE = ''''widechar'''')
Add comment 101 Plus  INSERT INTO IF_SysMan.dbo.SqlMiJobLog (JobName, CollectTime, Content)
Add comment 102 Plus  SELECT ''''IndexOptimize'''' as JobName, GETDATE() as CollectTime, Content FROM #demo''
Add comment 103 Plus  exec (@sql)'
Add comment 104 Plus  
Add comment 105 Plus  EXEC @ReturnCode = msdb.dbo.sp_update_jobstep
Add comment 106 Plus   @job_name='IndexOptimize - USER_DATABASES',
Add comment 107 Plus   @step_id=2,
Add comment 108 Plus   @cmdexec_success_code=0,
Add comment 109 Plus   @on_success_action=2,
Add comment 110 Plus   @on_success_step_id=0,
Add comment 111 Plus   @on_fail_action=2,
Add comment 112 Plus   @on_fail_step_id=0,
Add comment 113 Plus   @retry_attempts=0,
Add comment 114 Plus   @retry_interval=0,
Add comment 115 Plus   @os_run_priority=0, @subsystem=N'TSQL',
Add comment 116 Plus   @command=@cmdstepf,
Add comment 117 Plus   @database_name=N'If_Sysman',
Add comment 118 Plus   @flags=0
Add comment 119 Plus  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 120 Plus  
Add comment 121 Plus  --step3
Add comment 122 Plus  DECLARE @cmdsteps varchar(max) = N'IF OBJECT_ID(''dbo.SqlMiJobLog'') IS NULL
Add comment 123 Plus  CREATE TABLE [dbo].[SqlMiJobLog](
Add comment 124 Plus   [ID] [int] IDENTITY(1,1) NOT NULL,
Add comment 125 Plus   [JobName] [nvarchar] (100) NOT NULL,
Add comment 126 Plus   [CollectTime] [datetime] NOT NULL,
Add comment 127 Plus   [Content] [nvarchar](max) NULL,
Add comment 128 Plus   ) ON [PRIMARY]
Add comment 129 Plus  GO
Add comment 130 Plus  DECLARE @pathtolog NVARCHAR(1000)
Add comment 131 Plus  select @pathtolog=LEFT(filename, CHARINDEX(''\work\data'', filename)) + ''temp\IndexOptimizeLog.txt'' from tempdb.sys.sysfiles where name=''templog''
Add comment 132 Plus  DECLARE @sql varchar(max)
Add comment 133 Plus  set @sql = ''CREATE TABLE #demo(Content NVARCHAR(1000));
Add comment 134 Plus  BULK INSERT #demo
Add comment 135 Plus   FROM ''''''+@pathtolog+''''''
Add comment 136 Plus   WITH (ROWTERMINATOR =''''\n'''', DATAFILETYPE = ''''widechar'''')
Add comment 137 Plus  INSERT INTO IF_SysMan.dbo.SqlMiJobLog (JobName, CollectTime, Content)
Add comment 138 Plus  SELECT ''''IndexOptimize'''' as JobName, GETDATE() as CollectTime, Content FROM #demo''
Add comment 139 Plus  exec (@sql)'
Add comment 140 Plus  
Add comment 141 Plus  EXEC @ReturnCode = msdb.dbo.sp_update_jobstep
Add comment 142 Plus   @job_name='IndexOptimize - USER_DATABASES',
Add comment 143 Plus   @step_id=3,
Add comment 144 Plus   @cmdexec_success_code=0,
Add comment 145 Plus   @on_success_action=1,
Add comment 146 Plus   @on_success_step_id=0,
Add comment 147 Plus   @on_fail_action=2,
Add comment 148 Plus   @on_fail_step_id=0,
Add comment 149 Plus   @retry_attempts=0,
Add comment 150 Plus   @retry_interval=0,
Add comment 151 Plus   @os_run_priority=0, @subsystem=N'TSQL',
Add comment 152 Plus   @command=@cmdsteps,
Add comment 153 Plus   @database_name=N'If_Sysman',
Add comment 154 Plus   @flags=0
Add comment 155 Plus  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 156 Plus  /*
Add comment 157 Plus   Dropping and creating schedule: 'Daily - 02:00'
Add comment 158 Plus   Attaching job: IndexOptimize - USER_DATABASES
Add comment 159 Plus  */
Add comment 160 Plus  
Add comment 161 Plus  DECLARE @Id int
Add comment 162 Plus  WHILE EXISTS (SELECT name FROM msdb.dbo.sysschedules WHERE name = N'Daily - 02:00')
Add comment 163 Plus  BEGIN
Add comment 164 Plus   SET @Id = (SELECT TOP 1 schedule_id FROM msdb.dbo.sysschedules WHERE name = N'Daily - 02:00')
Add comment 165 Plus   EXEC @ReturnCode = msdb.dbo.sp_delete_schedule @schedule_id = @Id, @force_delete = 1
Add comment 166 Plus   IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 167 Plus  END
Add comment 168 Plus  
Add comment 169 Plus  DECLARE @schedule_id int
Add comment 170 Plus  EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_name=N'IndexOptimize - USER_DATABASES', @name=N'Daily - 02:00',
Add comment 171 Plus   @enabled=1,
Add comment 172 Plus   @freq_type=4,
Add comment 173 Plus   @freq_interval=1,
Add comment 174 Plus   @freq_subday_type=1,
Add comment 175 Plus   @freq_subday_interval=0,
Add comment 176 Plus   @freq_relative_interval=0,
Add comment 177 Plus   @freq_recurrence_factor=1,
Add comment 178 Plus   @active_start_date=20170711,
Add comment 179 Plus   @active_end_date=99991231,
Add comment 180 Plus   @active_start_time=20000,
Add comment 181 Plus   @active_end_time=235959, @schedule_id = @schedule_id OUTPUT
Add comment 182 Plus  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 183 Plus  
Add comment 184 Plus  COMMIT TRANSACTION
Add comment 185 Plus  GOTO EndSave
Add comment 186 Plus  QuitWithRollback:
Add comment 187 Plus   IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
Add comment 188 Plus  EndSave:
Add comment 189 Plus  GO
032_IntegrityCheck.sql
/Deployment/032_IntegrityCheck.sql+191
/Deployment/032_IntegrityCheck.sql
Add comment 1 Plus  use [msdb]
Add comment 2 Plus  GO
Add comment 3 Plus  BEGIN TRANSACTION
Add comment 4 Plus  DECLARE @ReturnCode INT
Add comment 5 Plus  SELECT @ReturnCode = 0
Add comment 6 Plus  /*
Add comment 7 Plus   Renaming USRER_DATABASES to ALL_DATABASES
Add comment 8 Plus  */
Add comment 9 Plus  
Add comment 10 Plus  IF NOT EXISTS (SELECT name FROM msdb.dbo.sysjobs WHERE name = N'DatabaseIntegrityCheck - ALL_DATABASES')
Add comment 11 Plus  BEGIN
Add comment 12 Plus   EXEC @ReturnCode = msdb.dbo.sp_update_job @job_name=N'DatabaseIntegrityCheck - USER_DATABASES', @new_name=N'DatabaseIntegrityCheck - ALL_DATABASES'
Add comment 13 Plus   IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 14 Plus  END
Add comment 15 Plus  /*
Add comment 16 Plus   Updating job step DatabaseIntegrityCheck - ALL_DATABASES
Add comment 17 Plus  */
Add comment 18 Plus  --dummy step2
Add comment 19 Plus  IF NOT EXISTS (select step_id from msdb.dbo.sysjobs j join msdb.dbo.sysjobsteps s on j.job_id = s.job_id where j.name=N'DatabaseIntegrityCheck - ALL_DATABASES' and s.step_name='PushLogTo_IfSysman_onfailure')
Add comment 20 Plus  BEGIN
Add comment 21 Plus   EXEC @ReturnCode = sp_add_jobstep
Add comment 22 Plus   @step_id=2,
Add comment 23 Plus   @job_name = N'DatabaseIntegrityCheck - ALL_DATABASES',
Add comment 24 Plus   @step_name = N'PushLogTo_IfSysman_onfailure',
Add comment 25 Plus   @subsystem = N'TSQL',
Add comment 26 Plus   @command = N'this is dummy and will be replaced'
Add comment 27 Plus  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 28 Plus  END
Add comment 29 Plus  --dummy step3
Add comment 30 Plus  IF NOT EXISTS (select step_id from msdb.dbo.sysjobs j join msdb.dbo.sysjobsteps s on j.job_id = s.job_id where j.name=N'DatabaseIntegrityCheck - ALL_DATABASES' and s.step_name='PushLogTo_IfSysman_onsuccess')
Add comment 31 Plus  BEGIN
Add comment 32 Plus   EXEC @ReturnCode = sp_add_jobstep
Add comment 33 Plus   @step_id=3,
Add comment 34 Plus   @job_name = N'DatabaseIntegrityCheck - ALL_DATABASES',
Add comment 35 Plus   @step_name = N'PushLogTo_IfSysman_onsuccess',
Add comment 36 Plus   @subsystem = N'TSQL',
Add comment 37 Plus   @command = N'this is dummy and will be replaced'
Add comment 38 Plus  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 39 Plus  END
Add comment 40 Plus  
Add comment 41 Plus  --step1
Add comment 42 Plus  DECLARE @pathtolog NVARCHAR(1000)
Add comment 43 Plus  select @pathtolog=LEFT(filename, CHARINDEX('\work\data', filename)) + 'temp\DatabaseIntegrityCheckLog.txt' from tempdb.sys.sysfiles where name='templog'
Add comment 44 Plus  EXEC @ReturnCode = msdb.dbo.sp_update_jobstep @job_name='DatabaseIntegrityCheck - ALL_DATABASES',
Add comment 45 Plus   @step_id=1,
Add comment 46 Plus   @on_success_action=4,
Add comment 47 Plus   @on_success_step_id=3,
Add comment 48 Plus   @on_fail_action=4,
Add comment 49 Plus   @on_fail_step_id=2,
Add comment 50 Plus   @subsystem=N'TSQL',
Add comment 51 Plus   @command=N'EXECUTE [dbo].[DatabaseIntegrityCheck]
Add comment 52 Plus   @Databases = ''ALL_DATABASES'',
Add comment 53 Plus   @CheckCommands = ''CHECKDB'',
Add comment 54 Plus   @PhysicalOnly = ''N'',
Add comment 55 Plus   @NoIndex = ''N'',
Add comment 56 Plus   @ExtendedLogicalChecks = ''N'',
Add comment 57 Plus   @TabLock = ''N'',
Add comment 58 Plus   @FileGroups = NULL,
Add comment 59 Plus   @Objects = NULL,
Add comment 60 Plus   @MaxDOP = NULL,
Add comment 61 Plus   @AvailabilityGroups = NULL,
Add comment 62 Plus   @AvailabilityGroupReplicas = ''ALL'',
Add comment 63 Plus   @Updateability = ''ALL'',
Add comment 64 Plus   @TimeLimit = NULL,
Add comment 65 Plus   @LockTimeout = NULL,
Add comment 66 Plus   @LockMessageSeverity = NULL,
Add comment 67 Plus   @DatabaseOrder = NULL,
Add comment 68 Plus   @DatabasesInParallel = ''N'',
Add comment 69 Plus   @LogToTable = ''Y'',
Add comment 70 Plus   @Execute = ''Y''
Add comment 71 Plus  ',
Add comment 72 Plus   @database_name=N'IF_SysMan',
Add comment 73 Plus   @output_file_name=@pathtolog
Add comment 74 Plus  
Add comment 75 Plus  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 76 Plus  
Add comment 77 Plus  --step2
Add comment 78 Plus  DECLARE @cmdstepf varchar(max) = N'IF OBJECT_ID(''dbo.SqlMiJobLog'') IS NULL
Add comment 79 Plus  CREATE TABLE [dbo].[SqlMiJobLog](
Add comment 80 Plus   [ID] [int] IDENTITY(1,1) NOT NULL,
Add comment 81 Plus   [JobName] [nvarchar] (100) NOT NULL,
Add comment 82 Plus   [CollectTime] [datetime] NOT NULL,
Add comment 83 Plus   [Content] [nvarchar](max) NULL,
Add comment 84 Plus   ) ON [PRIMARY]
Add comment 85 Plus  GO
Add comment 86 Plus  DECLARE @pathtolog NVARCHAR(1000)
Add comment 87 Plus  select @pathtolog=LEFT(filename, CHARINDEX(''\work\data'', filename)) + ''temp\DatabaseIntegrityCheckLog.txt'' from tempdb.sys.sysfiles where name=''templog''
Add comment 88 Plus  DECLARE @sql varchar(max)
Add comment 89 Plus  set @sql = ''CREATE TABLE #demo(Content NVARCHAR(1000));
Add comment 90 Plus  BULK INSERT #demo
Add comment 91 Plus   FROM ''''''+@pathtolog+''''''
Add comment 92 Plus   WITH (ROWTERMINATOR =''''\n'''', DATAFILETYPE = ''''widechar'''')
Add comment 93 Plus  INSERT INTO IF_SysMan.dbo.SqlMiJobLog (JobName, CollectTime, Content)
Add comment 94 Plus  SELECT ''''DatabaseIntegrityCheck'''' as JobName, GETDATE() as CollectTime, Content FROM #demo''
Add comment 95 Plus  exec (@sql)'
Add comment 96 Plus  
Add comment 97 Plus  EXEC @ReturnCode = msdb.dbo.sp_update_jobstep
Add comment 98 Plus   @job_name='DatabaseIntegrityCheck - ALL_DATABASES',
Add comment 99 Plus   @step_id=2,
Add comment 100 Plus   @cmdexec_success_code=0,
Add comment 101 Plus   @on_success_action=2,
Add comment 102 Plus   @on_success_step_id=0,
Add comment 103 Plus   @on_fail_action=2,
Add comment 104 Plus   @on_fail_step_id=0,
Add comment 105 Plus   @retry_attempts=0,
Add comment 106 Plus   @retry_interval=0,
Add comment 107 Plus   @os_run_priority=0, @subsystem=N'TSQL',
Add comment 108 Plus   @command=@cmdstepf,
Add comment 109 Plus   @database_name=N'If_Sysman',
Add comment 110 Plus   @flags=0
Add comment 111 Plus  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 112 Plus  
Add comment 113 Plus  --step3
Add comment 114 Plus  DECLARE @cmdsteps varchar(max) = N'IF OBJECT_ID(''dbo.SqlMiJobLog'') IS NULL
Add comment 115 Plus  CREATE TABLE [dbo].[SqlMiJobLog](
Add comment 116 Plus   [ID] [int] IDENTITY(1,1) NOT NULL,
Add comment 117 Plus   [JobName] [nvarchar] (100) NOT NULL,
Add comment 118 Plus   [CollectTime] [datetime] NOT NULL,
Add comment 119 Plus   [Content] [nvarchar](max) NULL,
Add comment 120 Plus   ) ON [PRIMARY]
Add comment 121 Plus  GO
Add comment 122 Plus  DECLARE @pathtolog NVARCHAR(1000)
Add comment 123 Plus  select @pathtolog=LEFT(filename, CHARINDEX(''\work\data'', filename)) + ''temp\DatabaseIntegrityCheckLog.txt'' from tempdb.sys.sysfiles where name=''templog''
Add comment 124 Plus  DECLARE @sql varchar(max)
Add comment 125 Plus  set @sql = ''CREATE TABLE #demo(Content NVARCHAR(1000));
Add comment 126 Plus  BULK INSERT #demo
Add comment 127 Plus   FROM ''''''+@pathtolog+''''''
Add comment 128 Plus   WITH (ROWTERMINATOR =''''\n'''', DATAFILETYPE = ''''widechar'''')
Add comment 129 Plus  INSERT INTO IF_SysMan.dbo.SqlMiJobLog (JobName, CollectTime, Content)
Add comment 130 Plus  SELECT ''''DatabaseIntegrityCheck'''' as JobName, GETDATE() as CollectTime, Content FROM #demo''
Add comment 131 Plus  exec (@sql)'
Add comment 132 Plus  
Add comment 133 Plus  EXEC @ReturnCode = msdb.dbo.sp_update_jobstep
Add comment 134 Plus   @job_name='DatabaseIntegrityCheck - ALL_DATABASES',
Add comment 135 Plus   @step_id=3,
Add comment 136 Plus   @cmdexec_success_code=0,
Add comment 137 Plus   @on_success_action=1,
Add comment 138 Plus   @on_success_step_id=0,
Add comment 139 Plus   @on_fail_action=2,
Add comment 140 Plus   @on_fail_step_id=0,
Add comment 141 Plus   @retry_attempts=0,
Add comment 142 Plus   @retry_interval=0,
Add comment 143 Plus   @os_run_priority=0, @subsystem=N'TSQL',
Add comment 144 Plus   @command=@cmdsteps,
Add comment 145 Plus   @database_name=N'If_Sysman',
Add comment 146 Plus   @flags=0
Add comment 147 Plus  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 148 Plus  
Add comment 149 Plus  
Add comment 150 Plus  /*
Add comment 151 Plus   Dropping and creating schedule: 'Weekly - Sunday - 03:00'
Add comment 152 Plus   Attaching jobs: DatabaseIntegrityCheck - ALL_DATABASES
Add comment 153 Plus  */
Add comment 154 Plus  
Add comment 155 Plus  DECLARE @Id int
Add comment 156 Plus  WHILE EXISTS (SELECT name FROM msdb.dbo.sysschedules WHERE name = N'Weekly - Sunday - 03:00')
Add comment 157 Plus  BEGIN
Add comment 158 Plus   SET @Id = (SELECT TOP 1 schedule_id FROM msdb.dbo.sysschedules WHERE name = N'Weekly - Sunday - 03:00')
Add comment 159 Plus   EXEC @ReturnCode = msdb.dbo.sp_delete_schedule @schedule_id = @Id, @force_delete = 1
Add comment 160 Plus   IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 161 Plus  END
Add comment 162 Plus  
Add comment 163 Plus  DECLARE @schedule_id int
Add comment 164 Plus  EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_name=N'DatabaseIntegrityCheck - ALL_DATABASES', @name=N'Weekly - Sunday - 03:00',
Add comment 165 Plus   @enabled=1,
Add comment 166 Plus   @freq_type=8,
Add comment 167 Plus   @freq_interval=1,
Add comment 168 Plus   @freq_subday_type=1,
Add comment 169 Plus   @freq_subday_interval=0,
Add comment 170 Plus   @freq_relative_interval=0,
Add comment 171 Plus   @freq_recurrence_factor=1,
Add comment 172 Plus   @active_start_date=20170711,
Add comment 173 Plus   @active_end_date=99991231,
Add comment 174 Plus   @active_start_time=30000,
Add comment 175 Plus   @active_end_time=235959, @schedule_id = @schedule_id OUTPUT
Add comment 176 Plus  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 177 Plus  
Add comment 178 Plus  IF EXISTS (SELECT name FROM msdb.dbo.sysjobs WHERE name = N'DatabaseIntegrityCheck - SYSTEM_DATABASES')
Add comment 179 Plus   EXEC @ReturnCode = msdb.dbo.sp_delete_job @job_name=N'DatabaseIntegrityCheck - SYSTEM_DATABASES', @delete_unused_schedule=1
Add comment 180 Plus  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 181 Plus  
Add comment 182 Plus  IF EXISTS (SELECT name FROM msdb.dbo.sysjobs WHERE name = N'DatabaseIntegrityCheck - USER_DATABASES')
Add comment 183 Plus   EXEC @ReturnCode= msdb.dbo.sp_delete_job @job_name=N'DatabaseIntegrityCheck - USER_DATABASES', @delete_unused_schedule=1
Add comment 184 Plus  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
Add comment 185 Plus  
Add comment 186 Plus  COMMIT TRANSACTION
Add comment 187 Plus  GOTO EndSave
Add comment 188 Plus  QuitWithRollback:
Add comment 189 Plus   IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
Add comment 190 Plus  EndSave:
Add comment 191 Plus  GO
037_CleanupJobSchedules.sql
/Deployment/037_CleanupJobSchedules.sql+36
/Deployment/037_CleanupJobSchedules.sql
Add comment 1 Plus  USE [msdb]
Add comment 2 Plus  GO
Add comment 3 Plus  
Add comment 4 Plus  /*
Add comment 5 Plus   Dropping and creating schedule: 'Weekly - Sunday - 07:00'
Add comment 6 Plus   Attaching jobs: CommandLog Cleanup
Add comment 7 Plus   sp_purge_jobhistory
Add comment 8 Plus  */
Add comment 9 Plus  
Add comment 10 Plus  DECLARE @Id int
Add comment 11 Plus  WHILE EXISTS (SELECT name FROM msdb.dbo.sysschedules WHERE name = N'Weekly - Sunday - 07:00')
Add comment 12 Plus  BEGIN
Add comment 13 Plus   SET @Id = (SELECT TOP 1 schedule_id FROM msdb.dbo.sysschedules WHERE name = N'Weekly - Sunday - 07:00')
Add comment 14 Plus   EXEC msdb.dbo.sp_delete_schedule @schedule_id = @Id, @force_delete = 1
Add comment 15 Plus  END
Add comment 16 Plus  
Add comment 17 Plus  DECLARE @schedule_id int
Add comment 18 Plus  EXEC msdb.dbo.sp_add_jobschedule @job_name=N'CommandLog Cleanup', @name=N'Weekly - Sunday - 07:00',
Add comment 19 Plus   @enabled=1,
Add comment 20 Plus   @freq_type=8,
Add comment 21 Plus   @freq_interval=1,
Add comment 22 Plus   @freq_subday_type=1,
Add comment 23 Plus   @freq_subday_interval=0,
Add comment 24 Plus   @freq_relative_interval=0,
Add comment 25 Plus   @freq_recurrence_factor=1,
Add comment 26 Plus   @active_start_date=20170711,
Add comment 27 Plus   @active_end_date=99991231,
Add comment 28 Plus   @active_start_time=70000,
Add comment 29 Plus   @active_end_time=235959, @schedule_id = @schedule_id OUTPUT
Add comment 30 Plus  
Add comment 31 Plus  --EXEC msdb.dbo.sp_attach_schedule @job_name=N'sp_delete_backuphistory',@schedule_id=@schedule_id
Add comment 32 Plus  
Add comment 33 Plus  EXEC msdb.dbo.sp_attach_schedule @job_name=N'sp_purge_jobhistory',@schedule_id=@schedule_id
Add comment 34 Plus  
Add comment 35 Plus  --EXEC msdb.dbo.sp_attach_schedule @job_name=N'Output File Cleanup',@schedule_id=@schedule_id
Add comment 36 Plus  GO
040_sp_WhoIsActive.sql
/Deployment/040_sp_WhoIsActive.sql+5503
/Deployment/040_sp_WhoIsActive.sql
Add comment 1 Plus  SET QUOTED_IDENTIFIER ON;
Add comment 2 Plus  SET ANSI_PADDING ON;
Add comment 3 Plus  SET CONCAT_NULL_YIELDS_NULL ON;
Add comment 4 Plus  SET ANSI_WARNINGS ON;
Add comment 5 Plus  SET NUMERIC_ROUNDABORT OFF;
Add comment 6 Plus  SET ARITHABORT ON;
Add comment 7 Plus  GO
Add comment 8 Plus  
Add comment 9 Plus  IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_NAME = 'sp_WhoIsActive')
Add comment 10 Plus   EXEC ('CREATE PROC dbo.sp_WhoIsActive AS SELECT ''stub version, to be replaced''')
Add comment 11 Plus  GO
Add comment 12 Plus  
Add comment 13 Plus  /*********************************************************************************************
Add comment 14 Plus  Who Is Active? v12.00 (2021-11-10)
Add comment 15 Plus  (C) 2007-2021, Adam Machanic
Add comment 16 Plus  
Add comment 17 Plus  Feedback: https://github.com/amachanic/sp_whoisactive/issues
Add comment 18 Plus  Releases: https://github.com/amachanic/sp_whoisactive/releases
Add comment 19 Plus  Docs: http://whoisactive.com
Add comment 20 Plus  
Add comment 21 Plus  License:
Add comment 22 Plus   https://github.com/amachanic/sp_whoisactive/blob/master/LICENSE
Add comment 23 Plus  *********************************************************************************************/
Add comment 24 Plus  ALTER PROC dbo.sp_WhoIsActive
Add comment 25 Plus  (
Add comment 26 Plus  --~
Add comment 27 Plus   --Filters--Both inclusive and exclusive
Add comment 28 Plus   --Set either filter to '' to disable
Add comment 29 Plus   --Valid filter types are: session, program, database, login, and host
Add comment 30 Plus   --Session is a session ID, and either 0 or '' can be used to indicate "all" sessions
Add comment 31 Plus   --All other filter types support % or _ as wildcards
Add comment 32 Plus   @filter sysname = '',
Add comment 33 Plus   @filter_type VARCHAR(10) = 'session',
Add comment 34 Plus   @not_filter sysname = '',
Add comment 35 Plus   @not_filter_type VARCHAR(10) = 'session',
Add comment 36 Plus  
Add comment 37 Plus   --Retrieve data about the calling session?
Add comment 38 Plus   @show_own_spid BIT = 0,
Add comment 39 Plus  
Add comment 40 Plus   --Retrieve data about system sessions?
Add comment 41 Plus   @show_system_spids BIT = 0,
Add comment 42 Plus  
Add comment 43 Plus   --Controls how sleeping SPIDs are handled, based on the idea of levels of interest
Add comment 44 Plus   --0 does not pull any sleeping SPIDs
Add comment 45 Plus   --1 pulls only those sleeping SPIDs that also have an open transaction
Add comment 46 Plus   --2 pulls all sleeping SPIDs
Add comment 47 Plus   @show_sleeping_spids TINYINT = 1,
Add comment 48 Plus  
Add comment 49 Plus   --If 1, gets the full stored procedure or running batch, when available
Add comment 50 Plus   --If 0, gets only the actual statement that is currently running in the batch or procedure
Add comment 51 Plus   @get_full_inner_text BIT = 0,
Add comment 52 Plus  
Add comment 53 Plus   --Get associated query plans for running tasks, if available
Add comment 54 Plus   --If @get_plans = 1, gets the plan based on the request's statement offset
Add comment 55 Plus   --If @get_plans = 2, gets the entire plan based on the request's plan_handle
Add comment 56 Plus   @get_plans TINYINT = 0,
Add comment 57 Plus  
Add comment 58 Plus   --Get the associated outer ad hoc query or stored procedure call, if available
Add comment 59 Plus   @get_outer_command BIT = 0,
Add comment 60 Plus  
Add comment 61 Plus   --Enables pulling transaction log write info, transaction duration, and the
Add comment 62 Plus   --implicit_transaction identification column
Add comment 63 Plus   @get_transaction_info BIT = 0,
Add comment 64 Plus  
Add comment 65 Plus   --Get information on active tasks, based on three interest levels
Add comment 66 Plus   --Level 0 does not pull any task-related information
Add comment 67 Plus   --Level 1 is a lightweight mode that pulls the top non-CXPACKET wait, giving preference to blockers
Add comment 68 Plus   --Level 2 pulls all available task-based metrics, including:
Add comment 69 Plus   --number of active tasks, current wait stats, physical I/O, context switches, and blocker information
Add comment 70 Plus   @get_task_info TINYINT = 1,
Add comment 71 Plus  
Add comment 72 Plus   --Gets associated locks for each request, aggregated in an XML format
Add comment 73 Plus   @get_locks BIT = 0,
Add comment 74 Plus  
Add comment 75 Plus   --Get average time for past runs of an active query
Add comment 76 Plus   --(based on the combination of plan handle, sql handle, and offset)
Add comment 77 Plus   @get_avg_time BIT = 0,
Add comment 78 Plus  
Add comment 79 Plus   --Get additional non-performance-related information about the session or request
Add comment 80 Plus   --text_size, language, date_format, date_first, quoted_identifier, arithabort, ansi_null_dflt_on,
Add comment 81 Plus   --ansi_defaults, ansi_warnings, ansi_padding, ansi_nulls, concat_null_yields_null,
Add comment 82 Plus   --transaction_isolation_level, lock_timeout, deadlock_priority, row_count, command_type
Add comment 83 Plus   --
Add comment 84 Plus   --If a SQL Agent job is running, an subnode called agent_info will be populated with some or all of
Add comment 85 Plus   --the following: job_id, job_name, step_id, step_name, msdb_query_error (in the event of an error)
Add comment 86 Plus   --
Add comment 87 Plus   --If @get_task_info is set to 2 and a lock wait is detected, a subnode called block_info will be
Add comment 88 Plus   --populated with some or all of the following: lock_type, database_name, object_id, file_id, hobt_id,
Add comment 89 Plus   --applock_hash, metadata_resource, metadata_class_id, object_name, schema_name
Add comment 90 Plus   @get_additional_info BIT = 0,
Add comment 91 Plus  
Add comment 92 Plus   --Get additional information related to workspace memory
Add comment 93 Plus   --requested_memory, granted_memory, max_used_memory, and memory_info.
Add comment 94 Plus   --
Add comment 95 Plus   --Not available for SQL Server 2005.
Add comment 96 Plus   @get_memory_info BIT = 0,
Add comment 97 Plus  
Add comment 98 Plus   --Walk the blocking chain and count the number of
Add comment 99 Plus   --total SPIDs blocked all the way down by a given session
Add comment 100 Plus   --Also enables task_info Level 1, if @get_task_info is set to 0
Add comment 101 Plus   @find_block_leaders BIT = 0,
Add comment 102 Plus  
Add comment 103 Plus   --Pull deltas on various metrics
Add comment 104 Plus   --Interval in seconds to wait before doing the second data pull
Add comment 105 Plus   @delta_interval TINYINT = 0,
Add comment 106 Plus  
Add comment 107 Plus   --List of desired output columns, in desired order
Add comment 108 Plus   --Note that the final output will be the intersection of all enabled features and all
Add comment 109 Plus   --columns in the list. Therefore, only columns associated with enabled features will
Add comment 110 Plus   --actually appear in the output. Likewise, removing columns from this list may effectively
Add comment 111 Plus   --disable features, even if they are turned on
Add comment 112 Plus   --
Add comment 113 Plus   --Each element in this list must be one of the valid output column names. Names must be
Add comment 114 Plus   --delimited by square brackets. White space, formatting, and additional characters are
Add comment 115 Plus   --allowed, as long as the list contains exact matches of delimited valid column names.
Add comment 116 Plus   @output_column_list VARCHAR(8000) = '[dd%][session_id][sql_text][sql_command][login_name][wait_info][tasks][tran_log%][cpu%][temp%][block%][reads%][writes%][context%][physical%][query_plan][locks][%]',
Add comment 117 Plus  
Add comment 118 Plus   --Column(s) by which to sort output, optionally with sort directions.
Add comment 119 Plus   --Valid column choices:
Add comment 120 Plus   --session_id, physical_io, reads, physical_reads, writes, tempdb_allocations,
Add comment 121 Plus   --tempdb_current, CPU, context_switches, used_memory, physical_io_delta, reads_delta,
Add comment 122 Plus   --physical_reads_delta, writes_delta, tempdb_allocations_delta, tempdb_current_delta,
Add comment 123 Plus   --CPU_delta, context_switches_delta, used_memory_delta, tasks, tran_start_time,
Add comment 124 Plus   --open_tran_count, blocking_session_id, blocked_session_count, percent_complete,
Add comment 125 Plus   --host_name, login_name, database_name, start_time, login_time, program_name
Add comment 126 Plus   --
Add comment 127 Plus   --Note that column names in the list must be bracket-delimited. Commas and/or white
Add comment 128 Plus   --space are not required.
Add comment 129 Plus   @sort_order VARCHAR(500) = '[start_time] ASC',
Add comment 130 Plus  
Add comment 131 Plus   --Formats some of the output columns in a more "human readable" form
Add comment 132 Plus   --0 disables outfput format
Add comment 133 Plus   --1 formats the output for variable-width fonts
Add comment 134 Plus   --2 formats the output for fixed-width fonts
Add comment 135 Plus   @format_output TINYINT = 1,
Add comment 136 Plus  
Add comment 137 Plus   --If set to a non-blank value, the script will attempt to insert into the specified
Add comment 138 Plus   --destination table. Please note that the script will not verify that the table exists,
Add comment 139 Plus   --or that it has the correct schema, before doing the insert.
Add comment 140 Plus   --Table can be specified in one, two, or three-part format
Add comment 141 Plus   @destination_table VARCHAR(4000) = '',
Add comment 142 Plus  
Add comment 143 Plus   --If set to 1, no data collection will happen and no result set will be returned; instead,
Add comment 144 Plus   --a CREATE TABLE statement will be returned via the @schema parameter, which will match
Add comment 145 Plus   --the schema of the result set that would be returned by using the same collection of the
Add comment 146 Plus   --rest of the parameters. The CREATE TABLE statement will have a placeholder token of
Add comment 147 Plus   --<table_name> in place of an actual table name.
Add comment 148 Plus   @return_schema BIT = 0,
Add comment 149 Plus   @schema VARCHAR(MAX) = NULL OUTPUT,
Add comment 150 Plus  
Add comment 151 Plus   --Help! What do I do?
Add comment 152 Plus   @help BIT = 0
Add comment 153 Plus  --~
Add comment 154 Plus  )
Add comment 155 Plus  /*
Add comment 156 Plus  OUTPUT COLUMNS
Add comment 157 Plus  --------------
Add comment 158 Plus  Formatted/Non: [session_id] [smallint] NOT NULL
Add comment 159 Plus   Session ID (a.k.a. SPID)
Add comment 160 Plus  
Add comment 161 Plus  Formatted: [dd hh:mm:ss.mss] [varchar](15) NULL
Add comment 162 Plus  Non-Formatted: <not returned>
Add comment 163 Plus   For an active request, time the query has been running
Add comment 164 Plus   For a sleeping session, time since the last batch completed
Add comment 165 Plus  
Add comment 166 Plus  Formatted: [dd hh:mm:ss.mss (avg)] [varchar](15) NULL
Add comment 167 Plus  Non-Formatted: [avg_elapsed_time] [int] NULL
Add comment 168 Plus   (Requires @get_avg_time option)
Add comment 169 Plus   How much time has the active portion of the query taken in the past, on average?
Add comment 170 Plus  
Add comment 171 Plus  Formatted: [physical_io] [varchar](30) NULL
Add comment 172 Plus  Non-Formatted: [physical_io] [bigint] NULL
Add comment 173 Plus   Shows the number of physical I/Os, for active requests
Add comment 174 Plus  
Add comment 175 Plus  Formatted: [reads] [varchar](30) NULL
Add comment 176 Plus  Non-Formatted: [reads] [bigint] NULL
Add comment 177 Plus   For an active request, number of reads done for the current query
Add comment 178 Plus   For a sleeping session, total number of reads done over the lifetime of the session
Add comment 179 Plus  
Add comment 180 Plus  Formatted: [physical_reads] [varchar](30) NULL
Add comment 181 Plus  Non-Formatted: [physical_reads] [bigint] NULL
Add comment 182 Plus   For an active request, number of physical reads done for the current query
Add comment 183 Plus   For a sleeping session, total number of physical reads done over the lifetime of the session
Add comment 184 Plus  
Add comment 185 Plus  Formatted: [writes] [varchar](30) NULL
Add comment 186 Plus  Non-Formatted: [writes] [bigint] NULL
Add comment 187 Plus   For an active request, number of writes done for the current query
Add comment 188 Plus   For a sleeping session, total number of writes done over the lifetime of the session
Add comment 189 Plus  
Add comment 190 Plus  Formatted: [tempdb_allocations] [varchar](30) NULL
Add comment 191 Plus  Non-Formatted: [tempdb_allocations] [bigint] NULL
Add comment 192 Plus   For an active request, number of TempDB writes done for the current query
Add comment 193 Plus   For a sleeping session, total number of TempDB writes done over the lifetime of the session
Add comment 194 Plus  
Add comment 195 Plus  Formatted: [tempdb_current] [varchar](30) NULL
Add comment 196 Plus  Non-Formatted: [tempdb_current] [bigint] NULL
Add comment 197 Plus   For an active request, number of TempDB pages currently allocated for the query
Add comment 198 Plus   For a sleeping session, number of TempDB pages currently allocated for the session
Add comment 199 Plus  
Add comment 200 Plus  Formatted: [CPU] [varchar](30) NULL
Add comment 201 Plus  Non-Formatted: [CPU] [bigint] NULL
Add comment 202 Plus   For an active request, total CPU time consumed by the current query
Add comment 203 Plus   For a sleeping session, total CPU time consumed over the lifetime of the session
Add comment 204 Plus  
Add comment 205 Plus  Formatted: [context_switches] [varchar](30) NULL
Add comment 206 Plus  Non-Formatted: [context_switches] [bigint] NULL
Add comment 207 Plus   Shows the number of context switches, for active requests
Add comment 208 Plus  
Add comment 209 Plus  Formatted: [used_memory] [varchar](30) NOT NULL
Add comment 210 Plus  Non-Formatted: [used_memory] [bigint] NOT NULL
Add comment 211 Plus   For an active request, total memory consumption for the current query
Add comment 212 Plus   For a sleeping session, total current memory consumption
Add comment 213 Plus  
Add comment 214 Plus  Formatted: [max_used_memory] [varchar](30) NULL
Add comment 215 Plus  Non-Formatted: [max_used_memory] [bigint] NULL
Add comment 216 Plus   (Requires @get_memory_info = 1)
Add comment 217 Plus   For an active request, the maximum amount of memory that has been used during
Add comment 218 Plus   processing up to the point of observation for the current query
Add comment 219 Plus  
Add comment 220 Plus  Formatted: [requested_memory] [varchar](30) NULL
Add comment 221 Plus  Non-Formatted: [requested_memory] [bigint] NULL
Add comment 222 Plus   (Requires @get_memory_info = 1)
Add comment 223 Plus   For an active request, the amount of memory requested by the query processor
Add comment 224 Plus   for hash, sort, and parallelism operations
Add comment 225 Plus  
Add comment 226 Plus  Formatted: [granted_memory] [varchar](30) NULL
Add comment 227 Plus  Non-Formatted: [granted_memory] [bigint] NULL
Add comment 228 Plus   (Requires @get_memory_info = 1)
Add comment 229 Plus   For an active request, the amount of memory granted to the query processor
Add comment 230 Plus   for hash, sort, and parallelism operations
Add comment 231 Plus  
Add comment 232 Plus  Formatted: [physical_io_delta] [varchar](30) NULL
Add comment 233 Plus  Non-Formatted: [physical_io_delta] [bigint] NULL
Add comment 234 Plus   (Requires @delta_interval option)
Add comment 235 Plus   Difference between the number of physical I/Os reported on the first and second collections.
Add comment 236 Plus   If the request started after the first collection, the value will be NULL
Add comment 237 Plus  
Add comment 238 Plus  Formatted: [reads_delta] [varchar](30) NULL
Add comment 239 Plus  Non-Formatted: [reads_delta] [bigint] NULL
Add comment 240 Plus   (Requires @delta_interval option)
Add comment 241 Plus   Difference between the number of reads reported on the first and second collections.
Add comment 242 Plus   If the request started after the first collection, the value will be NULL
Add comment 243 Plus  
Add comment 244 Plus  Formatted: [physical_reads_delta] [varchar](30) NULL
Add comment 245 Plus  Non-Formatted: [physical_reads_delta] [bigint] NULL
Add comment 246 Plus   (Requires @delta_interval option)
Add comment 247 Plus   Difference between the number of physical reads reported on the first and second collections.
Add comment 248 Plus   If the request started after the first collection, the value will be NULL
Add comment 249 Plus  
Add comment 250 Plus  Formatted: [writes_delta] [varchar](30) NULL
Add comment 251 Plus  Non-Formatted: [writes_delta] [bigint] NULL
Add comment 252 Plus   (Requires @delta_interval option)
Add comment 253 Plus   Difference between the number of writes reported on the first and second collections.
Add comment 254 Plus   If the request started after the first collection, the value will be NULL
Add comment 255 Plus  
Add comment 256 Plus  Formatted: [tempdb_allocations_delta] [varchar](30) NULL
Add comment 257 Plus  Non-Formatted: [tempdb_allocations_delta] [bigint] NULL
Add comment 258 Plus   (Requires @delta_interval option)
Add comment 259 Plus   Difference between the number of TempDB writes reported on the first and second collections.
Add comment 260 Plus   If the request started after the first collection, the value will be NULL
Add comment 261 Plus  
Add comment 262 Plus  Formatted: [tempdb_current_delta] [varchar](30) NULL
Add comment 263 Plus  Non-Formatted: [tempdb_current_delta] [bigint] NULL
Add comment 264 Plus   (Requires @delta_interval option)
Add comment 265 Plus   Difference between the number of allocated TempDB pages reported on the first and second
Add comment 266 Plus   collections. If the request started after the first collection, the value will be NULL
Add comment 267 Plus  
Add comment 268 Plus  Formatted: [CPU_delta] [varchar](30) NULL
Add comment 269 Plus  Non-Formatted: [CPU_delta] [int] NULL
Add comment 270 Plus   (Requires @delta_interval option)
Add comment 271 Plus   Difference between the CPU time reported on the first and second collections.
Add comment 272 Plus   If the request started after the first collection, the value will be NULL
Add comment 273 Plus  
Add comment 274 Plus  Formatted: [context_switches_delta] [varchar](30) NULL
Add comment 275 Plus  Non-Formatted: [context_switches_delta] [bigint] NULL
Add comment 276 Plus   (Requires @delta_interval option)
Add comment 277 Plus   Difference between the context switches count reported on the first and second collections
Add comment 278 Plus   If the request started after the first collection, the value will be NULL
Add comment 279 Plus  
Add comment 280 Plus  Formatted: [used_memory_delta] [varchar](30) NULL
Add comment 281 Plus  Non-Formatted: [used_memory_delta] [bigint] NULL
Add comment 282 Plus   Difference between the memory usage reported on the first and second collections
Add comment 283 Plus   If the request started after the first collection, the value will be NULL
Add comment 284 Plus  
Add comment 285 Plus  Formatted: [max_used_memory_delta] [varchar](30) NULL
Add comment 286 Plus  Non-Formatted: [max_used_memory_delta] [bigint] NULL
Add comment 287 Plus   Difference between the max memory usage reported on the first and second collections
Add comment 288 Plus   If the request started after the first collection, the value will be NULL
Add comment 289 Plus  
Add comment 290 Plus  Formatted: [tasks] [varchar](30) NULL
Add comment 291 Plus  Non-Formatted: [tasks] [smallint] NULL
Add comment 292 Plus   Number of worker tasks currently allocated, for active requests
Add comment 293 Plus  
Add comment 294 Plus  Formatted/Non: [status] [varchar](30) NOT NULL
Add comment 295 Plus   Activity status for the session (running, sleeping, etc)
Add comment 296 Plus  
Add comment 297 Plus  Formatted/Non: [wait_info] [nvarchar](4000) NULL
Add comment 298 Plus   Aggregates wait information, in the following format:
Add comment 299 Plus   (Ax: Bms/Cms/Dms)E
Add comment 300 Plus   A is the number of waiting tasks currently waiting on resource type E. B/C/D are wait
Add comment 301 Plus   times, in milliseconds. If only one thread is waiting, its wait time will be shown as B.
Add comment 302 Plus   If two tasks are waiting, each of their wait times will be shown (B/C). If three or more
Add comment 303 Plus   tasks are waiting, the minimum, average, and maximum wait times will be shown (B/C/D).
Add comment 304 Plus   If wait type E is a page latch wait and the page is of a "special" type (e.g. PFS, GAM, SGAM),
Add comment 305 Plus   the page type will be identified.
Add comment 306 Plus   If wait type E is CXPACKET, CXCONSUMER, CXSYNC_PORT, or CXSYNC_CONSUMER the nodeId from the
Add comment 307 Plus   query plan will be identified
Add comment 308 Plus  
Add comment 309 Plus  Formatted/Non: [locks] [xml] NULL
Add comment 310 Plus   (Requires @get_locks option)
Add comment 311 Plus   Aggregates lock information, in XML format.
Add comment 312 Plus   The lock XML includes the lock mode, locked object, and aggregates the number of requests.
Add comment 313 Plus   Attempts are made to identify locked objects by name
Add comment 314 Plus  
Add comment 315 Plus  Formatted/Non: [tran_start_time] [datetime] NULL
Add comment 316 Plus   (Requires @get_transaction_info option)
Add comment 317 Plus   Date and time that the first transaction opened by a session caused a transaction log
Add comment 318 Plus   write to occur.
Add comment 319 Plus  
Add comment 320 Plus  Formatted/Non: [tran_log_writes] [nvarchar](4000) NULL
Add comment 321 Plus   (Requires @get_transaction_info option)
Add comment 322 Plus   Aggregates transaction log write information, in the following format:
Add comment 323 Plus   A:wB (C kB)
Add comment 324 Plus   A is a database that has been touched by an active transaction
Add comment 325 Plus   B is the number of log writes that have been made in the database as a result of the transaction
Add comment 326 Plus   C is the number of log kilobytes consumed by the log records
Add comment 327 Plus  
Add comment 328 Plus  Formatted/Non: [implicit_tran] [nvarchar](3) NULL
Add comment 329 Plus   (Requires @get_transaction_info option)
Add comment 330 Plus   For active read-write transactions, returns on "ON" the transaction has been started as a result
Add comment 331 Plus   of the session using the implicit_transactions option, or "OFF" otherwise.
Add comment 332 Plus  
Add comment 333 Plus  Formatted: [open_tran_count] [varchar](30) NULL
Add comment 334 Plus  Non-Formatted: [open_tran_count] [smallint] NULL
Add comment 335 Plus   Shows the number of open transactions the session has open
Add comment 336 Plus  
Add comment 337 Plus  Formatted: [sql_command] [xml] NULL
Add comment 338 Plus  Non-Formatted: [sql_command] [nvarchar](max) NULL
Add comment 339 Plus   (Requires @get_outer_command option)
Add comment 340 Plus   Shows the "outer" SQL command, i.e. the text of the batch or RPC sent to the server,
Add comment 341 Plus   if available
Add comment 342 Plus  
Add comment 343 Plus  Formatted: [sql_text] [xml] NULL
Add comment 344 Plus  Non-Formatted: [sql_text] [nvarchar](max) NULL
Add comment 345 Plus   Shows the SQL text for active requests or the last statement executed
Add comment 346 Plus   for sleeping sessions, if available in either case.
Add comment 347 Plus   If @get_full_inner_text option is set, shows the full text of the batch.
Add comment 348 Plus   Otherwise, shows only the active statement within the batch.
Add comment 349 Plus   If the query text is locked, a special timeout message will be sent, in the following format:
Add comment 350 Plus   <timeout_exceeded />
Add comment 351 Plus   If an error occurs, an error message will be sent, in the following format:
Add comment 352 Plus   <error message="message" />
Add comment 353 Plus  
Add comment 354 Plus  Formatted/Non: [query_plan] [xml] NULL
Add comment 355 Plus   (Requires @get_plans option)
Add comment 356 Plus   Shows the query plan for the request, if available.
Add comment 357 Plus   If the plan is locked, a special timeout message will be sent, in the following format:
Add comment 358 Plus   <timeout_exceeded />
Add comment 359 Plus   If an error occurs, an error message will be sent, in the following format:
Add comment 360 Plus   <error message="message" />
Add comment 361 Plus  
Add comment 362 Plus  Formatted/Non: [blocking_session_id] [smallint] NULL
Add comment 363 Plus   When applicable, shows the blocking SPID
Add comment 364 Plus  
Add comment 365 Plus  Formatted: [blocked_session_count] [varchar](30) NULL
Add comment 366 Plus  Non-Formatted: [blocked_session_count] [smallint] NULL
Add comment 367 Plus   (Requires @find_block_leaders option)
Add comment 368 Plus   The total number of SPIDs blocked by this session,
Add comment 369 Plus   all the way down the blocking chain.
Add comment 370 Plus  
Add comment 371 Plus  Formatted: [percent_complete] [varchar](30) NULL
Add comment 372 Plus  Non-Formatted: [percent_complete] [real] NULL
Add comment 373 Plus   When applicable, shows the percent complete (e.g. for backups, restores, and some rollbacks)
Add comment 374 Plus  
Add comment 375 Plus  Formatted/Non: [host_name] [sysname] NOT NULL
Add comment 376 Plus   Shows the host name for the connection
Add comment 377 Plus  
Add comment 378 Plus  Formatted/Non: [login_name] [sysname] NOT NULL
Add comment 379 Plus   Shows the login name for the connection
Add comment 380 Plus  
Add comment 381 Plus  Formatted/Non: [database_name] [sysname] NULL
Add comment 382 Plus   Shows the connected database
Add comment 383 Plus  
Add comment 384 Plus  Formatted/Non: [program_name] [sysname] NULL
Add comment 385 Plus   Shows the reported program/application name
Add comment 386 Plus  
Add comment 387 Plus  Formatted/Non: [additional_info] [xml] NULL
Add comment 388 Plus   (Requires @get_additional_info option)
Add comment 389 Plus   Returns additional non-performance-related session/request information
Add comment 390 Plus   If the script finds a SQL Agent job running, the name of the job and job step will be reported
Add comment 391 Plus   If @get_task_info = 2 and the script finds a lock wait, the locked object will be reported
Add comment 392 Plus  
Add comment 393 Plus  Formatted/Non: [start_time] [datetime] NOT NULL
Add comment 394 Plus   For active requests, shows the time the request started
Add comment 395 Plus   For sleeping sessions, shows the time the last batch completed
Add comment 396 Plus  
Add comment 397 Plus  Formatted/Non: [login_time] [datetime] NOT NULL
Add comment 398 Plus   Shows the time that the session connected
Add comment 399 Plus  
Add comment 400 Plus  Formatted/Non: [request_id] [int] NULL
Add comment 401 Plus   For active requests, shows the request_id
Add comment 402 Plus   Should be 0 unless MARS is being used
Add comment 403 Plus  
Add comment 404 Plus  Formatted/Non: [collection_time] [datetime] NOT NULL
Add comment 405 Plus   Time that this script's final SELECT ran
Add comment 406 Plus  
Add comment 407 Plus  Formatted/Non: [memory_info] [xml] NULL
Add comment 408 Plus   (Requires @get_memory_info)
Add comment 409 Plus   For active queries that require workspace memory, returns information on memory grants,
Add comment 410 Plus   resource semaphores, and the resource governor settings that are impacting the allocation.
Add comment 411 Plus  */
Add comment 412 Plus  AS
Add comment 413 Plus  BEGIN;
Add comment 414 Plus  
Add comment 415 Plus   IF(1 <> IS_MEMBER('db_owner'))
Add comment 416 Plus   BEGIN
Add comment 417 Plus   RAISERROR ('Sorry, you dont have rights to execute procedure in this database context. Please contact sql@if.se', 0, 1)
Add comment 418 Plus   RETURN;
Add comment 419 Plus   END;
Add comment 420 Plus  
Add comment 421 Plus   SET NOCOUNT ON;
Add comment 422 Plus   SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
Add comment 423 Plus   SET QUOTED_IDENTIFIER ON;
Add comment 424 Plus   SET ANSI_PADDING ON;
Add comment 425 Plus   SET CONCAT_NULL_YIELDS_NULL ON;
Add comment 426 Plus   SET ANSI_WARNINGS ON;
Add comment 427 Plus   SET NUMERIC_ROUNDABORT OFF;
Add comment 428 Plus   SET ARITHABORT ON;
Add comment 429 Plus  
Add comment 430 Plus   IF
Add comment 431 Plus   @filter IS NULL
Add comment 432 Plus   OR @filter_type IS NULL
Add comment 433 Plus   OR @not_filter IS NULL
Add comment 434 Plus   OR @not_filter_type IS NULL
Add comment 435 Plus   OR @show_own_spid IS NULL
Add comment 436 Plus   OR @show_system_spids IS NULL
Add comment 437 Plus   OR @show_sleeping_spids IS NULL
Add comment 438 Plus   OR @get_full_inner_text IS NULL
Add comment 439 Plus   OR @get_plans IS NULL
Add comment 440 Plus   OR @get_outer_command IS NULL
Add comment 441 Plus   OR @get_transaction_info IS NULL
Add comment 442 Plus   OR @get_task_info IS NULL
Add comment 443 Plus   OR @get_locks IS NULL
Add comment 444 Plus   OR @get_avg_time IS NULL
Add comment 445 Plus   OR @get_additional_info IS NULL
Add comment 446 Plus   OR @find_block_leaders IS NULL
Add comment 447 Plus   OR @delta_interval IS NULL
Add comment 448 Plus   OR @format_output IS NULL
Add comment 449 Plus   OR @output_column_list IS NULL
Add comment 450 Plus   OR @sort_order IS NULL
Add comment 451 Plus   OR @return_schema IS NULL
Add comment 452 Plus   OR @destination_table IS NULL
Add comment 453 Plus   OR @help IS NULL
Add comment 454 Plus   BEGIN;
Add comment 455 Plus   RAISERROR('Input parameters cannot be NULL', 16, 1);
Add comment 456 Plus   RETURN;
Add comment 457 Plus   END;
Add comment 458 Plus  
Add comment 459 Plus   IF @filter_type NOT IN ('session', 'program', 'database', 'login', 'host')
Add comment 460 Plus   BEGIN;
Add comment 461 Plus   RAISERROR('Valid filter types are: session, program, database, login, host', 16, 1);
Add comment 462 Plus   RETURN;
Add comment 463 Plus   END;
Add comment 464 Plus  
Add comment 465 Plus   IF @filter_type = 'session' AND @filter LIKE '%[^0123456789]%'
Add comment 466 Plus   BEGIN;
Add comment 467 Plus   RAISERROR('Session filters must be valid integers', 16, 1);
Add comment 468 Plus   RETURN;
Add comment 469 Plus   END;
Add comment 470 Plus  
Add comment 471 Plus   IF @not_filter_type NOT IN ('session', 'program', 'database', 'login', 'host')
Add comment 472 Plus   BEGIN;
Add comment 473 Plus   RAISERROR('Valid filter types are: session, program, database, login, host', 16, 1);
Add comment 474 Plus   RETURN;
Add comment 475 Plus   END;
Add comment 476 Plus  
Add comment 477 Plus   IF @not_filter_type = 'session' AND @not_filter LIKE '%[^0123456789]%'
Add comment 478 Plus   BEGIN;
Add comment 479 Plus   RAISERROR('Session filters must be valid integers', 16, 1);
Add comment 480 Plus   RETURN;
Add comment 481 Plus   END;
Add comment 482 Plus  
Add comment 483 Plus   IF @show_sleeping_spids NOT IN (0, 1, 2)
Add comment 484 Plus   BEGIN;
Add comment 485 Plus   RAISERROR('Valid values for @show_sleeping_spids are: 0, 1, or 2', 16, 1);
Add comment 486 Plus   RETURN;
Add comment 487 Plus   END;
Add comment 488 Plus  
Add comment 489 Plus   IF @get_plans NOT IN (0, 1, 2)
Add comment 490 Plus   BEGIN;
Add comment 491 Plus   RAISERROR('Valid values for @get_plans are: 0, 1, or 2', 16, 1);
Add comment 492 Plus   RETURN;
Add comment 493 Plus   END;
Add comment 494 Plus  
Add comment 495 Plus   IF @get_task_info NOT IN (0, 1, 2)
Add comment 496 Plus   BEGIN;
Add comment 497 Plus   RAISERROR('Valid values for @get_task_info are: 0, 1, or 2', 16, 1);
Add comment 498 Plus   RETURN;
Add comment 499 Plus   END;
041_sp_WhoIsActive_signature_and_rights.sql
/Deployment/041_sp_WhoIsActive_signature_and_rights.sql+29
/Deployment/041_sp_WhoIsActive_signature_and_rights.sql
Add comment 1 Plus  EXECUTE AS LOGIN = 'sa'; --fix to overcome context switching bug in Devops
Add comment 2 Plus  
Add comment 3 Plus  USE master;
Add comment 4 Plus  GO
Add comment 5 Plus  IF NOT EXISTS (SELECT * FROM sys.certificates WHERE name = 'CertViewServerState')
Add comment 6 Plus   CREATE CERTIFICATE CertViewServerState
Add comment 7 Plus   ENCRYPTION BY PASSWORD = N'BNj9wgPxBwjIPP9HpcWc'
Add comment 8 Plus   WITH SUBJECT = N'To grant permissions for procedures in master db';
Add comment 9 Plus  GO
Add comment 10 Plus  IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE name = 'CertLoginViewServerState')
Add comment 11 Plus   CREATE LOGIN CertLoginViewServerState FROM CERTIFICATE CertViewServerState;
Add comment 12 Plus  Go
Add comment 13 Plus  GRANT VIEW SERVER STATE TO CertLoginViewServerState
Add comment 14 Plus  GO
Add comment 15 Plus  
Add comment 16 Plus  IF NOT EXISTS (SELECT * FROM sys.certificates c
Add comment 17 Plus   INNER JOIN sys.crypt_properties cp ON cp.thumbprint = c.thumbprint
Add comment 18 Plus   WHERE Object_Name(cp.major_id) = 'sp_WhoIsActive')
Add comment 19 Plus  BEGIN
Add comment 20 Plus   ADD SIGNATURE TO dbo.sp_WhoIsActive
Add comment 21 Plus   BY CERTIFICATE CertViewServerState
Add comment 22 Plus   WITH PASSWORD = 'BNj9wgPxBwjIPP9HpcWc'
Add comment 23 Plus  END
Add comment 24 Plus  
Add comment 25 Plus  GO
Add comment 26 Plus  GRANT EXEC ON dbo.sp_WhoIsActive TO PUBLIC
Add comment 27 Plus  
Add comment 28 Plus  
Add comment 29 Plus  
042_WhoIsActive_Monitor.sql
/Deployment/042_WhoIsActive_Monitor.sql
/Deployment/042_WhoIsActive_Monitor.sql
050_DeadLockMonitoring.sql
/Deployment/050_DeadLockMonitoring.sql
/Deployment/050_DeadLockMonitoring.sql
051_GetDeadlocks.sql
/Deployment/051_GetDeadlocks.sql
/Deployment/051_GetDeadlocks.sql
052_DeadLock_Cleanup.sql
/Deployment/052_DeadLock_Cleanup.sql
/Deployment/052_DeadLock_Cleanup.sql
060_System_health.sql
/Deployment/060_System_health.sql
/Deployment/060_System_health.sql
080_Audit.sql
/Deployment/080_Audit.sql
/Deployment/080_Audit.sql
090_SetInstanceProperties.sql
/Deployment/090_SetInstanceProperties.sql
/Deployment/090_SetInstanceProperties.sql