From 6a1e2d7165fb279b9637d0cdd93aef7515398fa9 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 20 Mar 2018 19:35:55 +0100 Subject: [PATCH 001/188] Improved the input parameter checking for @MaxTransferSize in DatabaseBackup. --- DatabaseBackup.sql | 2 +- MaintenanceSolution.sql | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 76b0f0c5..3e8322e3 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -762,7 +762,7 @@ BEGIN SET @Error = @@ERROR END - IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR @MaxTransferSize % 65536 > 0 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL) + IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @MaxTransferSize is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index c28a9299..4fe86e29 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -1,6 +1,6 @@ /* -SQL Server Maintenance Solution - SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, and SQL Server 2016 +SQL Server Maintenance Solution - SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, and SQL Server 2017 Backup: https://ola.hallengren.com/sql-server-backup.html Integrity Check: https://ola.hallengren.com/sql-server-integrity-check.html @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 7 October, 2016. +Last updated 20 March, 2018. Ola Hallengren https://ola.hallengren.com @@ -1071,7 +1071,7 @@ BEGIN SET @Error = @@ERROR END - IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR @MaxTransferSize % 65536 > 0 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL) + IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @MaxTransferSize is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -4958,3 +4958,4 @@ BEGIN END GO + From 7d6d70f6b5eb6fffbe9cc71056fc6ea52aa601ae Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 21 Mar 2018 17:19:58 +0100 Subject: [PATCH 002/188] Fixed an issue with consistency checks on databases in availability groups in Standard Edition --- DatabaseIntegrityCheck.sql | 3 ++- MaintenanceSolution.sql | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 03cfe015..2b572d96 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -25,7 +25,7 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -724,6 +724,7 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR SERVERPROPERTY('EngineEdition') = 3) AND (@CurrentAvailabilityGroupRole = @AvailabilityGroupReplicas OR @AvailabilityGroupReplicas = 'ALL' OR @CurrentAvailabilityGroupRole IS NULL) AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 4fe86e29..34fbdb4f 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 20 March, 2018. +Last updated 21 March, 2018. Ola Hallengren https://ola.hallengren.com @@ -2146,7 +2146,7 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2845,6 +2845,7 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR SERVERPROPERTY('EngineEdition') = 3) AND (@CurrentAvailabilityGroupRole = @AvailabilityGroupReplicas OR @AvailabilityGroupReplicas = 'ALL' OR @CurrentAvailabilityGroupRole IS NULL) AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') From 3e703651daa1d0aac8c771abe71a172d1b470dc3 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 22 Mar 2018 01:15:51 +0100 Subject: [PATCH 003/188] Added a check for suspect databases in DatabaseBackup, DatabaseIntegrityCheck, and IndexOptimize --- DatabaseBackup.sql | 7 +++++++ DatabaseIntegrityCheck.sql | 7 +++++++ IndexOptimize.sql | 7 +++++++ MaintenanceSolution.sql | 23 ++++++++++++++++++++++- 4 files changed, 43 insertions(+), 1 deletion(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 3e8322e3..048d76f5 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -1746,6 +1746,13 @@ BEGIN END END + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + -- Update that the database is completed UPDATE @tmpDatabases SET Completed = 1 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 2b572d96..78f0ca58 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -997,6 +997,13 @@ BEGIN END + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + -- Update that the database is completed UPDATE @tmpDatabases SET Completed = 1 diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 1e8c42ae..748b7003 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -1488,6 +1488,13 @@ BEGIN END + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + -- Update that the database is completed UPDATE @tmpDatabases SET Completed = 1 diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 34fbdb4f..26084d95 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 21 March, 2018. +Last updated 22 March, 2018. Ola Hallengren https://ola.hallengren.com @@ -2055,6 +2055,13 @@ BEGIN END END + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + -- Update that the database is completed UPDATE @tmpDatabases SET Completed = 1 @@ -3118,6 +3125,13 @@ BEGIN END + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + -- Update that the database is completed UPDATE @tmpDatabases SET Completed = 1 @@ -4663,6 +4677,13 @@ BEGIN END + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + -- Update that the database is completed UPDATE @tmpDatabases SET Completed = 1 From 3137c0bf9fe795f93118288d8c2c52b3c48ce377 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 27 Mar 2018 18:48:55 +0200 Subject: [PATCH 004/188] Add files via upload --- DatabaseBackup.sql | 39 +++++++ DatabaseIntegrityCheck.sql | 105 +++++++++++++++++ IndexOptimize.sql | 83 ++++++++++++++ MaintenanceSolution.sql | 229 ++++++++++++++++++++++++++++++++++++- 4 files changed, 455 insertions(+), 1 deletion(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 048d76f5..38655064 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -917,6 +917,45 @@ BEGIN GOTO Logging END + ---------------------------------------------------------------------------------------------------- + --// Check that selected databases and availability groups exist //-- + ---------------------------------------------------------------------------------------------------- + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedDatabases + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(AvailabilityGroupName) + ', ' + FROM @SelectedAvailabilityGroups + WHERE AvailabilityGroupName NOT LIKE '%[%]%' + AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + ---------------------------------------------------------------------------------------------------- + --// Check @@SERVERNAME //-- + ---------------------------------------------------------------------------------------------------- + + IF @@SERVERNAME <> SERVERPROPERTY('ServerName') AND SERVERPROPERTY('IsHadrEnabled') = 1 + BEGIN + SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). Please see ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + ---------------------------------------------------------------------------------------------------- --// Check Availability Group cluster name //-- ---------------------------------------------------------------------------------------------------- diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 78f0ca58..5574c3a9 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -647,6 +647,84 @@ BEGIN GOTO Logging END + ---------------------------------------------------------------------------------------------------- + --// Check that selected databases and availability groups exist //-- + ---------------------------------------------------------------------------------------------------- + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedDatabases + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedFileGroups + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedObjects + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(AvailabilityGroupName) + ', ' + FROM @SelectedAvailabilityGroups + WHERE AvailabilityGroupName NOT LIKE '%[%]%' + AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedFileGroups + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName IN (SELECT DatabaseName FROM @tmpDatabases) + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedObjects + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName IN (SELECT DatabaseName FROM @tmpDatabases) + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + ---------------------------------------------------------------------------------------------------- --// Check Availability Group cluster name //-- ---------------------------------------------------------------------------------------------------- @@ -785,6 +863,19 @@ BEGIN WHERE SelectedFileGroups.Selected = 0 END + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + '.' + QUOTENAME(FileGroupName) + ', ' + FROM @SelectedFileGroups SelectedFileGroups + WHERE DatabaseName = @CurrentDatabaseName + AND FileGroupName NOT LIKE '%[%]%' + AND NOT EXISTS (SELECT * FROM @tmpFileGroups WHERE FileGroupName = SelectedFileGroups.FileGroupName) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following file groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + WHILE EXISTS (SELECT * FROM @tmpFileGroups WHERE Selected = 1 AND Completed = 0) BEGIN SELECT TOP 1 @CurrentFGID = ID, @@ -903,6 +994,20 @@ BEGIN WHERE SelectedObjects.Selected = 0 END + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + ', ' + FROM @SelectedObjects SelectedObjects + WHERE DatabaseName = @CurrentDatabaseName + AND SchemaName NOT LIKE '%[%]%' + AND ObjectName NOT LIKE '%[%]%' + AND NOT EXISTS (SELECT * FROM @tmpObjects WHERE SchemaName = SelectedObjects.SchemaName AND ObjectName = SelectedObjects.ObjectName) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following objects do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + WHILE EXISTS (SELECT * FROM @tmpObjects WHERE Selected = 1 AND Completed = 0) BEGIN SELECT TOP 1 @CurrentOID = ID, diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 748b7003..8cdab0eb 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -792,6 +792,59 @@ BEGIN GOTO Logging END + ---------------------------------------------------------------------------------------------------- + --// Check that selected databases and availability groups exist //-- + ---------------------------------------------------------------------------------------------------- + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedDatabases + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedIndexes + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(AvailabilityGroupName) + ', ' + FROM @SelectedAvailabilityGroups + WHERE AvailabilityGroupName NOT LIKE '%[%]%' + AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedIndexes + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName IN (SELECT DatabaseName FROM @tmpDatabases) + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + ---------------------------------------------------------------------------------------------------- --// Check Availability Group cluster name //-- ---------------------------------------------------------------------------------------------------- @@ -933,6 +986,36 @@ BEGIN WHERE SelectedIndexes.Selected = 0 END + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + ', ' + FROM @SelectedIndexes SelectedIndexes + WHERE DatabaseName = @CurrentDatabaseName + AND SchemaName NOT LIKE '%[%]%' + AND ObjectName NOT LIKE '%[%]%' + AND IndexName LIKE '%[%]%' + AND NOT EXISTS (SELECT * FROM @tmpIndexesStatistics WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + '.' + QUOTENAME(IndexName) + ', ' + FROM @SelectedIndexes SelectedIndexes + WHERE DatabaseName = @CurrentDatabaseName + AND SchemaName NOT LIKE '%[%]%' + AND ObjectName NOT LIKE '%[%]%' + AND IndexName NOT LIKE '%[%]%' + AND NOT EXISTS (SELECT * FROM @tmpIndexesStatistics WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName AND IndexName = SelectedIndexes.IndexName) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + WHILE EXISTS (SELECT * FROM @tmpIndexesStatistics WHERE Selected = 1 AND Completed = 0 AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL)) BEGIN diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 26084d95..5e8d07d5 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 22 March, 2018. +Last updated 27 March, 2018. Ola Hallengren https://ola.hallengren.com @@ -1226,6 +1226,45 @@ BEGIN GOTO Logging END + ---------------------------------------------------------------------------------------------------- + --// Check that selected databases and availability groups exist //-- + ---------------------------------------------------------------------------------------------------- + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedDatabases + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(AvailabilityGroupName) + ', ' + FROM @SelectedAvailabilityGroups + WHERE AvailabilityGroupName NOT LIKE '%[%]%' + AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + ---------------------------------------------------------------------------------------------------- + --// Check @@SERVERNAME //-- + ---------------------------------------------------------------------------------------------------- + + IF @@SERVERNAME <> SERVERPROPERTY('ServerName') AND SERVERPROPERTY('IsHadrEnabled') = 1 + BEGIN + SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). Please see ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + ---------------------------------------------------------------------------------------------------- --// Check Availability Group cluster name //-- ---------------------------------------------------------------------------------------------------- @@ -2775,6 +2814,84 @@ BEGIN GOTO Logging END + ---------------------------------------------------------------------------------------------------- + --// Check that selected databases and availability groups exist //-- + ---------------------------------------------------------------------------------------------------- + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedDatabases + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedFileGroups + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedObjects + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(AvailabilityGroupName) + ', ' + FROM @SelectedAvailabilityGroups + WHERE AvailabilityGroupName NOT LIKE '%[%]%' + AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedFileGroups + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName IN (SELECT DatabaseName FROM @tmpDatabases) + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedObjects + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName IN (SELECT DatabaseName FROM @tmpDatabases) + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + ---------------------------------------------------------------------------------------------------- --// Check Availability Group cluster name //-- ---------------------------------------------------------------------------------------------------- @@ -2913,6 +3030,19 @@ BEGIN WHERE SelectedFileGroups.Selected = 0 END + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + '.' + QUOTENAME(FileGroupName) + ', ' + FROM @SelectedFileGroups SelectedFileGroups + WHERE DatabaseName = @CurrentDatabaseName + AND FileGroupName NOT LIKE '%[%]%' + AND NOT EXISTS (SELECT * FROM @tmpFileGroups WHERE FileGroupName = SelectedFileGroups.FileGroupName) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following file groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + WHILE EXISTS (SELECT * FROM @tmpFileGroups WHERE Selected = 1 AND Completed = 0) BEGIN SELECT TOP 1 @CurrentFGID = ID, @@ -3031,6 +3161,20 @@ BEGIN WHERE SelectedObjects.Selected = 0 END + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + ', ' + FROM @SelectedObjects SelectedObjects + WHERE DatabaseName = @CurrentDatabaseName + AND SchemaName NOT LIKE '%[%]%' + AND ObjectName NOT LIKE '%[%]%' + AND NOT EXISTS (SELECT * FROM @tmpObjects WHERE SchemaName = SelectedObjects.SchemaName AND ObjectName = SelectedObjects.ObjectName) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following objects do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + WHILE EXISTS (SELECT * FROM @tmpObjects WHERE Selected = 1 AND Completed = 0) BEGIN SELECT TOP 1 @CurrentOID = ID, @@ -3981,6 +4125,59 @@ BEGIN GOTO Logging END + ---------------------------------------------------------------------------------------------------- + --// Check that selected databases and availability groups exist //-- + ---------------------------------------------------------------------------------------------------- + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedDatabases + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedIndexes + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(AvailabilityGroupName) + ', ' + FROM @SelectedAvailabilityGroups + WHERE AvailabilityGroupName NOT LIKE '%[%]%' + AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + ', ' + FROM @SelectedIndexes + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName IN (SELECT DatabaseName FROM @tmpDatabases) + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + ---------------------------------------------------------------------------------------------------- --// Check Availability Group cluster name //-- ---------------------------------------------------------------------------------------------------- @@ -4122,6 +4319,36 @@ BEGIN WHERE SelectedIndexes.Selected = 0 END + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + ', ' + FROM @SelectedIndexes SelectedIndexes + WHERE DatabaseName = @CurrentDatabaseName + AND SchemaName NOT LIKE '%[%]%' + AND ObjectName NOT LIKE '%[%]%' + AND IndexName LIKE '%[%]%' + AND NOT EXISTS (SELECT * FROM @tmpIndexesStatistics WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + SET @ErrorMessage = '' + SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + '.' + QUOTENAME(IndexName) + ', ' + FROM @SelectedIndexes SelectedIndexes + WHERE DatabaseName = @CurrentDatabaseName + AND SchemaName NOT LIKE '%[%]%' + AND ObjectName NOT LIKE '%[%]%' + AND IndexName NOT LIKE '%[%]%' + AND NOT EXISTS (SELECT * FROM @tmpIndexesStatistics WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName AND IndexName = SelectedIndexes.IndexName) + IF @@ROWCOUNT > 0 + BEGIN + SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + WHILE EXISTS (SELECT * FROM @tmpIndexesStatistics WHERE Selected = 1 AND Completed = 0 AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL)) BEGIN From 1f383ba21f654d9e5bcce387acdd016c311ae6e4 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 28 Mar 2018 13:18:15 +0200 Subject: [PATCH 005/188] Add files via upload --- DatabaseBackup.sql | 36 ++++++++++++++++++++++-------------- MaintenanceSolution.sql | 38 +++++++++++++++++++++++--------------- 2 files changed, 45 insertions(+), 29 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 38655064..1c06efa0 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -748,7 +748,7 @@ BEGIN SET @Error = @@ERROR END - IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL) + IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @BlockSize is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -762,14 +762,14 @@ BEGIN SET @Error = @@ERROR END - IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL) + IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @MaxTransferSize is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) + IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) BEGIN SET @ErrorMessage = 'The value for the parameter @NumberOfFiles is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1197,22 +1197,30 @@ BEGIN SELECT 0, 0 END ELSE + IF @URL IS NOT NULL BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + '.' + @CurrentFileExtension + SET @CurrentFileNumber = 0 - IF LEN(@CurrentFilePath) > 259 + WHILE @CurrentFileNumber < @NumberOfFiles BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + '.' + @CurrentFileExtension - END + SET @CurrentFileNumber = @CurrentFileNumber + 1 - IF LEN(@CurrentFilePath) > 259 - BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + '.' + @CurrentFileExtension - END + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) - SELECT 'URL', @CurrentFilePath, 0 + IF LEN(@CurrentFilePath) > 259 + BEGIN + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + END + + IF LEN(@CurrentFilePath) > 259 + BEGIN + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + END + + INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) + SELECT 'URL', @CurrentFilePath, 0 + END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) SELECT 0, 0 @@ -1585,6 +1593,7 @@ BEGIN IF @CurrentCommandOutput03 <> 0 SET @ReturnCode = @CurrentCommandOutput03 END + -- Verify the backup IF @CurrentCommandOutput03 = 0 AND @Verify = 'Y' BEGIN @@ -1854,6 +1863,5 @@ BEGIN ---------------------------------------------------------------------------------------------------- END - GO diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 5e8d07d5..7a4bab1a 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 27 March, 2018. +Last updated 28 March, 2018. Ola Hallengren https://ola.hallengren.com @@ -1057,7 +1057,7 @@ BEGIN SET @Error = @@ERROR END - IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL) + IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @BlockSize is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1071,14 +1071,14 @@ BEGIN SET @Error = @@ERROR END - IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL) + IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @MaxTransferSize is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) + IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) BEGIN SET @ErrorMessage = 'The value for the parameter @NumberOfFiles is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1506,22 +1506,30 @@ BEGIN SELECT 0, 0 END ELSE + IF @URL IS NOT NULL BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + '.' + @CurrentFileExtension + SET @CurrentFileNumber = 0 - IF LEN(@CurrentFilePath) > 259 + WHILE @CurrentFileNumber < @NumberOfFiles BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + '.' + @CurrentFileExtension - END + SET @CurrentFileNumber = @CurrentFileNumber + 1 - IF LEN(@CurrentFilePath) > 259 - BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + '.' + @CurrentFileExtension - END + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) - SELECT 'URL', @CurrentFilePath, 0 + IF LEN(@CurrentFilePath) > 259 + BEGIN + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + END + + IF LEN(@CurrentFilePath) > 259 + BEGIN + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + END + + INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) + SELECT 'URL', @CurrentFilePath, 0 + END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) SELECT 0, 0 @@ -1894,6 +1902,7 @@ BEGIN IF @CurrentCommandOutput03 <> 0 SET @ReturnCode = @CurrentCommandOutput03 END + -- Verify the backup IF @CurrentCommandOutput03 = 0 AND @Verify = 'Y' BEGIN @@ -2163,7 +2172,6 @@ BEGIN ---------------------------------------------------------------------------------------------------- END - GO SET ANSI_NULLS ON GO From 428b8074fd368ef87872272a94c765bebc66a058 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 30 Mar 2018 17:04:43 +0200 Subject: [PATCH 006/188] Add files via upload --- CommandExecute.sql | 9 +++++-- DatabaseBackup.sql | 11 +++++--- DatabaseIntegrityCheck.sql | 9 +++++-- IndexOptimize.sql | 18 ++++++------- MaintenanceSolution.sql | 54 ++++++++++++++++++++++---------------- 5 files changed, 61 insertions(+), 40 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index a96b7ef8..ccb77135 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -2,7 +2,12 @@ GO SET QUOTED_IDENTIFIER ON GO -CREATE PROCEDURE [dbo].[CommandExecute] +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CommandExecute]') AND type in (N'P', N'PC')) +BEGIN +EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[CommandExecute] AS' +END +GO +ALTER PROCEDURE [dbo].[CommandExecute] @Command nvarchar(max), @CommandType nvarchar(max), @@ -25,7 +30,7 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 1c06efa0..513c487c 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -2,7 +2,12 @@ GO SET QUOTED_IDENTIFIER ON GO -CREATE PROCEDURE [dbo].[DatabaseBackup] +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DatabaseBackup]') AND type in (N'P', N'PC')) +BEGIN +EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[DatabaseBackup] AS' +END +GO +ALTER PROCEDURE [dbo].[DatabaseBackup] @Databases nvarchar(max) = NULL, @Directory nvarchar(max) = NULL, @@ -46,7 +51,7 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -327,7 +332,7 @@ BEGIN SELECT [name] AS DatabaseName, LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster) THEN 1 ELSE 0 END AS AvailabilityGroup, + CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id) THEN 1 ELSE 0 END AS AvailabilityGroup, 0 AS Selected, 0 AS Completed FROM sys.databases diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 5574c3a9..28d0b7c8 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -2,7 +2,12 @@ GO SET QUOTED_IDENTIFIER ON GO -CREATE PROCEDURE [dbo].[DatabaseIntegrityCheck] +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DatabaseIntegrityCheck]') AND type in (N'P', N'PC')) +BEGIN +EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[DatabaseIntegrityCheck] AS' +END +GO +ALTER PROCEDURE [dbo].[DatabaseIntegrityCheck] @Databases nvarchar(max) = NULL, @CheckCommands nvarchar(max) = 'CHECKDB', @@ -271,7 +276,7 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster) THEN 1 ELSE 0 END AS AvailabilityGroup, + CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id) THEN 1 ELSE 0 END AS AvailabilityGroup, CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], 0 AS Selected, 0 AS Completed diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 8cdab0eb..7c1bc479 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -2,7 +2,12 @@ GO SET QUOTED_IDENTIFIER ON GO -CREATE PROCEDURE [dbo].[IndexOptimize] +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[IndexOptimize]') AND type in (N'P', N'PC')) +BEGIN +EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[IndexOptimize] AS' +END +GO +ALTER PROCEDURE [dbo].[IndexOptimize] @Databases nvarchar(max) = NULL, @FragmentationLow nvarchar(max) = NULL, @@ -37,7 +42,7 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -262,13 +267,6 @@ BEGIN SET @Error = @@ERROR END - IF SERVERPROPERTY('EngineEdition') = 5 AND @Version < 12 - BEGIN - SET @ErrorMessage = 'The stored procedure IndexOptimize is not supported on this version of Azure SQL Database.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - SET @Error = @@ERROR - END - IF @Error <> 0 BEGIN SET @ReturnCode = @Error @@ -335,7 +333,7 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster) THEN 1 ELSE 0 END AS AvailabilityGroup, + CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id) THEN 1 ELSE 0 END AS AvailabilityGroup, 0 AS Selected, 0 AS Completed FROM sys.databases diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 7a4bab1a..2d4a9643 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 28 March, 2018. +Last updated 30 March, 2018. Ola Hallengren https://ola.hallengren.com @@ -89,11 +89,6 @@ VALUES('DatabaseName', DB_NAME(DB_ID())) INSERT INTO #Config ([Name], [Value]) VALUES('Error', CAST(@Error AS nvarchar)) -IF OBJECT_ID('[dbo].[DatabaseBackup]') IS NOT NULL DROP PROCEDURE [dbo].[DatabaseBackup] -IF OBJECT_ID('[dbo].[DatabaseIntegrityCheck]') IS NOT NULL DROP PROCEDURE [dbo].[DatabaseIntegrityCheck] -IF OBJECT_ID('[dbo].[IndexOptimize]') IS NOT NULL DROP PROCEDURE [dbo].[IndexOptimize] -IF OBJECT_ID('[dbo].[CommandExecute]') IS NOT NULL DROP PROCEDURE [dbo].[CommandExecute] - IF OBJECT_ID('[dbo].[CommandLog]') IS NULL AND OBJECT_ID('[dbo].[PK_CommandLog]') IS NULL BEGIN CREATE TABLE [dbo].[CommandLog]( @@ -120,7 +115,12 @@ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -CREATE PROCEDURE [dbo].[CommandExecute] +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CommandExecute]') AND type in (N'P', N'PC')) +BEGIN +EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[CommandExecute] AS' +END +GO +ALTER PROCEDURE [dbo].[CommandExecute] @Command nvarchar(max), @CommandType nvarchar(max), @@ -143,7 +143,7 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -311,7 +311,12 @@ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -CREATE PROCEDURE [dbo].[DatabaseBackup] +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DatabaseBackup]') AND type in (N'P', N'PC')) +BEGIN +EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[DatabaseBackup] AS' +END +GO +ALTER PROCEDURE [dbo].[DatabaseBackup] @Databases nvarchar(max) = NULL, @Directory nvarchar(max) = NULL, @@ -355,7 +360,7 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -636,7 +641,7 @@ BEGIN SELECT [name] AS DatabaseName, LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster) THEN 1 ELSE 0 END AS AvailabilityGroup, + CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id) THEN 1 ELSE 0 END AS AvailabilityGroup, 0 AS Selected, 0 AS Completed FROM sys.databases @@ -2177,7 +2182,12 @@ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -CREATE PROCEDURE [dbo].[DatabaseIntegrityCheck] +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DatabaseIntegrityCheck]') AND type in (N'P', N'PC')) +BEGIN +EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[DatabaseIntegrityCheck] AS' +END +GO +ALTER PROCEDURE [dbo].[DatabaseIntegrityCheck] @Databases nvarchar(max) = NULL, @CheckCommands nvarchar(max) = 'CHECKDB', @@ -2446,7 +2456,7 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster) THEN 1 ELSE 0 END AS AvailabilityGroup, + CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id) THEN 1 ELSE 0 END AS AvailabilityGroup, CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], 0 AS Selected, 0 AS Completed @@ -3343,7 +3353,12 @@ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -CREATE PROCEDURE [dbo].[IndexOptimize] +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[IndexOptimize]') AND type in (N'P', N'PC')) +BEGIN +EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[IndexOptimize] AS' +END +GO +ALTER PROCEDURE [dbo].[IndexOptimize] @Databases nvarchar(max) = NULL, @FragmentationLow nvarchar(max) = NULL, @@ -3378,7 +3393,7 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3603,13 +3618,6 @@ BEGIN SET @Error = @@ERROR END - IF SERVERPROPERTY('EngineEdition') = 5 AND @Version < 12 - BEGIN - SET @ErrorMessage = 'The stored procedure IndexOptimize is not supported on this version of Azure SQL Database.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - SET @Error = @@ERROR - END - IF @Error <> 0 BEGIN SET @ReturnCode = @Error @@ -3676,7 +3684,7 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster) THEN 1 ELSE 0 END AS AvailabilityGroup, + CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id) THEN 1 ELSE 0 END AS AvailabilityGroup, 0 AS Selected, 0 AS Completed FROM sys.databases From 6ccdfda2c8d5427ec7dfe5eb3034d74502b6ed8f Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 30 Mar 2018 20:18:16 +0200 Subject: [PATCH 007/188] Add files via upload --- DatabaseBackup.sql | 6 +++--- DatabaseIntegrityCheck.sql | 4 ++-- IndexOptimize.sql | 4 ++-- MaintenanceSolution.sql | 14 +++++++------- 4 files changed, 14 insertions(+), 14 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 513c487c..41cb347d 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -384,7 +384,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 + IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -464,7 +464,7 @@ BEGIN END - IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -956,7 +956,7 @@ BEGIN IF @@SERVERNAME <> SERVERPROPERTY('ServerName') AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). Please see ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 28d0b7c8..02aabb98 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -327,7 +327,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 + IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -407,7 +407,7 @@ BEGIN END - IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 7c1bc479..fc449559 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -384,7 +384,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 + IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -464,7 +464,7 @@ BEGIN END - IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 2d4a9643..ac81612e 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -693,7 +693,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 + IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -773,7 +773,7 @@ BEGIN END - IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1265,7 +1265,7 @@ BEGIN IF @@SERVERNAME <> SERVERPROPERTY('ServerName') AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). Please see ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END @@ -2507,7 +2507,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 + IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -2587,7 +2587,7 @@ BEGIN END - IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -3735,7 +3735,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 + IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -3815,7 +3815,7 @@ BEGIN END - IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT From ace2c3741a65c0417c88ab761e5f826d85582295 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 31 Mar 2018 12:25:34 +0200 Subject: [PATCH 008/188] Add files via upload --- DatabaseBackup.sql | 60 ++++++++++++++++++++++++++++----------- MaintenanceSolution.sql | 62 +++++++++++++++++++++++++++++------------ 2 files changed, 87 insertions(+), 35 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 41cb347d..ab0c252e 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -62,6 +62,8 @@ BEGIN DECLARE @ErrorMessage nvarchar(max) DECLARE @Version numeric(18,10) + DECLARE @HostPlatform nvarchar(max) + DECLARE @DirectorySeparator nvarchar(max) DECLARE @AmazonRDS bit DECLARE @Cluster nvarchar(max) @@ -182,6 +184,16 @@ BEGIN SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) + IF @Version >= 14 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END + ELSE + BEGIN + SET @HostPlatform = 'Windows' + END + SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -192,6 +204,7 @@ BEGIN SET @StartMessage = @StartMessage + 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + CHAR(13) + CHAR(10) SET @StartMessage = @StartMessage + 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + CHAR(13) + CHAR(10) SET @StartMessage = @StartMessage + 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + CHAR(13) + CHAR(10) + SET @StartMessage = @StartMessage + 'Platform: ' + @HostPlatform + CHAR(13) + CHAR(10) SET @StartMessage = @StartMessage + 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + CHAR(13) + CHAR(10) SET @StartMessage = @StartMessage + 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL') @@ -521,13 +534,18 @@ BEGIN --// Select directories //-- ---------------------------------------------------------------------------------------------------- - IF @Directory IS NULL AND @URL IS NULL + IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Windows' BEGIN EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultDirectory OUTPUT INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) SELECT 1, @DefaultDirectory, 0, 0 END + IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Linux' + BEGIN + INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) + SELECT 1, '.', 0, 0 + END ELSE BEGIN SET @Directory = REPLACE(@Directory, CHAR(10), '') @@ -595,7 +613,7 @@ BEGIN SET @DirectoryCheck = 1 - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%') OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) BEGIN SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -603,7 +621,7 @@ BEGIN SET @DirectoryCheck = 0 END - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%') OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -683,7 +701,7 @@ BEGIN SET @Error = @@ERROR END - IF @CleanupTime < 0 OR (@CleanupTime IS NOT NULL AND @URL IS NOT NULL) + IF @CleanupTime < 0 OR (@CleanupTime IS NOT NULL AND @URL IS NOT NULL) OR (@CleanupTime IS NOT NULL AND @HostPlatform = 'Linux') BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -718,7 +736,7 @@ BEGIN SET @Error = @@ERROR END - IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE') + IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN SET @ErrorMessage = 'The value for the parameter @BackupSoftware is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1160,8 +1178,14 @@ BEGIN WHEN @BackupSoftware = 'SQLSAFE' AND @CurrentBackupType = 'LOG' THEN 'safe' END + SELECT @DirectorySeparator = CASE + WHEN @URL IS NOT NULL THEN '/' + WHEN @HostPlatform = 'Windows' THEN '\' + WHEN @HostPlatform = 'Linux' THEN '/' + END + INSERT INTO @CurrentDirectories (ID, DirectoryPath, Mirror, DirectoryNumber, CreateCompleted, CleanupCompleted) - SELECT ROW_NUMBER() OVER (ORDER BY ID), DirectoryPath + CASE WHEN RIGHT(DirectoryPath,1) = '\' THEN '' ELSE '\' END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '\' + @CurrentDatabaseNameFS + '\' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END, Mirror, ROW_NUMBER() OVER (PARTITION BY Mirror ORDER BY ID ASC), 0, 0 + SELECT ROW_NUMBER() OVER (ORDER BY ID), DirectoryPath + CASE WHEN RIGHT(DirectoryPath,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + @DirectorySeparator + @CurrentDatabaseNameFS + @DirectorySeparator + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END, Mirror, ROW_NUMBER() OVER (PARTITION BY Mirror ORDER BY ID ASC), 0, 0 FROM @Directories ORDER BY ID ASC @@ -1179,16 +1203,16 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 0) AND Mirror = 0 - SET @CurrentFilePath = @CurrentDirectoryPath + '\' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + '\' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + '\' + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) @@ -1211,16 +1235,16 @@ BEGIN BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) @@ -1245,16 +1269,16 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) AND Mirror = 1 - SET @CurrentFilePath = @CurrentDirectoryPath + '\' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + '\' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + '\' + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) @@ -1269,7 +1293,7 @@ BEGIN END -- Create directory - WHILE EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateCompleted = 0) + WHILE EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateCompleted = 0) AND @HostPlatform = 'Windows' BEGIN SELECT TOP 1 @CurrentDirectoryID = ID, @CurrentDirectoryPath = DirectoryPath @@ -1333,6 +1357,7 @@ BEGIN -- Delete old backup files, before backup IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateOutput <> 0 OR CreateOutput IS NULL) + AND @HostPlatform = 'Windows' AND @CurrentBackupType = @BackupType BEGIN WHILE EXISTS (SELECT * FROM @CurrentDirectories WHERE CleanupDate IS NOT NULL AND CleanupMode = 'BEFORE_BACKUP' AND CleanupCompleted = 0) @@ -1396,7 +1421,7 @@ BEGIN END -- Perform a backup - IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateOutput <> 0 OR CreateOutput IS NULL) + IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateOutput <> 0 OR CreateOutput IS NULL) OR @HostPlatform = 'Linux' BEGIN IF @BackupSoftware IS NULL BEGIN @@ -1736,6 +1761,7 @@ BEGIN -- Delete old backup files, after backup IF ((@CurrentCommandOutput03 = 0 AND @Verify = 'N') OR (@CurrentCommandOutput03 = 0 AND @Verify = 'Y' AND NOT EXISTS (SELECT * FROM @CurrentBackupSet WHERE VerifyOutput <> 0 OR VerifyOutput IS NULL))) + AND @HostPlatform = 'Windows' AND @CurrentBackupType = @BackupType BEGIN WHILE EXISTS (SELECT * FROM @CurrentDirectories WHERE CleanupDate IS NOT NULL AND CleanupMode = 'AFTER_BACKUP' AND CleanupCompleted = 0) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index ac81612e..b2643801 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 30 March, 2018. +Last updated 31 March, 2018. Ola Hallengren https://ola.hallengren.com @@ -371,6 +371,8 @@ BEGIN DECLARE @ErrorMessage nvarchar(max) DECLARE @Version numeric(18,10) + DECLARE @HostPlatform nvarchar(max) + DECLARE @DirectorySeparator nvarchar(max) DECLARE @AmazonRDS bit DECLARE @Cluster nvarchar(max) @@ -491,6 +493,16 @@ BEGIN SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) + IF @Version >= 14 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END + ELSE + BEGIN + SET @HostPlatform = 'Windows' + END + SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -501,6 +513,7 @@ BEGIN SET @StartMessage = @StartMessage + 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + CHAR(13) + CHAR(10) SET @StartMessage = @StartMessage + 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + CHAR(13) + CHAR(10) SET @StartMessage = @StartMessage + 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + CHAR(13) + CHAR(10) + SET @StartMessage = @StartMessage + 'Platform: ' + @HostPlatform + CHAR(13) + CHAR(10) SET @StartMessage = @StartMessage + 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + CHAR(13) + CHAR(10) SET @StartMessage = @StartMessage + 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL') @@ -830,13 +843,18 @@ BEGIN --// Select directories //-- ---------------------------------------------------------------------------------------------------- - IF @Directory IS NULL AND @URL IS NULL + IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Windows' BEGIN EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultDirectory OUTPUT INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) SELECT 1, @DefaultDirectory, 0, 0 END + IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Linux' + BEGIN + INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) + SELECT 1, '.', 0, 0 + END ELSE BEGIN SET @Directory = REPLACE(@Directory, CHAR(10), '') @@ -904,7 +922,7 @@ BEGIN SET @DirectoryCheck = 1 - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%') OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) BEGIN SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -912,7 +930,7 @@ BEGIN SET @DirectoryCheck = 0 END - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%') OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -992,7 +1010,7 @@ BEGIN SET @Error = @@ERROR END - IF @CleanupTime < 0 OR (@CleanupTime IS NOT NULL AND @URL IS NOT NULL) + IF @CleanupTime < 0 OR (@CleanupTime IS NOT NULL AND @URL IS NOT NULL) OR (@CleanupTime IS NOT NULL AND @HostPlatform = 'Linux') BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1027,7 +1045,7 @@ BEGIN SET @Error = @@ERROR END - IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE') + IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN SET @ErrorMessage = 'The value for the parameter @BackupSoftware is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1469,8 +1487,14 @@ BEGIN WHEN @BackupSoftware = 'SQLSAFE' AND @CurrentBackupType = 'LOG' THEN 'safe' END + SELECT @DirectorySeparator = CASE + WHEN @URL IS NOT NULL THEN '/' + WHEN @HostPlatform = 'Windows' THEN '\' + WHEN @HostPlatform = 'Linux' THEN '/' + END + INSERT INTO @CurrentDirectories (ID, DirectoryPath, Mirror, DirectoryNumber, CreateCompleted, CleanupCompleted) - SELECT ROW_NUMBER() OVER (ORDER BY ID), DirectoryPath + CASE WHEN RIGHT(DirectoryPath,1) = '\' THEN '' ELSE '\' END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '\' + @CurrentDatabaseNameFS + '\' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END, Mirror, ROW_NUMBER() OVER (PARTITION BY Mirror ORDER BY ID ASC), 0, 0 + SELECT ROW_NUMBER() OVER (ORDER BY ID), DirectoryPath + CASE WHEN RIGHT(DirectoryPath,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + @DirectorySeparator + @CurrentDatabaseNameFS + @DirectorySeparator + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END, Mirror, ROW_NUMBER() OVER (PARTITION BY Mirror ORDER BY ID ASC), 0, 0 FROM @Directories ORDER BY ID ASC @@ -1488,16 +1512,16 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 0) AND Mirror = 0 - SET @CurrentFilePath = @CurrentDirectoryPath + '\' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + '\' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + '\' + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) @@ -1520,16 +1544,16 @@ BEGIN BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = '/' THEN '' ELSE '/' END + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) @@ -1554,16 +1578,16 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) AND Mirror = 1 - SET @CurrentFilePath = @CurrentDirectoryPath + '\' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + '\' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + '\' + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) @@ -1578,7 +1602,7 @@ BEGIN END -- Create directory - WHILE EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateCompleted = 0) + WHILE EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateCompleted = 0) AND @HostPlatform = 'Windows' BEGIN SELECT TOP 1 @CurrentDirectoryID = ID, @CurrentDirectoryPath = DirectoryPath @@ -1642,6 +1666,7 @@ BEGIN -- Delete old backup files, before backup IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateOutput <> 0 OR CreateOutput IS NULL) + AND @HostPlatform = 'Windows' AND @CurrentBackupType = @BackupType BEGIN WHILE EXISTS (SELECT * FROM @CurrentDirectories WHERE CleanupDate IS NOT NULL AND CleanupMode = 'BEFORE_BACKUP' AND CleanupCompleted = 0) @@ -1705,7 +1730,7 @@ BEGIN END -- Perform a backup - IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateOutput <> 0 OR CreateOutput IS NULL) + IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateOutput <> 0 OR CreateOutput IS NULL) OR @HostPlatform = 'Linux' BEGIN IF @BackupSoftware IS NULL BEGIN @@ -2045,6 +2070,7 @@ BEGIN -- Delete old backup files, after backup IF ((@CurrentCommandOutput03 = 0 AND @Verify = 'N') OR (@CurrentCommandOutput03 = 0 AND @Verify = 'Y' AND NOT EXISTS (SELECT * FROM @CurrentBackupSet WHERE VerifyOutput <> 0 OR VerifyOutput IS NULL))) + AND @HostPlatform = 'Windows' AND @CurrentBackupType = @BackupType BEGIN WHILE EXISTS (SELECT * FROM @CurrentDirectories WHERE CleanupDate IS NOT NULL AND CleanupMode = 'AFTER_BACKUP' AND CleanupCompleted = 0) From 71fe57ff6094753b37b8332a6a1c97144863133e Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 31 Mar 2018 12:36:34 +0200 Subject: [PATCH 009/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e4fd9b2b..927bd55d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # sql-server-maintenance-solution -Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, and SQL Server 2017 (on Windows) +Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, and SQL Server 2017
  • Backup: https://ola.hallengren.com/sql-server-backup.html
  • From 952b939af6753a0d517d1b2b3990b6e292365673 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 1 Apr 2018 15:33:19 +0200 Subject: [PATCH 010/188] Add files via upload --- CommandLog.sql | 41 +++++++++++++++++++++----------------- MaintenanceSolution.sql | 44 ++++++++++++++++++++++++----------------- 2 files changed, 49 insertions(+), 36 deletions(-) diff --git a/CommandLog.sql b/CommandLog.sql index 9f8faa1b..241a4cde 100644 --- a/CommandLog.sql +++ b/CommandLog.sql @@ -2,25 +2,30 @@ GO SET QUOTED_IDENTIFIER ON GO -SET ANSI_PADDING ON -GO +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CommandLog]') AND type in (N'U')) +BEGIN CREATE TABLE [dbo].[CommandLog]( -[ID] int IDENTITY(1,1) NOT NULL CONSTRAINT [PK_CommandLog] PRIMARY KEY CLUSTERED, -[DatabaseName] sysname NULL, -[SchemaName] sysname NULL, -[ObjectName] sysname NULL, -[ObjectType] char(2) NULL, -[IndexName] sysname NULL, -[IndexType] tinyint NULL, -[StatisticsName] sysname NULL, -[PartitionNumber] int NULL, -[ExtendedInfo] xml NULL, -[Command] nvarchar(max) NOT NULL, -[CommandType] nvarchar(60) NOT NULL, -[StartTime] datetime NOT NULL, -[EndTime] datetime NULL, -[ErrorNumber] int NULL, -[ErrorMessage] nvarchar(max) NULL + [ID] [int] IDENTITY(1,1) NOT NULL, + [DatabaseName] [sysname] NULL, + [SchemaName] [sysname] NULL, + [ObjectName] [sysname] NULL, + [ObjectType] [char](2) NULL, + [IndexName] [sysname] NULL, + [IndexType] [tinyint] NULL, + [StatisticsName] [sysname] NULL, + [PartitionNumber] [int] NULL, + [ExtendedInfo] [xml] NULL, + [Command] [nvarchar](max) NOT NULL, + [CommandType] [nvarchar](60) NOT NULL, + [StartTime] [datetime] NOT NULL, + [EndTime] [datetime] NULL, + [ErrorNumber] [int] NULL, + [ErrorMessage] [nvarchar](max) NULL, + CONSTRAINT [PK_CommandLog] PRIMARY KEY CLUSTERED +( + [ID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ) +END GO diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index b2643801..57960318 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -88,26 +88,34 @@ VALUES('DatabaseName', DB_NAME(DB_ID())) INSERT INTO #Config ([Name], [Value]) VALUES('Error', CAST(@Error AS nvarchar)) - -IF OBJECT_ID('[dbo].[CommandLog]') IS NULL AND OBJECT_ID('[dbo].[PK_CommandLog]') IS NULL +GO +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CommandLog]') AND type in (N'U')) BEGIN CREATE TABLE [dbo].[CommandLog]( -[ID] int IDENTITY(1,1) NOT NULL CONSTRAINT [PK_CommandLog] PRIMARY KEY CLUSTERED, -[DatabaseName] sysname NULL, -[SchemaName] sysname NULL, -[ObjectName] sysname NULL, -[ObjectType] char(2) NULL, -[IndexName] sysname NULL, -[IndexType] tinyint NULL, -[StatisticsName] sysname NULL, -[PartitionNumber] int NULL, -[ExtendedInfo] xml NULL, -[Command] nvarchar(max) NOT NULL, -[CommandType] nvarchar(60) NOT NULL, -[StartTime] datetime NOT NULL, -[EndTime] datetime NULL, -[ErrorNumber] int NULL, -[ErrorMessage] nvarchar(max) NULL + [ID] [int] IDENTITY(1,1) NOT NULL, + [DatabaseName] [sysname] NULL, + [SchemaName] [sysname] NULL, + [ObjectName] [sysname] NULL, + [ObjectType] [char](2) NULL, + [IndexName] [sysname] NULL, + [IndexType] [tinyint] NULL, + [StatisticsName] [sysname] NULL, + [PartitionNumber] [int] NULL, + [ExtendedInfo] [xml] NULL, + [Command] [nvarchar](max) NOT NULL, + [CommandType] [nvarchar](60) NOT NULL, + [StartTime] [datetime] NOT NULL, + [EndTime] [datetime] NULL, + [ErrorNumber] [int] NULL, + [ErrorMessage] [nvarchar](max) NULL, + CONSTRAINT [PK_CommandLog] PRIMARY KEY CLUSTERED +( + [ID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ) END GO From 9abd07fdab1aee9bad40b22b6b8a7a9505ee8a38 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 2 Apr 2018 12:12:09 +0200 Subject: [PATCH 011/188] Add files via upload --- IndexOptimize.sql | 3 +-- MaintenanceSolution.sql | 5 ++--- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/IndexOptimize.sql b/IndexOptimize.sql index fc449559..855c0a20 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -938,7 +938,6 @@ BEGIN IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_partition_stats dm_db_partition_stats ON indexes.[object_id] = dm_db_partition_stats.[object_id] AND indexes.[index_id] = dm_db_partition_stats.[index_id] AND partitions.partition_id = dm_db_partition_stats.partition_id' IF @PartitionLevel = 'N' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN (SELECT dm_db_partition_stats.[object_id], dm_db_partition_stats.[index_id], SUM(dm_db_partition_stats.in_row_data_page_count) AS in_row_data_page_count FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_partition_stats dm_db_partition_stats GROUP BY dm_db_partition_stats.[object_id], dm_db_partition_stats.[index_id]) dm_db_partition_stats ON indexes.[object_id] = dm_db_partition_stats.[object_id] AND indexes.[index_id] = dm_db_partition_stats.[index_id]' SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0' - IF (@UpdateStatistics NOT IN('ALL','INDEX') OR @UpdateStatistics IS NULL) AND @PageCountLevel > 0 SET @CurrentCommand01 = @CurrentCommand01 + ' AND (dm_db_partition_stats.in_row_data_page_count >= @ParamPageCountLevel OR dm_db_partition_stats.in_row_data_page_count IS NULL)' IF NOT EXISTS(SELECT * FROM @ActionsPreferred) SET @CurrentCommand01 = @CurrentCommand01 + ' AND stats.stats_id IS NOT NULL' END @@ -953,7 +952,7 @@ BEGIN IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', PartitionNumber ASC' INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, StatisticsID, StatisticsName, PartitionID, PartitionNumber, PartitionCount, Selected, Completed) - EXECUTE sp_executesql @statement = @CurrentCommand01, @params = N'@ParamPageCountLevel int', @ParamPageCountLevel = @PageCountLevel + EXECUTE sp_executesql @statement = @CurrentCommand01 SET @Error = @@ERROR IF @Error <> 0 BEGIN diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 57960318..205c2772 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 31 March, 2018. +Last updated 2 April, 2018. Ola Hallengren https://ola.hallengren.com @@ -4323,7 +4323,6 @@ BEGIN IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_partition_stats dm_db_partition_stats ON indexes.[object_id] = dm_db_partition_stats.[object_id] AND indexes.[index_id] = dm_db_partition_stats.[index_id] AND partitions.partition_id = dm_db_partition_stats.partition_id' IF @PartitionLevel = 'N' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN (SELECT dm_db_partition_stats.[object_id], dm_db_partition_stats.[index_id], SUM(dm_db_partition_stats.in_row_data_page_count) AS in_row_data_page_count FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_partition_stats dm_db_partition_stats GROUP BY dm_db_partition_stats.[object_id], dm_db_partition_stats.[index_id]) dm_db_partition_stats ON indexes.[object_id] = dm_db_partition_stats.[object_id] AND indexes.[index_id] = dm_db_partition_stats.[index_id]' SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0' - IF (@UpdateStatistics NOT IN('ALL','INDEX') OR @UpdateStatistics IS NULL) AND @PageCountLevel > 0 SET @CurrentCommand01 = @CurrentCommand01 + ' AND (dm_db_partition_stats.in_row_data_page_count >= @ParamPageCountLevel OR dm_db_partition_stats.in_row_data_page_count IS NULL)' IF NOT EXISTS(SELECT * FROM @ActionsPreferred) SET @CurrentCommand01 = @CurrentCommand01 + ' AND stats.stats_id IS NOT NULL' END @@ -4338,7 +4337,7 @@ BEGIN IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', PartitionNumber ASC' INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, StatisticsID, StatisticsName, PartitionID, PartitionNumber, PartitionCount, Selected, Completed) - EXECUTE sp_executesql @statement = @CurrentCommand01, @params = N'@ParamPageCountLevel int', @ParamPageCountLevel = @PageCountLevel + EXECUTE sp_executesql @statement = @CurrentCommand01 SET @Error = @@ERROR IF @Error <> 0 BEGIN From c1d5ce857b0fd02fb24ca80c913ef2d74f27b4e7 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 2 Apr 2018 22:49:32 +0200 Subject: [PATCH 012/188] Add files via upload --- CommandExecute.sql | 25 ++- DatabaseBackup.sql | 123 ++++++++++---- DatabaseIntegrityCheck.sql | 85 +++++++--- IndexOptimize.sql | 85 +++++++--- MaintenanceSolution.sql | 318 +++++++++++++++++++++++++++---------- 5 files changed, 474 insertions(+), 162 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index ccb77135..de98f9ee 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -123,12 +123,20 @@ BEGIN SET @StartTime = GETDATE() SET @StartTimeSec = CONVERT(datetime,CONVERT(nvarchar,@StartTime,120),120) - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTimeSec,120) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Command: ' + @Command - IF @Comment IS NOT NULL SET @StartMessage = @StartMessage + CHAR(13) + CHAR(10) + 'Comment: ' + @Comment + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTimeSec,120) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Command: ' + @Command SET @StartMessage = REPLACE(@StartMessage,'%','%%') RAISERROR(@StartMessage,10,1) WITH NOWAIT + IF @Comment IS NOT NULL + BEGIN + SET @StartMessage = 'Comment: ' + @Comment + SET @StartMessage = REPLACE(@StartMessage,'%','%%') + RAISERROR(@StartMessage,10,1) WITH NOWAIT + END + IF @LogToTable = 'Y' BEGIN INSERT INTO dbo.CommandLog (DatabaseName, SchemaName, ObjectName, ObjectType, IndexName, IndexType, StatisticsName, PartitionNumber, ExtendedInfo, CommandType, Command, StartTime) @@ -169,10 +177,13 @@ BEGIN SET @EndTime = GETDATE() SET @EndTimeSec = CONVERT(datetime,CONVERT(varchar,@EndTime,120),120) - SET @EndMessage = 'Outcome: ' + CASE WHEN @Execute = 'N' THEN 'Not Executed' WHEN @Error = 0 THEN 'Succeeded' ELSE 'Failed' END + CHAR(13) + CHAR(10) - SET @EndMessage = @EndMessage + 'Duration: ' + CASE WHEN DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) > 0 THEN CAST(DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) AS nvarchar) + '.' ELSE '' END + CONVERT(nvarchar,@EndTimeSec - @StartTimeSec,108) + CHAR(13) + CHAR(10) - SET @EndMessage = @EndMessage + 'Date and time: ' + CONVERT(nvarchar,@EndTimeSec,120) + CHAR(13) + CHAR(10) + ' ' - SET @EndMessage = REPLACE(@EndMessage,'%','%%') + SET @EndMessage = 'Outcome: ' + CASE WHEN @Execute = 'N' THEN 'Not Executed' WHEN @Error = 0 THEN 'Succeeded' ELSE 'Failed' END + RAISERROR(@EndMessage,10,1) WITH NOWAIT + + SET @EndMessage = 'Duration: ' + CASE WHEN DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) > 0 THEN CAST(DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) AS nvarchar) + '.' ELSE '' END + CONVERT(nvarchar,@EndTimeSec - @StartTimeSec,108) + RAISERROR(@EndMessage,10,1) WITH NOWAIT + + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTimeSec,120) + CHAR(13) + CHAR(10) + ' ' RAISERROR(@EndMessage,10,1) WITH NOWAIT IF @LogToTable = 'Y' diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index ab0c252e..07cc5cf0 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -200,13 +200,25 @@ BEGIN --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Platform: ' + @HostPlatform + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Platform: ' + @HostPlatform + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @BackupType = ' + ISNULL('''' + REPLACE(@BackupType,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @Verify = ' + ISNULL('''' + REPLACE(@Verify,'''','''''') + '''','NULL') @@ -241,9 +253,11 @@ BEGIN SET @StartMessage = @StartMessage + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) - SET @StartMessage = REPLACE(@StartMessage,'%','%%') + ' ' + SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @StartMessage = REPLACE(@StartMessage,'%','%%') + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@StartMessage,10,1) WITH NOWAIT ---------------------------------------------------------------------------------------------------- @@ -1113,28 +1127,77 @@ BEGIN EXECUTE sp_executesql @statement = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT END - -- Set database message - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Database: ' + QUOTENAME(@CurrentDatabaseName) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + CHAR(13) + CHAR(10) - IF @CurrentIsDatabaseAccessible IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Encrypted: ' + CASE WHEN @CurrentIsEncrypted = 1 THEN 'Yes' WHEN @CurrentIsEncrypted = 0 THEN 'No' ELSE 'N/A' END + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Availability group: ' + @CurrentAvailabilityGroup + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Availability group role: ' + @CurrentAvailabilityGroupRole + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Availability group backup preference: ' + @CurrentAvailabilityGroupBackupPreference + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Is preferred backup replica: ' + CASE WHEN @CurrentIsPreferredBackupReplica = 1 THEN 'Yes' WHEN @CurrentIsPreferredBackupReplica = 0 THEN 'No' ELSE 'N/A' END + CHAR(13) + CHAR(10) - IF @CurrentDatabaseMirroringRole IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Database mirroring role: ' + @CurrentDatabaseMirroringRole + CHAR(13) + CHAR(10) - IF @CurrentLogShippingRole IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Log shipping role: ' + @CurrentLogShippingRole + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Differential base LSN: ' + ISNULL(CAST(@CurrentDifferentialBaseLSN AS nvarchar),'N/A') + CHAR(13) + CHAR(10) - IF @CurrentBackupType = 'DIFF' SET @DatabaseMessage = @DatabaseMessage + 'Differential base is snapshot: ' + CASE WHEN @CurrentDifferentialBaseIsSnapshot = 1 THEN 'Yes' WHEN @CurrentDifferentialBaseIsSnapshot = 0 THEN 'No' ELSE 'N/A' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') + CHAR(13) + CHAR(10) - SET @DatabaseMessage = REPLACE(@DatabaseMessage,'%','%%') + ' ' + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + IF @CurrentIsDatabaseAccessible IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Encrypted: ' + CASE WHEN @CurrentIsEncrypted = 1 THEN 'Yes' WHEN @CurrentIsEncrypted = 0 THEN 'No' ELSE 'N/A' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + IF @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group backup preference: ' + @CurrentAvailabilityGroupBackupPreference + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Is preferred backup replica: ' + CASE WHEN @CurrentIsPreferredBackupReplica = 1 THEN 'Yes' WHEN @CurrentIsPreferredBackupReplica = 0 THEN 'No' ELSE 'N/A' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + IF @CurrentDatabaseMirroringRole IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + IF @CurrentLogShippingRole IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Log shipping role: ' + @CurrentLogShippingRole + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + SET @DatabaseMessage = 'Differential base LSN: ' + ISNULL(CAST(@CurrentDifferentialBaseLSN AS nvarchar),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + IF @CurrentBackupType = 'DIFF' + BEGIN + SET @DatabaseMessage = 'Differential base is snapshot: ' + CASE WHEN @CurrentDifferentialBaseIsSnapshot = 1 THEN 'Yes' WHEN @CurrentDifferentialBaseIsSnapshot = 0 THEN 'No' ELSE 'N/A' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + RAISERROR('',10,1) WITH NOWAIT + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) AND DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 0 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 02aabb98..8737ea4b 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -154,12 +154,22 @@ BEGIN --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @CheckCommands = ' + ISNULL('''' + REPLACE(@CheckCommands,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @PhysicalOnly = ' + ISNULL('''' + REPLACE(@PhysicalOnly,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @NoIndex = ' + ISNULL('''' + REPLACE(@NoIndex,'''','''''') + '''','NULL') @@ -173,9 +183,11 @@ BEGIN SET @StartMessage = @StartMessage + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @StartMessage = @StartMessage + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) - SET @StartMessage = REPLACE(@StartMessage,'%','%%') + ' ' + SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @StartMessage = REPLACE(@StartMessage,'%','%%') + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@StartMessage,10,1) WITH NOWAIT ---------------------------------------------------------------------------------------------------- @@ -790,21 +802,50 @@ BEGIN FROM sys.databases WHERE name = @CurrentDatabaseName - -- Set database message - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Database: ' + QUOTENAME(@CurrentDatabaseName) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + CHAR(13) + CHAR(10) - IF @CurrentIsDatabaseAccessible IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Availability group: ' + @CurrentAvailabilityGroup + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Availability group role: ' + @CurrentAvailabilityGroupRole + CHAR(13) + CHAR(10) - IF @CurrentDatabaseMirroringRole IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Database mirroring role: ' + @CurrentDatabaseMirroringRole + CHAR(13) + CHAR(10) - SET @DatabaseMessage = REPLACE(@DatabaseMessage,'%','%%') + ' ' + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + IF @CurrentIsDatabaseAccessible IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + IF @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + IF @CurrentDatabaseMirroringRole IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + RAISERROR('',10,1) WITH NOWAIT + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR SERVERPROPERTY('EngineEdition') = 3) diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 855c0a20..ebab3525 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -206,12 +206,22 @@ BEGIN SET @StartTime = CONVERT(datetime,CONVERT(nvarchar,GETDATE(),120),120) - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @FragmentationLow = ' + ISNULL('''' + REPLACE(@FragmentationLow,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @FragmentationMedium = ' + ISNULL('''' + REPLACE(@FragmentationMedium,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @FragmentationHigh = ' + ISNULL('''' + REPLACE(@FragmentationHigh,'''','''''') + '''','NULL') @@ -237,9 +247,11 @@ BEGIN SET @StartMessage = @StartMessage + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @StartMessage = @StartMessage + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) - SET @StartMessage = REPLACE(@StartMessage,'%','%%') + ' ' + SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @StartMessage = REPLACE(@StartMessage,'%','%%') + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@StartMessage,10,1) WITH NOWAIT ---------------------------------------------------------------------------------------------------- @@ -903,21 +915,50 @@ BEGIN FROM sys.databases WHERE name = @CurrentDatabaseName - -- Set database message - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Database: ' + QUOTENAME(@CurrentDatabaseName) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + CHAR(13) + CHAR(10) - IF @CurrentIsDatabaseAccessible IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Availability group: ' + @CurrentAvailabilityGroup + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Availability group role: ' + @CurrentAvailabilityGroupRole + CHAR(13) + CHAR(10) - IF @CurrentDatabaseMirroringRole IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Database mirroring role: ' + @CurrentDatabaseMirroringRole + CHAR(13) + CHAR(10) - SET @DatabaseMessage = REPLACE(@DatabaseMessage,'%','%%') + ' ' + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + IF @CurrentIsDatabaseAccessible IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + IF @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + IF @CurrentDatabaseMirroringRole IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + RAISERROR('',10,1) WITH NOWAIT + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) AND DATABASEPROPERTYEX(@CurrentDatabaseName,'Updateability') = 'READ_WRITE' diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 205c2772..dce4472a 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -244,12 +244,20 @@ BEGIN SET @StartTime = GETDATE() SET @StartTimeSec = CONVERT(datetime,CONVERT(nvarchar,@StartTime,120),120) - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTimeSec,120) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Command: ' + @Command - IF @Comment IS NOT NULL SET @StartMessage = @StartMessage + CHAR(13) + CHAR(10) + 'Comment: ' + @Comment + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTimeSec,120) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Command: ' + @Command SET @StartMessage = REPLACE(@StartMessage,'%','%%') RAISERROR(@StartMessage,10,1) WITH NOWAIT + IF @Comment IS NOT NULL + BEGIN + SET @StartMessage = 'Comment: ' + @Comment + SET @StartMessage = REPLACE(@StartMessage,'%','%%') + RAISERROR(@StartMessage,10,1) WITH NOWAIT + END + IF @LogToTable = 'Y' BEGIN INSERT INTO dbo.CommandLog (DatabaseName, SchemaName, ObjectName, ObjectType, IndexName, IndexType, StatisticsName, PartitionNumber, ExtendedInfo, CommandType, Command, StartTime) @@ -290,10 +298,13 @@ BEGIN SET @EndTime = GETDATE() SET @EndTimeSec = CONVERT(datetime,CONVERT(varchar,@EndTime,120),120) - SET @EndMessage = 'Outcome: ' + CASE WHEN @Execute = 'N' THEN 'Not Executed' WHEN @Error = 0 THEN 'Succeeded' ELSE 'Failed' END + CHAR(13) + CHAR(10) - SET @EndMessage = @EndMessage + 'Duration: ' + CASE WHEN DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) > 0 THEN CAST(DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) AS nvarchar) + '.' ELSE '' END + CONVERT(nvarchar,@EndTimeSec - @StartTimeSec,108) + CHAR(13) + CHAR(10) - SET @EndMessage = @EndMessage + 'Date and time: ' + CONVERT(nvarchar,@EndTimeSec,120) + CHAR(13) + CHAR(10) + ' ' - SET @EndMessage = REPLACE(@EndMessage,'%','%%') + SET @EndMessage = 'Outcome: ' + CASE WHEN @Execute = 'N' THEN 'Not Executed' WHEN @Error = 0 THEN 'Succeeded' ELSE 'Failed' END + RAISERROR(@EndMessage,10,1) WITH NOWAIT + + SET @EndMessage = 'Duration: ' + CASE WHEN DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) > 0 THEN CAST(DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) AS nvarchar) + '.' ELSE '' END + CONVERT(nvarchar,@EndTimeSec - @StartTimeSec,108) + RAISERROR(@EndMessage,10,1) WITH NOWAIT + + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTimeSec,120) + CHAR(13) + CHAR(10) + ' ' RAISERROR(@EndMessage,10,1) WITH NOWAIT IF @LogToTable = 'Y' @@ -517,13 +528,25 @@ BEGIN --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Platform: ' + @HostPlatform + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Platform: ' + @HostPlatform + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @BackupType = ' + ISNULL('''' + REPLACE(@BackupType,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @Verify = ' + ISNULL('''' + REPLACE(@Verify,'''','''''') + '''','NULL') @@ -558,9 +581,11 @@ BEGIN SET @StartMessage = @StartMessage + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) - SET @StartMessage = REPLACE(@StartMessage,'%','%%') + ' ' + SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @StartMessage = REPLACE(@StartMessage,'%','%%') + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@StartMessage,10,1) WITH NOWAIT ---------------------------------------------------------------------------------------------------- @@ -1430,28 +1455,77 @@ BEGIN EXECUTE sp_executesql @statement = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT END - -- Set database message - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Database: ' + QUOTENAME(@CurrentDatabaseName) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + CHAR(13) + CHAR(10) - IF @CurrentIsDatabaseAccessible IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Encrypted: ' + CASE WHEN @CurrentIsEncrypted = 1 THEN 'Yes' WHEN @CurrentIsEncrypted = 0 THEN 'No' ELSE 'N/A' END + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Availability group: ' + @CurrentAvailabilityGroup + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Availability group role: ' + @CurrentAvailabilityGroupRole + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Availability group backup preference: ' + @CurrentAvailabilityGroupBackupPreference + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Is preferred backup replica: ' + CASE WHEN @CurrentIsPreferredBackupReplica = 1 THEN 'Yes' WHEN @CurrentIsPreferredBackupReplica = 0 THEN 'No' ELSE 'N/A' END + CHAR(13) + CHAR(10) - IF @CurrentDatabaseMirroringRole IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Database mirroring role: ' + @CurrentDatabaseMirroringRole + CHAR(13) + CHAR(10) - IF @CurrentLogShippingRole IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Log shipping role: ' + @CurrentLogShippingRole + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Differential base LSN: ' + ISNULL(CAST(@CurrentDifferentialBaseLSN AS nvarchar),'N/A') + CHAR(13) + CHAR(10) - IF @CurrentBackupType = 'DIFF' SET @DatabaseMessage = @DatabaseMessage + 'Differential base is snapshot: ' + CASE WHEN @CurrentDifferentialBaseIsSnapshot = 1 THEN 'Yes' WHEN @CurrentDifferentialBaseIsSnapshot = 0 THEN 'No' ELSE 'N/A' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') + CHAR(13) + CHAR(10) - SET @DatabaseMessage = REPLACE(@DatabaseMessage,'%','%%') + ' ' + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + IF @CurrentIsDatabaseAccessible IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Encrypted: ' + CASE WHEN @CurrentIsEncrypted = 1 THEN 'Yes' WHEN @CurrentIsEncrypted = 0 THEN 'No' ELSE 'N/A' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + IF @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group backup preference: ' + @CurrentAvailabilityGroupBackupPreference + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Is preferred backup replica: ' + CASE WHEN @CurrentIsPreferredBackupReplica = 1 THEN 'Yes' WHEN @CurrentIsPreferredBackupReplica = 0 THEN 'No' ELSE 'N/A' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + IF @CurrentDatabaseMirroringRole IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + IF @CurrentLogShippingRole IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Log shipping role: ' + @CurrentLogShippingRole + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + SET @DatabaseMessage = 'Differential base LSN: ' + ISNULL(CAST(@CurrentDifferentialBaseLSN AS nvarchar),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + IF @CurrentBackupType = 'DIFF' + BEGIN + SET @DatabaseMessage = 'Differential base is snapshot: ' + CASE WHEN @CurrentDifferentialBaseIsSnapshot = 1 THEN 'Yes' WHEN @CurrentDifferentialBaseIsSnapshot = 0 THEN 'No' ELSE 'N/A' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + RAISERROR('',10,1) WITH NOWAIT + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) AND DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 0 @@ -2368,12 +2442,22 @@ BEGIN --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @CheckCommands = ' + ISNULL('''' + REPLACE(@CheckCommands,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @PhysicalOnly = ' + ISNULL('''' + REPLACE(@PhysicalOnly,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @NoIndex = ' + ISNULL('''' + REPLACE(@NoIndex,'''','''''') + '''','NULL') @@ -2387,9 +2471,11 @@ BEGIN SET @StartMessage = @StartMessage + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @StartMessage = @StartMessage + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) - SET @StartMessage = REPLACE(@StartMessage,'%','%%') + ' ' + SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @StartMessage = REPLACE(@StartMessage,'%','%%') + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@StartMessage,10,1) WITH NOWAIT ---------------------------------------------------------------------------------------------------- @@ -3004,21 +3090,50 @@ BEGIN FROM sys.databases WHERE name = @CurrentDatabaseName - -- Set database message - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Database: ' + QUOTENAME(@CurrentDatabaseName) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + CHAR(13) + CHAR(10) - IF @CurrentIsDatabaseAccessible IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Availability group: ' + @CurrentAvailabilityGroup + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Availability group role: ' + @CurrentAvailabilityGroupRole + CHAR(13) + CHAR(10) - IF @CurrentDatabaseMirroringRole IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Database mirroring role: ' + @CurrentDatabaseMirroringRole + CHAR(13) + CHAR(10) - SET @DatabaseMessage = REPLACE(@DatabaseMessage,'%','%%') + ' ' + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + IF @CurrentIsDatabaseAccessible IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + IF @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + IF @CurrentDatabaseMirroringRole IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + RAISERROR('',10,1) WITH NOWAIT + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR SERVERPROPERTY('EngineEdition') = 3) @@ -3591,12 +3706,22 @@ BEGIN SET @StartTime = CONVERT(datetime,CONVERT(nvarchar,GETDATE(),120),120) - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @FragmentationLow = ' + ISNULL('''' + REPLACE(@FragmentationLow,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @FragmentationMedium = ' + ISNULL('''' + REPLACE(@FragmentationMedium,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @FragmentationHigh = ' + ISNULL('''' + REPLACE(@FragmentationHigh,'''','''''') + '''','NULL') @@ -3622,9 +3747,11 @@ BEGIN SET @StartMessage = @StartMessage + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @StartMessage = @StartMessage + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + CHAR(13) + CHAR(10) - SET @StartMessage = @StartMessage + 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) - SET @StartMessage = REPLACE(@StartMessage,'%','%%') + ' ' + SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @StartMessage = REPLACE(@StartMessage,'%','%%') + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@StartMessage,10,1) WITH NOWAIT ---------------------------------------------------------------------------------------------------- @@ -4288,21 +4415,50 @@ BEGIN FROM sys.databases WHERE name = @CurrentDatabaseName - -- Set database message - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Database: ' + QUOTENAME(@CurrentDatabaseName) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + CHAR(13) + CHAR(10) - IF @CurrentIsDatabaseAccessible IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END + CHAR(13) + CHAR(10) - SET @DatabaseMessage = @DatabaseMessage + 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Availability group: ' + @CurrentAvailabilityGroup + CHAR(13) + CHAR(10) - IF @CurrentAvailabilityGroup IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Availability group role: ' + @CurrentAvailabilityGroupRole + CHAR(13) + CHAR(10) - IF @CurrentDatabaseMirroringRole IS NOT NULL SET @DatabaseMessage = @DatabaseMessage + 'Database mirroring role: ' + @CurrentDatabaseMirroringRole + CHAR(13) + CHAR(10) - SET @DatabaseMessage = REPLACE(@DatabaseMessage,'%','%%') + ' ' + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + IF @CurrentIsDatabaseAccessible IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + IF @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + IF @CurrentDatabaseMirroringRole IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + RAISERROR('',10,1) WITH NOWAIT + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) AND DATABASEPROPERTYEX(@CurrentDatabaseName,'Updateability') = 'READ_WRITE' From e4fa32869198bcfce49c75f36c40cfd1cabe2673 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 5 Apr 2018 21:19:38 +0200 Subject: [PATCH 013/188] Add files via upload --- DatabaseBackup.sql | 10 ++++++++++ MaintenanceSolution.sql | 12 +++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 07cc5cf0..9f1f5342 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -43,6 +43,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @MirrorCleanupMode nvarchar(max) = 'AFTER_BACKUP', @AvailabilityGroups nvarchar(max) = NULL, @Updateability nvarchar(max) = 'ALL', +@AdaptiveCompression nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -252,6 +253,7 @@ BEGIN SET @StartMessage = @StartMessage + ', @MirrorCleanupMode = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') + SET @StartMessage = @StartMessage + ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = REPLACE(@StartMessage,'%','%%') @@ -932,6 +934,13 @@ BEGIN SET @Error = @@ERROR END + IF @AdaptiveCompression NOT IN('SIZE','SPEED') OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) + BEGIN + SET @ErrorMessage = 'The value for the parameter @AdaptiveCompression is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1581,6 +1590,7 @@ BEGIN SET @CurrentCommand03 = @CurrentCommand03 + '''' IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ', @read_write_filegroups = 1' IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) + IF @AdaptiveCompression IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @adaptivecompression = ''' + CASE WHEN @AdaptiveCompression = 'SIZE' THEN 'Size' WHEN @AdaptiveCompression = 'SPEED' THEN 'Speed' END + '''' IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @buffercount = ' + CAST(@BufferCount AS nvarchar) IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @maxtransfersize = ' + CAST(@MaxTransferSize AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @threads = ' + CAST(@Threads AS nvarchar) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index dce4472a..41074795 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 2 April, 2018. +Last updated 5 April, 2018. Ola Hallengren https://ola.hallengren.com @@ -371,6 +371,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @MirrorCleanupMode nvarchar(max) = 'AFTER_BACKUP', @AvailabilityGroups nvarchar(max) = NULL, @Updateability nvarchar(max) = 'ALL', +@AdaptiveCompression nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -580,6 +581,7 @@ BEGIN SET @StartMessage = @StartMessage + ', @MirrorCleanupMode = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') + SET @StartMessage = @StartMessage + ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = REPLACE(@StartMessage,'%','%%') @@ -1260,6 +1262,13 @@ BEGIN SET @Error = @@ERROR END + IF @AdaptiveCompression NOT IN('SIZE','SPEED') OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) + BEGIN + SET @ErrorMessage = 'The value for the parameter @AdaptiveCompression is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1909,6 +1918,7 @@ BEGIN SET @CurrentCommand03 = @CurrentCommand03 + '''' IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ', @read_write_filegroups = 1' IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) + IF @AdaptiveCompression IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @adaptivecompression = ''' + CASE WHEN @AdaptiveCompression = 'SIZE' THEN 'Size' WHEN @AdaptiveCompression = 'SPEED' THEN 'Speed' END + '''' IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @buffercount = ' + CAST(@BufferCount AS nvarchar) IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @maxtransfersize = ' + CAST(@MaxTransferSize AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @threads = ' + CAST(@Threads AS nvarchar) From afa0bc394c21075ab883f7830cd7f60314d73250 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 9 Apr 2018 14:26:38 +0200 Subject: [PATCH 014/188] Add files via upload --- MaintenanceSolution.sql | 438 ++++++++++++++++++++-------------------- 1 file changed, 224 insertions(+), 214 deletions(-) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 41074795..271db6b6 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 5 April, 2018. +Last updated 9 April, 2018. Ola Hallengren https://ola.hallengren.com @@ -26,8 +26,6 @@ DECLARE @BackupDirectory nvarchar(max) DECLARE @CleanupTime int DECLARE @OutputFileDirectory nvarchar(max) DECLARE @LogToTable nvarchar(max) -DECLARE @Version numeric(18,10) -DECLARE @Error int SET @CreateJobs = 'Y' -- Specify whether jobs should be created. SET @BackupDirectory = N'C:\Backup' -- Specify the backup root directory. @@ -35,14 +33,9 @@ SET @CleanupTime = NULL -- Time in hours, after which backup fil SET @OutputFileDirectory = NULL -- Specify the output file directory. If no directory is specified, then the SQL Server error log directory is used. SET @LogToTable = 'Y' -- Log commands to a table. -SET @Error = 0 - -SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) - -IF IS_SRVROLEMEMBER('sysadmin') = 0 +IF IS_SRVROLEMEMBER('sysadmin') = 0 AND NOT (DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa') BEGIN - RAISERROR('You need to be a member of the SysAdmin server role to install the solution.',16,1) - SET @Error = @@ERROR + RAISERROR('You need to be a member of the SysAdmin server role to install the SQL Server Maintenance Solution.',16,1) END IF OBJECT_ID('tempdb..#Config') IS NOT NULL DROP TABLE #Config @@ -50,44 +43,12 @@ IF OBJECT_ID('tempdb..#Config') IS NOT NULL DROP TABLE #Config CREATE TABLE #Config ([Name] nvarchar(max), [Value] nvarchar(max)) -IF @CreateJobs = 'Y' AND @OutputFileDirectory IS NULL AND SERVERPROPERTY('EngineEdition') <> 4 AND @Version < 12 -BEGIN - IF @Version >= 11 - BEGIN - SELECT @OutputFileDirectory = [path] - FROM sys.dm_os_server_diagnostics_log_configurations - END - ELSE - BEGIN - SELECT @OutputFileDirectory = LEFT(CAST(SERVERPROPERTY('ErrorLogFileName') AS nvarchar(max)),LEN(CAST(SERVERPROPERTY('ErrorLogFileName') AS nvarchar(max))) - CHARINDEX('\',REVERSE(CAST(SERVERPROPERTY('ErrorLogFileName') AS nvarchar(max))))) - END -END - -IF @CreateJobs = 'Y' AND RIGHT(@OutputFileDirectory,1) = '\' AND SERVERPROPERTY('EngineEdition') <> 4 -BEGIN - SET @OutputFileDirectory = LEFT(@OutputFileDirectory, LEN(@OutputFileDirectory) - 1) -END - -INSERT INTO #Config ([Name], [Value]) -VALUES('CreateJobs', @CreateJobs) - -INSERT INTO #Config ([Name], [Value]) -VALUES('BackupDirectory', @BackupDirectory) - -INSERT INTO #Config ([Name], [Value]) -VALUES('CleanupTime', @CleanupTime) - -INSERT INTO #Config ([Name], [Value]) -VALUES('OutputFileDirectory', @OutputFileDirectory) - -INSERT INTO #Config ([Name], [Value]) -VALUES('LogToTable', @LogToTable) - -INSERT INTO #Config ([Name], [Value]) -VALUES('DatabaseName', DB_NAME(DB_ID())) - -INSERT INTO #Config ([Name], [Value]) -VALUES('Error', CAST(@Error AS nvarchar)) +INSERT INTO #Config ([Name], [Value]) VALUES('CreateJobs', @CreateJobs) +INSERT INTO #Config ([Name], [Value]) VALUES('BackupDirectory', @BackupDirectory) +INSERT INTO #Config ([Name], [Value]) VALUES('CleanupTime', @CleanupTime) +INSERT INTO #Config ([Name], [Value]) VALUES('OutputFileDirectory', @OutputFileDirectory) +INSERT INTO #Config ([Name], [Value]) VALUES('LogToTable', @LogToTable) +INSERT INTO #Config ([Name], [Value]) VALUES('DatabaseName', DB_NAME(DB_ID())) GO SET ANSI_NULLS ON GO @@ -5168,10 +5129,7 @@ BEGIN END GO - -IF (SELECT CAST([Value] AS int) FROM #Config WHERE Name = 'Error') = 0 -AND (SELECT [Value] FROM #Config WHERE Name = 'CreateJobs') = 'Y' -AND SERVERPROPERTY('EngineEdition') <> 4 +IF (SELECT [Value] FROM #Config WHERE Name = 'CreateJobs') = 'Y' AND SERVERPROPERTY('EngineEdition') <> 4 AND (IS_SRVROLEMEMBER('sysadmin') = 1 OR (DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa')) BEGIN DECLARE @BackupDirectory nvarchar(max) @@ -5181,6 +5139,10 @@ BEGIN DECLARE @DatabaseName nvarchar(max) DECLARE @Version numeric(18,10) + DECLARE @HostPlatform nvarchar(max) + DECLARE @AmazonRDS bit + DECLARE @DirectorySeparator nvarchar(max) + DECLARE @LogDirectory nvarchar(max) DECLARE @TokenServer nvarchar(max) DECLARE @TokenJobID nvarchar(max) @@ -5193,44 +5155,48 @@ BEGIN DECLARE @JobCategory nvarchar(max) DECLARE @JobOwner nvarchar(max) - DECLARE @JobName01 nvarchar(max) - DECLARE @JobName02 nvarchar(max) - DECLARE @JobName03 nvarchar(max) - DECLARE @JobName04 nvarchar(max) - DECLARE @JobName05 nvarchar(max) - DECLARE @JobName06 nvarchar(max) - DECLARE @JobName07 nvarchar(max) - DECLARE @JobName08 nvarchar(max) - DECLARE @JobName09 nvarchar(max) - DECLARE @JobName10 nvarchar(max) - DECLARE @JobName11 nvarchar(max) - - DECLARE @JobCommand01 nvarchar(max) - DECLARE @JobCommand02 nvarchar(max) - DECLARE @JobCommand03 nvarchar(max) - DECLARE @JobCommand04 nvarchar(max) - DECLARE @JobCommand05 nvarchar(max) - DECLARE @JobCommand06 nvarchar(max) - DECLARE @JobCommand07 nvarchar(max) - DECLARE @JobCommand08 nvarchar(max) - DECLARE @JobCommand09 nvarchar(max) - DECLARE @JobCommand10 nvarchar(max) - DECLARE @JobCommand11 nvarchar(max) - - DECLARE @OutputFile01 nvarchar(max) - DECLARE @OutputFile02 nvarchar(max) - DECLARE @OutputFile03 nvarchar(max) - DECLARE @OutputFile04 nvarchar(max) - DECLARE @OutputFile05 nvarchar(max) - DECLARE @OutputFile06 nvarchar(max) - DECLARE @OutputFile07 nvarchar(max) - DECLARE @OutputFile08 nvarchar(max) - DECLARE @OutputFile09 nvarchar(max) - DECLARE @OutputFile10 nvarchar(max) - DECLARE @OutputFile11 nvarchar(max) + DECLARE @Jobs TABLE (JobID int IDENTITY, + [Name] nvarchar(max), + CommandTSQL nvarchar(max), + CommandCmdExec nvarchar(max), + DatabaseName varchar(max), + OutputFileNamePart01 nvarchar(max), + OutputFileNamePart02 nvarchar(max), + Selected bit DEFAULT 0, + Completed bit DEFAULT 0) + + DECLARE @CurrentJobID int + DECLARE @CurrentJobName nvarchar(max) + DECLARE @CurrentCommandTSQL nvarchar(max) + DECLARE @CurrentCommandCmdExec nvarchar(max) + DECLARE @CurrentDatabaseName nvarchar(max) + DECLARE @CurrentOutputFileNamePart01 nvarchar(max) + DECLARE @CurrentOutputFileNamePart02 nvarchar(max) + + DECLARE @CurrentJobStepCommand nvarchar(max) + DECLARE @CurrentJobStepSubSystem nvarchar(max) + DECLARE @CurrentJobStepDatabaseName nvarchar(max) + DECLARE @CurrentOutputFileName nvarchar(max) SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) + SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + + IF @Version >= 14 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END + ELSE + BEGIN + SET @HostPlatform = 'Windows' + END + + SELECT @DirectorySeparator = CASE + WHEN @HostPlatform = 'Windows' THEN '\' + WHEN @HostPlatform = 'Linux' THEN '/' + END + IF @Version >= 9.002047 BEGIN SET @TokenServer = '$' + '(ESCAPE_SQUOTE(SRVR))' @@ -5248,7 +5214,7 @@ BEGIN SET @TokenTime = '$' + '(STRTTM)' END - IF @Version >= 12 + IF @Version >= 12 AND @HostPlatform = 'Windows' BEGIN SET @TokenLogDirectory = '$' + '(ESCAPE_SQUOTE(SQLLOGDIR))' END @@ -5257,9 +5223,12 @@ BEGIN FROM #Config WHERE [Name] = 'BackupDirectory' - SELECT @CleanupTime = Value - FROM #Config - WHERE [Name] = 'CleanupTime' + IF @HostPlatform = 'Windows' + BEGIN + SELECT @CleanupTime = Value + FROM #Config + WHERE [Name] = 'CleanupTime' + END SELECT @OutputFileDirectory = Value FROM #Config @@ -5273,151 +5242,192 @@ BEGIN FROM #Config WHERE [Name] = 'DatabaseName' - SET @JobDescription = 'Source: https://ola.hallengren.com' - SET @JobCategory = 'Database Maintenance' - SET @JobOwner = SUSER_SNAME(0x01) - - SET @JobName01 = 'DatabaseBackup - SYSTEM_DATABASES - FULL' - SET @JobCommand01 = 'sqlcmd -E -S ' + @TokenServer + ' -d ' + @DatabaseName + ' -Q "EXECUTE [dbo].[DatabaseBackup] @Databases = ''SYSTEM_DATABASES'', @Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') + ', @BackupType = ''FULL'', @Verify = ''Y'', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') + ', @CheckSum = ''Y''' + CASE WHEN @LogToTable = 'Y' THEN ', @LogToTable = ''Y''' ELSE '' END + '" -b' - SET @OutputFile01 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + 'DatabaseBackup_' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile01) > 200 SET @OutputFile01 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile01) > 200 SET @OutputFile01 = NULL - - SET @JobName02 = 'DatabaseBackup - USER_DATABASES - DIFF' - SET @JobCommand02 = 'sqlcmd -E -S ' + @TokenServer + ' -d ' + @DatabaseName + ' -Q "EXECUTE [dbo].[DatabaseBackup] @Databases = ''USER_DATABASES'', @Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') + ', @BackupType = ''DIFF'', @Verify = ''Y'', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') + ', @CheckSum = ''Y''' + CASE WHEN @LogToTable = 'Y' THEN ', @LogToTable = ''Y''' ELSE '' END + '" -b' - SET @OutputFile02 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + 'DatabaseBackup_' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile02) > 200 SET @OutputFile02 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile02) > 200 SET @OutputFile02 = NULL - - SET @JobName03 = 'DatabaseBackup - USER_DATABASES - FULL' - SET @JobCommand03 = 'sqlcmd -E -S ' + @TokenServer + ' -d ' + @DatabaseName + ' -Q "EXECUTE [dbo].[DatabaseBackup] @Databases = ''USER_DATABASES'', @Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') + ', @BackupType = ''FULL'', @Verify = ''Y'', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') + ', @CheckSum = ''Y''' + CASE WHEN @LogToTable = 'Y' THEN ', @LogToTable = ''Y''' ELSE '' END + '" -b' - SET @OutputFile03 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + 'DatabaseBackup_' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile03) > 200 SET @OutputFile03 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile03) > 200 SET @OutputFile03 = NULL - - SET @JobName04 = 'DatabaseBackup - USER_DATABASES - LOG' - SET @JobCommand04 = 'sqlcmd -E -S ' + @TokenServer + ' -d ' + @DatabaseName + ' -Q "EXECUTE [dbo].[DatabaseBackup] @Databases = ''USER_DATABASES'', @Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') + ', @BackupType = ''LOG'', @Verify = ''Y'', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') + ', @CheckSum = ''Y''' + CASE WHEN @LogToTable = 'Y' THEN ', @LogToTable = ''Y''' ELSE '' END + '" -b' - SET @OutputFile04 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + 'DatabaseBackup_' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile04) > 200 SET @OutputFile04 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile04) > 200 SET @OutputFile04 = NULL - - SET @JobName05 = 'DatabaseIntegrityCheck - SYSTEM_DATABASES' - SET @JobCommand05 = 'sqlcmd -E -S ' + @TokenServer + ' -d ' + @DatabaseName + ' -Q "EXECUTE [dbo].[DatabaseIntegrityCheck] @Databases = ''SYSTEM_DATABASES''' + CASE WHEN @LogToTable = 'Y' THEN ', @LogToTable = ''Y''' ELSE '' END + '" -b' - SET @OutputFile05 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + 'DatabaseIntegrityCheck_' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile05) > 200 SET @OutputFile05 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile05) > 200 SET @OutputFile05 = NULL - - SET @JobName06 = 'DatabaseIntegrityCheck - USER_DATABASES' - SET @JobCommand06 = 'sqlcmd -E -S ' + @TokenServer + ' -d ' + @DatabaseName + ' -Q "EXECUTE [dbo].[DatabaseIntegrityCheck] @Databases = ''USER_DATABASES''' + CASE WHEN @LogToTable = 'Y' THEN ', @LogToTable = ''Y''' ELSE '' END + '" -b' - SET @OutputFile06 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + 'DatabaseIntegrityCheck_' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile06) > 200 SET @OutputFile06 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile06) > 200 SET @OutputFile06 = NULL - - SET @JobName07 = 'IndexOptimize - USER_DATABASES' - SET @JobCommand07 = 'sqlcmd -E -S ' + @TokenServer + ' -d ' + @DatabaseName + ' -Q "EXECUTE [dbo].[IndexOptimize] @Databases = ''USER_DATABASES''' + CASE WHEN @LogToTable = 'Y' THEN ', @LogToTable = ''Y''' ELSE '' END + '" -b' - SET @OutputFile07 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + 'IndexOptimize_' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile07) > 200 SET @OutputFile07 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile07) > 200 SET @OutputFile07 = NULL - - SET @JobName08 = 'sp_delete_backuphistory' - SET @JobCommand08 = 'sqlcmd -E -S ' + @TokenServer + ' -d ' + 'msdb' + ' -Q "DECLARE @CleanupDate datetime SET @CleanupDate = DATEADD(dd,-30,GETDATE()) EXECUTE dbo.sp_delete_backuphistory @oldest_date = @CleanupDate" -b' - SET @OutputFile08 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + 'sp_delete_backuphistory_' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile08) > 200 SET @OutputFile08 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile08) > 200 SET @OutputFile08 = NULL - - SET @JobName09 = 'sp_purge_jobhistory' - SET @JobCommand09 = 'sqlcmd -E -S ' + @TokenServer + ' -d ' + 'msdb' + ' -Q "DECLARE @CleanupDate datetime SET @CleanupDate = DATEADD(dd,-30,GETDATE()) EXECUTE dbo.sp_purge_jobhistory @oldest_date = @CleanupDate" -b' - SET @OutputFile09 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + 'sp_purge_jobhistory_' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile09) > 200 SET @OutputFile09 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile09) > 200 SET @OutputFile09 = NULL - - SET @JobName10 = 'Output File Cleanup' - SET @JobCommand10 = 'cmd /q /c "For /F "tokens=1 delims=" %v In (''ForFiles /P "' + COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '" /m *_*_*_*.txt /d -30 2^>^&1'') do if EXIST "' + COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '"\%v echo del "' + COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '"\%v& del "' + COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '"\%v"' - SET @OutputFile10 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + 'OutputFileCleanup_' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile10) > 200 SET @OutputFile10 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile10) > 200 SET @OutputFile10 = NULL - - SET @JobName11 = 'CommandLog Cleanup' - SET @JobCommand11 = 'sqlcmd -E -S ' + @TokenServer + ' -d ' + @DatabaseName + ' -Q "DELETE FROM [dbo].[CommandLog] WHERE StartTime < DATEADD(dd,-30,GETDATE())" -b' - SET @OutputFile11 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + 'CommandLogCleanup_' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile11) > 200 SET @OutputFile11 = COALESCE(@OutputFileDirectory,@TokenLogDirectory) + '\' + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@OutputFile11) > 200 SET @OutputFile11 = NULL - - IF NOT EXISTS (SELECT * FROM msdb.dbo.sysjobs WHERE [name] = @JobName01) + IF @Version >= 11 BEGIN - EXECUTE msdb.dbo.sp_add_job @job_name = @JobName01, @description = @JobDescription, @category_name = @JobCategory, @owner_login_name = @JobOwner - EXECUTE msdb.dbo.sp_add_jobstep @job_name = @JobName01, @step_name = @JobName01, @subsystem = 'CMDEXEC', @command = @JobCommand01, @output_file_name = @OutputFile01 - EXECUTE msdb.dbo.sp_add_jobserver @job_name = @JobName01 + SELECT @LogDirectory = [path] + FROM sys.dm_os_server_diagnostics_log_configurations END - - IF NOT EXISTS (SELECT * FROM msdb.dbo.sysjobs WHERE [name] = @JobName02) + ELSE BEGIN - EXECUTE msdb.dbo.sp_add_job @job_name = @JobName02, @description = @JobDescription, @category_name = @JobCategory, @owner_login_name = @JobOwner - EXECUTE msdb.dbo.sp_add_jobstep @job_name = @JobName02, @step_name = @JobName02, @subsystem = 'CMDEXEC', @command = @JobCommand02, @output_file_name = @OutputFile02 - EXECUTE msdb.dbo.sp_add_jobserver @job_name = @JobName02 + SELECT @LogDirectory = LEFT(CAST(SERVERPROPERTY('ErrorLogFileName') AS nvarchar(max)),LEN(CAST(SERVERPROPERTY('ErrorLogFileName') AS nvarchar(max))) - CHARINDEX('\',REVERSE(CAST(SERVERPROPERTY('ErrorLogFileName') AS nvarchar(max))))) END - IF NOT EXISTS (SELECT * FROM msdb.dbo.sysjobs WHERE [name] = @JobName03) + IF @OutputFileDirectory IS NULL AND RIGHT(@OutputFileDirectory,1) = @DirectorySeparator BEGIN - EXECUTE msdb.dbo.sp_add_job @job_name = @JobName03, @description = @JobDescription, @category_name = @JobCategory, @owner_login_name = @JobOwner - EXECUTE msdb.dbo.sp_add_jobstep @job_name = @JobName03, @step_name = @JobName03, @subsystem = 'CMDEXEC', @command = @JobCommand03, @output_file_name = @OutputFile03 - EXECUTE msdb.dbo.sp_add_jobserver @job_name = @JobName03 + SET @OutputFileDirectory = LEFT(@OutputFileDirectory, LEN(@OutputFileDirectory) - 1) END - IF NOT EXISTS (SELECT * FROM msdb.dbo.sysjobs WHERE [name] = @JobName04) + IF @LogDirectory IS NOT NULL AND RIGHT(@LogDirectory,1) = @DirectorySeparator BEGIN - EXECUTE msdb.dbo.sp_add_job @job_name = @JobName04, @description = @JobDescription, @category_name = @JobCategory, @owner_login_name = @JobOwner - EXECUTE msdb.dbo.sp_add_jobstep @job_name = @JobName04, @step_name = @JobName04, @subsystem = 'CMDEXEC', @command = @JobCommand04, @output_file_name = @OutputFile04 - EXECUTE msdb.dbo.sp_add_jobserver @job_name = @JobName04 + SET @LogDirectory = LEFT(@LogDirectory, LEN(@LogDirectory) - 1) END - IF NOT EXISTS (SELECT * FROM msdb.dbo.sysjobs WHERE [name] = @JobName05) - BEGIN - EXECUTE msdb.dbo.sp_add_job @job_name = @JobName05, @description = @JobDescription, @category_name = @JobCategory, @owner_login_name = @JobOwner - EXECUTE msdb.dbo.sp_add_jobstep @job_name = @JobName05, @step_name = @JobName05, @subsystem = 'CMDEXEC', @command = @JobCommand05, @output_file_name = @OutputFile05 - EXECUTE msdb.dbo.sp_add_jobserver @job_name = @JobName05 - END + SET @JobDescription = 'Source: https://ola.hallengren.com' + SET @JobCategory = 'Database Maintenance' - IF NOT EXISTS (SELECT * FROM msdb.dbo.sysjobs WHERE [name] = @JobName06) - BEGIN - EXECUTE msdb.dbo.sp_add_job @job_name = @JobName06, @description = @JobDescription, @category_name = @JobCategory, @owner_login_name = @JobOwner - EXECUTE msdb.dbo.sp_add_jobstep @job_name = @JobName06, @step_name = @JobName06, @subsystem = 'CMDEXEC', @command = @JobCommand06, @output_file_name = @OutputFile06 - EXECUTE msdb.dbo.sp_add_jobserver @job_name = @JobName06 - END + IF @AmazonRDS = 0 + BEGIN + SET @JobOwner = SUSER_SNAME(0x01) + END + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01, OutputFileNamePart02) + SELECT 'DatabaseBackup - SYSTEM_DATABASES - FULL', + 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''SYSTEM_DATABASES'',' + CHAR(13) + CHAR(10) + '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') + ',' + CHAR(13) + CHAR(10) + '@BackupType = ''FULL'',' + CHAR(13) + CHAR(10) + '@Verify = ''Y'',' + CHAR(13) + CHAR(10) + '@CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') + ',' + CHAR(13) + CHAR(10) + '@CheckSum = ''Y'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', + @DatabaseName, + 'DatabaseBackup', + 'FULL' + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01, OutputFileNamePart02) + SELECT 'DatabaseBackup - USER_DATABASES - DIFF', + 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') + ',' + CHAR(13) + CHAR(10) + '@BackupType = ''DIFF'',' + CHAR(13) + CHAR(10) + '@Verify = ''Y'',' + CHAR(13) + CHAR(10) + '@CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') + ',' + CHAR(13) + CHAR(10) + '@CheckSum = ''Y'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', + @DatabaseName, + 'DatabaseBackup', + 'DIFF' + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01, OutputFileNamePart02) + SELECT 'DatabaseBackup - USER_DATABASES - FULL', + 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') + ',' + CHAR(13) + CHAR(10) + '@BackupType = ''FULL'',' + CHAR(13) + CHAR(10) + '@Verify = ''Y'',' + CHAR(13) + CHAR(10) + '@CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') + ',' + CHAR(13) + CHAR(10) + '@CheckSum = ''Y'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', + @DatabaseName, + 'DatabaseBackup', + 'FULL' + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01, OutputFileNamePart02) + SELECT 'DatabaseBackup - USER_DATABASES - LOG', + 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') + ',' + CHAR(13) + CHAR(10) + '@BackupType = ''LOG'',' + CHAR(13) + CHAR(10) + '@Verify = ''Y'',' + CHAR(13) + CHAR(10) + '@CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') + ',' + CHAR(13) + CHAR(10) + '@CheckSum = ''Y'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', + @DatabaseName, + 'DatabaseBackup', + 'LOG' + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) + SELECT 'DatabaseIntegrityCheck - SYSTEM_DATABASES', + 'EXECUTE [dbo].[DatabaseIntegrityCheck]' + CHAR(13) + CHAR(10) + '@Databases = ''SYSTEM_DATABASES'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', + @DatabaseName, + 'DatabaseIntegrityCheck' + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) + SELECT 'DatabaseIntegrityCheck - USER_DATABASES', + 'EXECUTE [dbo].[DatabaseIntegrityCheck]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES' + CASE WHEN @AmazonRDS = 1 THEN ', -rdsadmin' ELSE '' END + ''',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', + @DatabaseName, + 'DatabaseIntegrityCheck' + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) + SELECT 'IndexOptimize - USER_DATABASES', + 'EXECUTE [dbo].[IndexOptimize]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', + @DatabaseName, + 'IndexOptimize' + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) + SELECT 'sp_delete_backuphistory', + 'DECLARE @CleanupDate datetime' + CHAR(13) + CHAR(10) + 'SET @CleanupDate = DATEADD(dd,-30,GETDATE())' + CHAR(13) + CHAR(10) + 'EXECUTE dbo.sp_delete_backuphistory @oldest_date = @CleanupDate', + 'msdb', + 'sp_delete_backuphistory' + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) + SELECT 'sp_purge_jobhistory', + 'DECLARE @CleanupDate datetime' + CHAR(13) + CHAR(10) + 'SET @CleanupDate = DATEADD(dd,-30,GETDATE())' + CHAR(13) + CHAR(10) + 'EXECUTE dbo.sp_purge_jobhistory @oldest_date = @CleanupDate', + 'msdb', + 'sp_purge_jobhistory' + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) + SELECT 'CommandLog Cleanup', + 'DELETE FROM [dbo].[CommandLog]' + CHAR(13) + CHAR(10) + 'WHERE StartTime < DATEADD(dd,-30,GETDATE())', + @DatabaseName, + 'CommandLogCleanup' + + INSERT INTO @Jobs ([Name], CommandCmdExec, OutputFileNamePart01) + SELECT 'Output File Cleanup', + 'cmd /q /c "For /F "tokens=1 delims=" %v In (''ForFiles /P "' + COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + '" /m *_*_*_*.txt /d -30 2^>^&1'') do if EXIST "' + COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + '"\%v echo del "' + COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + '"\%v& del "' + COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + '"\%v"', + 'OutputFileCleanup' - IF NOT EXISTS (SELECT * FROM msdb.dbo.sysjobs WHERE [name] = @JobName07) + IF @AmazonRDS = 1 BEGIN - EXECUTE msdb.dbo.sp_add_job @job_name = @JobName07, @description = @JobDescription, @category_name = @JobCategory, @owner_login_name = @JobOwner - EXECUTE msdb.dbo.sp_add_jobstep @job_name = @JobName07, @step_name = @JobName07, @subsystem = 'CMDEXEC', @command = @JobCommand07, @output_file_name = @OutputFile07 - EXECUTE msdb.dbo.sp_add_jobserver @job_name = @JobName07 + UPDATE @Jobs + SET Selected = 1 + WHERE [Name] IN('DatabaseIntegrityCheck - USER_DATABASES','IndexOptimize - USER_DATABASES','CommandLog Cleanup') END - - IF NOT EXISTS (SELECT * FROM msdb.dbo.sysjobs WHERE [name] = @JobName08) + ELSE IF @HostPlatform = 'Windows' BEGIN - EXECUTE msdb.dbo.sp_add_job @job_name = @JobName08, @description = @JobDescription, @category_name = @JobCategory, @owner_login_name = @JobOwner - EXECUTE msdb.dbo.sp_add_jobstep @job_name = @JobName08, @step_name = @JobName08, @subsystem = 'CMDEXEC', @command = @JobCommand08, @output_file_name = @OutputFile08 - EXECUTE msdb.dbo.sp_add_jobserver @job_name = @JobName08 + UPDATE @Jobs + SET Selected = 1 END - - IF NOT EXISTS (SELECT * FROM msdb.dbo.sysjobs WHERE [name] = @JobName09) + ELSE IF @HostPlatform = 'Linux' BEGIN - EXECUTE msdb.dbo.sp_add_job @job_name = @JobName09, @description = @JobDescription, @category_name = @JobCategory, @owner_login_name = @JobOwner - EXECUTE msdb.dbo.sp_add_jobstep @job_name = @JobName09, @step_name = @JobName09, @subsystem = 'CMDEXEC', @command = @JobCommand09, @output_file_name = @OutputFile09 - EXECUTE msdb.dbo.sp_add_jobserver @job_name = @JobName09 + UPDATE @Jobs + SET Selected = 1 + WHERE CommandTSQL IS NOT NULL END - IF NOT EXISTS (SELECT * FROM msdb.dbo.sysjobs WHERE [name] = @JobName10) + WHILE EXISTS (SELECT * FROM @Jobs WHERE Completed = 0 AND Selected = 1) BEGIN - EXECUTE msdb.dbo.sp_add_job @job_name = @JobName10, @description = @JobDescription, @category_name = @JobCategory, @owner_login_name = @JobOwner - EXECUTE msdb.dbo.sp_add_jobstep @job_name = @JobName10, @step_name = @JobName10, @subsystem = 'CMDEXEC', @command = @JobCommand10, @output_file_name = @OutputFile10 - EXECUTE msdb.dbo.sp_add_jobserver @job_name = @JobName10 - END + SELECT @CurrentJobID = JobID, + @CurrentJobName = [Name], + @CurrentCommandTSQL = CommandTSQL, + @CurrentCommandCmdExec = CommandCmdExec, + @CurrentDatabaseName = DatabaseName, + @CurrentOutputFileNamePart01 = OutputFileNamePart01, + @CurrentOutputFileNamePart02 = OutputFileNamePart02 + FROM @Jobs + WHERE Completed = 0 + AND Selected = 1 + ORDER BY JobID ASC + + IF @CurrentCommandTSQL IS NOT NULL AND @AmazonRDS = 1 + BEGIN + SET @CurrentJobStepSubSystem = 'TSQL' + SET @CurrentJobStepCommand = @CurrentCommandTSQL + SET @CurrentJobStepDatabaseName = @CurrentDatabaseName + END + ELSE IF @CurrentCommandTSQL IS NOT NULL AND @HostPlatform = 'Linux' + BEGIN + SET @CurrentJobStepSubSystem = 'TSQL' + SET @CurrentJobStepCommand = @CurrentCommandTSQL + SET @CurrentJobStepDatabaseName = @CurrentDatabaseName + END + ELSE IF @CurrentCommandTSQL IS NOT NULL AND @HostPlatform = 'Windows' + BEGIN + SET @CurrentJobStepSubSystem = 'CMDEXEC' + SET @CurrentJobStepCommand = 'sqlcmd -E -S ' + @TokenServer + ' -d ' + @CurrentDatabaseName + ' -Q "' + REPLACE(@CurrentCommandTSQL,(CHAR(13) + CHAR(10)),' ') + '" -b' + SET @CurrentJobStepDatabaseName = NULL + END + ELSE IF @CurrentCommandCmdExec IS NOT NULL AND @HostPlatform = 'Windows' + BEGIN + SET @CurrentJobStepSubSystem = 'CMDEXEC' + SET @CurrentJobStepCommand = @CurrentCommandCmdExec + SET @CurrentJobStepDatabaseName = NULL + END + + IF @AmazonRDS = 0 + BEGIN + SET @CurrentOutputFileName = COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + @DirectorySeparator + ISNULL(@CurrentOutputFileNamePart01 + '_','') + ISNULL(@CurrentOutputFileNamePart02 + '_','') + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' + IF LEN(@CurrentOutputFileName) > 200 SET @CurrentOutputFileName = COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + @DirectorySeparator + ISNULL(@CurrentOutputFileNamePart01 + '_','') + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' + IF LEN(@CurrentOutputFileName) > 200 SET @CurrentOutputFileName = COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + @DirectorySeparator + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' + IF LEN(@CurrentOutputFileName) > 200 SET @CurrentOutputFileName = NULL + END + + IF @CurrentJobStepSubSystem IS NOT NULL AND @CurrentJobStepCommand IS NOT NULL AND NOT EXISTS (SELECT * FROM msdb.dbo.sysjobs WHERE [name] = @CurrentJobName) + BEGIN + EXECUTE msdb.dbo.sp_add_job @job_name = @CurrentJobName, @description = @JobDescription, @category_name = @JobCategory, @owner_login_name = @JobOwner + EXECUTE msdb.dbo.sp_add_jobstep @job_name = @CurrentJobName, @step_name = @CurrentJobName, @subsystem = @CurrentJobStepSubSystem, @command = @CurrentJobStepCommand, @output_file_name = @CurrentOutputFileName, @database_name = @CurrentJobStepDatabaseName + EXECUTE msdb.dbo.sp_add_jobserver @job_name = @CurrentJobName + END + + UPDATE Jobs + SET Completed = 1 + FROM @Jobs Jobs + WHERE JobID = @CurrentJobID + + SET @CurrentJobID = NULL + SET @CurrentJobName = NULL + SET @CurrentCommandTSQL = NULL + SET @CurrentCommandCmdExec = NULL + SET @CurrentDatabaseName = NULL + SET @CurrentOutputFileNamePart01 = NULL + SET @CurrentOutputFileNamePart02 = NULL + SET @CurrentJobStepCommand = NULL + SET @CurrentJobStepSubSystem = NULL + SET @CurrentJobStepDatabaseName = NULL + SET @CurrentOutputFileName = NULL - IF NOT EXISTS (SELECT * FROM msdb.dbo.sysjobs WHERE [name] = @JobName11) - BEGIN - EXECUTE msdb.dbo.sp_add_job @job_name = @JobName11, @description = @JobDescription, @category_name = @JobCategory, @owner_login_name = @JobOwner - EXECUTE msdb.dbo.sp_add_jobstep @job_name = @JobName11, @step_name = @JobName11, @subsystem = 'CMDEXEC', @command = @JobCommand11, @output_file_name = @OutputFile11 - EXECUTE msdb.dbo.sp_add_jobserver @job_name = @JobName11 END END From b7200916c64fa896ea210c68beb3d657f3e986f7 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 12 Apr 2018 21:38:30 +0200 Subject: [PATCH 015/188] Add files via upload --- DatabaseBackup.sql | 178 ++++++++++------ DatabaseIntegrityCheck.sql | 80 +++++-- IndexOptimize.sql | 155 ++++++++++---- MaintenanceSolution.sql | 413 ++++++++++++++++++++++++++----------- 4 files changed, 576 insertions(+), 250 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 9f1f5342..5d21d933 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -62,6 +62,11 @@ BEGIN DECLARE @DatabaseMessage nvarchar(max) DECLARE @ErrorMessage nvarchar(max) + DECLARE @StartTime datetime + DECLARE @SchemaName nvarchar(max) + DECLARE @ObjectName nvarchar(max) + DECLARE @Parameters nvarchar(max) + DECLARE @Version numeric(18,10) DECLARE @HostPlatform nvarchar(max) DECLARE @DirectorySeparator nvarchar(max) @@ -201,7 +206,49 @@ BEGIN --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @StartTime = GETDATE() + SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + SET @ObjectName = OBJECT_NAME(@@PROCID) + + SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @BackupType = ' + ISNULL('''' + REPLACE(@BackupType,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Verify = ' + ISNULL('''' + REPLACE(@Verify,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @CleanupMode = ' + ISNULL('''' + REPLACE(@CleanupMode,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Compress = ' + ISNULL('''' + REPLACE(@Compress,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @CopyOnly = ' + ISNULL('''' + REPLACE(@CopyOnly,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ChangeBackupType = ' + ISNULL('''' + REPLACE(@ChangeBackupType,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @BackupSoftware = ' + ISNULL('''' + REPLACE(@BackupSoftware,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @CheckSum = ' + ISNULL('''' + REPLACE(@CheckSum,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @BlockSize = ' + ISNULL(CAST(@BlockSize AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @CompressionLevel = ' + ISNULL(CAST(@CompressionLevel AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @Encrypt = ' + ISNULL('''' + REPLACE(@Encrypt,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @EncryptionAlgorithm = ' + ISNULL('''' + REPLACE(@EncryptionAlgorithm,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ServerCertificate = ' + ISNULL('''' + REPLACE(@ServerCertificate,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ServerAsymmetricKey = ' + ISNULL('''' + REPLACE(@ServerAsymmetricKey,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @EncryptionKey = ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ReadWriteFileGroups = ' + ISNULL('''' + REPLACE(@ReadWriteFileGroups,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @OverrideBackupPreference = ' + ISNULL('''' + REPLACE(@OverrideBackupPreference,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @NoRecovery = ' + ISNULL('''' + REPLACE(@NoRecovery,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @URL = ' + ISNULL('''' + REPLACE(@URL,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Credential = ' + ISNULL('''' + REPLACE(@Credential,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @MirrorDirectory = ' + ISNULL('''' + REPLACE(@MirrorDirectory,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @MirrorCleanupTime = ' + ISNULL(CAST(@MirrorCleanupTime AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @MirrorCleanupMode = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) RAISERROR(@StartMessage,10,1) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) @@ -216,46 +263,10 @@ BEGIN SET @StartMessage = 'Platform: ' + @HostPlatform RAISERROR(@StartMessage,10,1) WITH NOWAIT - SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR(@StartMessage,10,1) WITH NOWAIT - SET @StartMessage = 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @BackupType = ' + ISNULL('''' + REPLACE(@BackupType,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Verify = ' + ISNULL('''' + REPLACE(@Verify,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @CleanupMode = ' + ISNULL('''' + REPLACE(@CleanupMode,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Compress = ' + ISNULL('''' + REPLACE(@Compress,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @CopyOnly = ' + ISNULL('''' + REPLACE(@CopyOnly,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @ChangeBackupType = ' + ISNULL('''' + REPLACE(@ChangeBackupType,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @BackupSoftware = ' + ISNULL('''' + REPLACE(@BackupSoftware,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @CheckSum = ' + ISNULL('''' + REPLACE(@CheckSum,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @BlockSize = ' + ISNULL(CAST(@BlockSize AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @CompressionLevel = ' + ISNULL(CAST(@CompressionLevel AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @Encrypt = ' + ISNULL('''' + REPLACE(@Encrypt,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @EncryptionAlgorithm = ' + ISNULL('''' + REPLACE(@EncryptionAlgorithm,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @ServerCertificate = ' + ISNULL('''' + REPLACE(@ServerCertificate,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @ServerAsymmetricKey = ' + ISNULL('''' + REPLACE(@ServerAsymmetricKey,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @EncryptionKey = ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @ReadWriteFileGroups = ' + ISNULL('''' + REPLACE(@ReadWriteFileGroups,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @OverrideBackupPreference = ' + ISNULL('''' + REPLACE(@OverrideBackupPreference,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @NoRecovery = ' + ISNULL('''' + REPLACE(@NoRecovery,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @URL = ' + ISNULL('''' + REPLACE(@URL,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Credential = ' + ISNULL('''' + REPLACE(@Credential,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @MirrorDirectory = ' + ISNULL('''' + REPLACE(@MirrorDirectory,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @MirrorCleanupTime = ' + ISNULL(CAST(@MirrorCleanupTime AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @MirrorCleanupMode = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @StartMessage = 'Parameters: ' + @Parameters SET @StartMessage = REPLACE(@StartMessage,'%','%%') RAISERROR(@StartMessage,10,1) WITH NOWAIT @@ -647,7 +658,7 @@ BEGIN IF @DirectoryCheck = 1 BEGIN - WHILE EXISTS(SELECT * FROM @Directories WHERE Completed = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentRootDirectoryID = ID, @CurrentRootDirectoryPath = DirectoryPath @@ -655,6 +666,11 @@ BEGIN WHERE Completed = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + INSERT INTO @DirectoryInfo (FileExists, FileIsADirectory, ParentDirectoryExists) EXECUTE [master].dbo.xp_fileexist @CurrentRootDirectoryPath @@ -1016,7 +1032,7 @@ BEGIN --// Execute backup commands //-- ---------------------------------------------------------------------------------------------------- - WHILE EXISTS (SELECT * FROM @tmpDatabases WHERE Selected = 1 AND Completed = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentDBID = ID, @@ -1027,6 +1043,11 @@ BEGIN AND Completed = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + SET @CurrentDatabaseID = DB_ID(@CurrentDatabaseName) IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' @@ -1365,34 +1386,42 @@ BEGIN END -- Create directory - WHILE EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateCompleted = 0) AND @HostPlatform = 'Windows' + IF @HostPlatform = 'Windows' BEGIN - SELECT TOP 1 @CurrentDirectoryID = ID, - @CurrentDirectoryPath = DirectoryPath - FROM @CurrentDirectories - WHERE CreateCompleted = 0 - ORDER BY ID ASC - - SET @CurrentCommandType01 = 'xp_create_subdir' - SET @CurrentCommand01 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_create_subdir N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''' IF @ReturnCode <> 0 RAISERROR(''Error creating directory.'', 16, 1)' - EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute - SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput01 = @Error - IF @CurrentCommandOutput01 <> 0 SET @ReturnCode = @CurrentCommandOutput01 + WHILE (1 = 1) + BEGIN + SELECT TOP 1 @CurrentDirectoryID = ID, + @CurrentDirectoryPath = DirectoryPath + FROM @CurrentDirectories + WHERE CreateCompleted = 0 + ORDER BY ID ASC - UPDATE @CurrentDirectories - SET CreateCompleted = 1, - CreateOutput = @CurrentCommandOutput01 - WHERE ID = @CurrentDirectoryID + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END - SET @CurrentDirectoryID = NULL - SET @CurrentDirectoryPath = NULL + SET @CurrentCommandType01 = 'xp_create_subdir' + SET @CurrentCommand01 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_create_subdir N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''' IF @ReturnCode <> 0 RAISERROR(''Error creating directory.'', 16, 1)' + EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + SET @Error = @@ERROR + IF @Error <> 0 SET @CurrentCommandOutput01 = @Error + IF @CurrentCommandOutput01 <> 0 SET @ReturnCode = @CurrentCommandOutput01 - SET @CurrentCommand01 = NULL + UPDATE @CurrentDirectories + SET CreateCompleted = 1, + CreateOutput = @CurrentCommandOutput01 + WHERE ID = @CurrentDirectoryID + + SET @CurrentDirectoryID = NULL + SET @CurrentDirectoryPath = NULL - SET @CurrentCommandOutput01 = NULL + SET @CurrentCommand01 = NULL - SET @CurrentCommandType01 = NULL + SET @CurrentCommandOutput01 = NULL + + SET @CurrentCommandType01 = NULL + END END IF @CleanupMode = 'BEFORE_BACKUP' @@ -1432,16 +1461,22 @@ BEGIN AND @HostPlatform = 'Windows' AND @CurrentBackupType = @BackupType BEGIN - WHILE EXISTS (SELECT * FROM @CurrentDirectories WHERE CleanupDate IS NOT NULL AND CleanupMode = 'BEFORE_BACKUP' AND CleanupCompleted = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentDirectoryID = ID, @CurrentDirectoryPath = DirectoryPath, @CurrentCleanupDate = CleanupDate FROM @CurrentDirectories WHERE CleanupDate IS NOT NULL + AND CleanupMode = 'BEFORE_BACKUP' AND CleanupCompleted = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + IF @BackupSoftware IS NULL BEGIN SET @CurrentCommandType02 = 'xp_delete_file' @@ -1700,7 +1735,7 @@ BEGIN -- Verify the backup IF @CurrentCommandOutput03 = 0 AND @Verify = 'Y' BEGIN - WHILE EXISTS (SELECT * FROM @CurrentBackupSet WHERE VerifyCompleted = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentBackupSetID = ID, @CurrentIsMirror = Mirror @@ -1708,6 +1743,11 @@ BEGIN WHERE VerifyCompleted = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + IF @BackupSoftware IS NULL BEGIN SET @CurrentCommandType04 = 'RESTORE_VERIFYONLY' @@ -1837,16 +1877,22 @@ BEGIN AND @HostPlatform = 'Windows' AND @CurrentBackupType = @BackupType BEGIN - WHILE EXISTS (SELECT * FROM @CurrentDirectories WHERE CleanupDate IS NOT NULL AND CleanupMode = 'AFTER_BACKUP' AND CleanupCompleted = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentDirectoryID = ID, @CurrentDirectoryPath = DirectoryPath, @CurrentCleanupDate = CleanupDate FROM @CurrentDirectories WHERE CleanupDate IS NOT NULL + AND CleanupMode = 'AFTER_BACKUP' AND CleanupCompleted = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + IF @BackupSoftware IS NULL BEGIN SET @CurrentCommandType05 = 'xp_delete_file' diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 8737ea4b..0d49ebb6 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,13 @@ BEGIN DECLARE @DatabaseMessage nvarchar(max) DECLARE @ErrorMessage nvarchar(max) + DECLARE @StartTime datetime + DECLARE @SchemaName nvarchar(max) + DECLARE @ObjectName nvarchar(max) + DECLARE @Parameters nvarchar(max) + DECLARE @Version numeric(18,10) + DECLARE @HostPlatform nvarchar(max) DECLARE @AmazonRDS bit DECLARE @Cluster nvarchar(max) @@ -148,13 +154,43 @@ BEGIN SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) + IF @Version >= 14 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END + ELSE + BEGIN + SET @HostPlatform = 'Windows' + END + SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @StartTime = GETDATE() + SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + SET @ObjectName = OBJECT_NAME(@@PROCID) + + SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @CheckCommands = ' + ISNULL('''' + REPLACE(@CheckCommands,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @PhysicalOnly = ' + ISNULL('''' + REPLACE(@PhysicalOnly,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @NoIndex = ' + ISNULL('''' + REPLACE(@NoIndex,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ExtendedLogicalChecks = ' + ISNULL('''' + REPLACE(@ExtendedLogicalChecks,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @TabLock = ' + ISNULL('''' + REPLACE(@TabLock,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FileGroups = ' + ISNULL('''' + REPLACE(@FileGroups,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Objects = ' + ISNULL('''' + REPLACE(@Objects,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @AvailabilityGroupReplicas = ' + ISNULL('''' + REPLACE(@AvailabilityGroupReplicas,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) RAISERROR(@StartMessage,10,1) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) @@ -166,24 +202,13 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR(@StartMessage,10,1) WITH NOWAIT - SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + SET @StartMessage = 'Platform: ' + @HostPlatform + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR(@StartMessage,10,1) WITH NOWAIT - SET @StartMessage = 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @CheckCommands = ' + ISNULL('''' + REPLACE(@CheckCommands,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @PhysicalOnly = ' + ISNULL('''' + REPLACE(@PhysicalOnly,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @NoIndex = ' + ISNULL('''' + REPLACE(@NoIndex,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @ExtendedLogicalChecks = ' + ISNULL('''' + REPLACE(@ExtendedLogicalChecks,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @TabLock = ' + ISNULL('''' + REPLACE(@TabLock,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @FileGroups = ' + ISNULL('''' + REPLACE(@FileGroups,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Objects = ' + ISNULL('''' + REPLACE(@Objects,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @AvailabilityGroupReplicas = ' + ISNULL('''' + REPLACE(@AvailabilityGroupReplicas,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @StartMessage = 'Parameters: ' + @Parameters SET @StartMessage = REPLACE(@StartMessage,'%','%%') RAISERROR(@StartMessage,10,1) WITH NOWAIT @@ -756,7 +781,7 @@ BEGIN --// Execute commands //-- ---------------------------------------------------------------------------------------------------- - WHILE EXISTS (SELECT * FROM @tmpDatabases WHERE Selected = 1 AND Completed = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentDBID = ID, @@ -766,6 +791,11 @@ BEGIN AND Completed = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + SET @CurrentDatabaseID = DB_ID(@CurrentDatabaseName) IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 @@ -922,7 +952,7 @@ BEGIN SET @Error = @@ERROR END - WHILE EXISTS (SELECT * FROM @tmpFileGroups WHERE Selected = 1 AND Completed = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentFGID = ID, @CurrentFileGroupID = FileGroupID, @@ -932,6 +962,11 @@ BEGIN AND Completed = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + -- Does the filegroup exist? SET @CurrentCommand03 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' @@ -1054,7 +1089,7 @@ BEGIN SET @Error = @@ERROR END - WHILE EXISTS (SELECT * FROM @tmpObjects WHERE Selected = 1 AND Completed = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentOID = ID, @CurrentSchemaID = SchemaID, @@ -1067,6 +1102,11 @@ BEGIN AND Completed = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + -- Does the object exist? SET @CurrentCommand07 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' diff --git a/IndexOptimize.sql b/IndexOptimize.sql index ebab3525..d6b3817d 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,13 +56,17 @@ BEGIN DECLARE @DatabaseMessage nvarchar(max) DECLARE @ErrorMessage nvarchar(max) + DECLARE @StartTime datetime + DECLARE @SchemaName nvarchar(max) + DECLARE @ObjectName nvarchar(max) + DECLARE @Parameters nvarchar(max) + DECLARE @Version numeric(18,10) + DECLARE @HostPlatform nvarchar(max) DECLARE @AmazonRDS bit DECLARE @Cluster nvarchar(max) - DECLARE @StartTime datetime - DECLARE @CurrentDBID int DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -190,6 +194,11 @@ BEGIN DECLARE @CurrentActionsAllowed TABLE ([Action] nvarchar(max)) + DECLARE @CurrentUpdateStatisticsWithClauseArguments TABLE (ID int IDENTITY, + Argument nvarchar(max)) + + DECLARE @CurrentUpdateStatisticsWithClause nvarchar(max) + DECLARE @Error int DECLARE @ReturnCode int @@ -198,13 +207,53 @@ BEGIN SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) + IF @Version >= 14 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END + ELSE + BEGIN + SET @HostPlatform = 'Windows' + END + SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartTime = CONVERT(datetime,CONVERT(nvarchar,GETDATE(),120),120) + SET @StartTime = GETDATE() + SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + SET @ObjectName = OBJECT_NAME(@@PROCID) + + SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FragmentationLow = ' + ISNULL('''' + REPLACE(@FragmentationLow,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FragmentationMedium = ' + ISNULL('''' + REPLACE(@FragmentationMedium,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FragmentationHigh = ' + ISNULL('''' + REPLACE(@FragmentationHigh,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FragmentationLevel1 = ' + ISNULL(CAST(@FragmentationLevel1 AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @FragmentationLevel2 = ' + ISNULL(CAST(@FragmentationLevel2 AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @PageCountLevel = ' + ISNULL(CAST(@PageCountLevel AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @SortInTempdb = ' + ISNULL('''' + REPLACE(@SortInTempdb,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @PadIndex = ' + ISNULL('''' + REPLACE(@PadIndex,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @LOBCompaction = ' + ISNULL('''' + REPLACE(@LOBCompaction,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @UpdateStatistics = ' + ISNULL('''' + REPLACE(@UpdateStatistics,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @StatisticsResample = ' + ISNULL('''' + REPLACE(@StatisticsResample,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @PartitionLevel = ' + ISNULL('''' + REPLACE(@PartitionLevel,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @MSShippedObjects = ' + ISNULL('''' + REPLACE(@MSShippedObjects,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Indexes = ' + ISNULL('''' + REPLACE(@Indexes,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @WaitAtLowPriorityAbortAfterWait = ' + ISNULL('''' + REPLACE(@WaitAtLowPriorityAbortAfterWait,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) RAISERROR(@StartMessage,10,1) WITH NOWAIT @@ -218,36 +267,13 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR(@StartMessage,10,1) WITH NOWAIT - SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + SET @StartMessage = 'Platform: ' + @HostPlatform + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR(@StartMessage,10,1) WITH NOWAIT - SET @StartMessage = 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @FragmentationLow = ' + ISNULL('''' + REPLACE(@FragmentationLow,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @FragmentationMedium = ' + ISNULL('''' + REPLACE(@FragmentationMedium,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @FragmentationHigh = ' + ISNULL('''' + REPLACE(@FragmentationHigh,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @FragmentationLevel1 = ' + ISNULL(CAST(@FragmentationLevel1 AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @FragmentationLevel2 = ' + ISNULL(CAST(@FragmentationLevel2 AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @PageCountLevel = ' + ISNULL(CAST(@PageCountLevel AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @SortInTempdb = ' + ISNULL('''' + REPLACE(@SortInTempdb,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @PadIndex = ' + ISNULL('''' + REPLACE(@PadIndex,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @LOBCompaction = ' + ISNULL('''' + REPLACE(@LOBCompaction,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @UpdateStatistics = ' + ISNULL('''' + REPLACE(@UpdateStatistics,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @StatisticsResample = ' + ISNULL('''' + REPLACE(@StatisticsResample,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @PartitionLevel = ' + ISNULL('''' + REPLACE(@PartitionLevel,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @MSShippedObjects = ' + ISNULL('''' + REPLACE(@MSShippedObjects,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Indexes = ' + ISNULL('''' + REPLACE(@Indexes,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @WaitAtLowPriorityAbortAfterWait = ' + ISNULL('''' + REPLACE(@WaitAtLowPriorityAbortAfterWait,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @StartMessage = 'Parameters: ' + @Parameters SET @StartMessage = REPLACE(@StartMessage,'%','%%') RAISERROR(@StartMessage,10,1) WITH NOWAIT @@ -869,7 +895,7 @@ BEGIN --// Execute commands //-- ---------------------------------------------------------------------------------------------------- - WHILE EXISTS (SELECT * FROM @tmpDatabases WHERE Selected = 1 AND Completed = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentDBID = ID, @@ -879,6 +905,11 @@ BEGIN AND Completed = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + SET @CurrentDatabaseID = DB_ID(@CurrentDatabaseName) IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 @@ -1054,7 +1085,7 @@ BEGIN SET @Error = @@ERROR END - WHILE EXISTS (SELECT * FROM @tmpIndexesStatistics WHERE Selected = 1 AND Completed = 0 AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL)) + WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SELECT TOP 1 @CurrentIxID = ID, @@ -1077,6 +1108,11 @@ BEGIN AND Completed = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + -- Is the index a partition? IF @CurrentPartitionNumber IS NULL OR @CurrentPartitionCount = 1 BEGIN SET @CurrentIsPartition = 0 END ELSE BEGIN SET @CurrentIsPartition = 1 END @@ -1516,6 +1552,8 @@ BEGIN END END + SET @CurrentMaxDOP = @MaxDOP + IF @CurrentStatisticsID IS NOT NULL AND @CurrentUpdateStatistics = 'Y' AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType14 = 'UPDATE_STATISTICS' @@ -1523,12 +1561,49 @@ BEGIN SET @CurrentCommand14 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand14 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand14 = @CurrentCommand14 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) - IF @CurrentStatisticsSample IS NOT NULL OR @CurrentStatisticsResample = 'Y' OR @CurrentNoRecompute = 1 SET @CurrentCommand14 = @CurrentCommand14 + ' WITH' - IF @CurrentStatisticsSample = 100 SET @CurrentCommand14 = @CurrentCommand14 + ' FULLSCAN' - IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 SET @CurrentCommand14 = @CurrentCommand14 + ' SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar) + ' PERCENT' - IF @CurrentStatisticsResample = 'Y' SET @CurrentCommand14 = @CurrentCommand14 + ' RESAMPLE' - IF (@CurrentStatisticsSample IS NOT NULL OR @CurrentStatisticsResample = 'Y') AND @CurrentNoRecompute = 1 SET @CurrentCommand14 = @CurrentCommand14 + ',' - IF @CurrentNoRecompute = 1 SET @CurrentCommand14 = @CurrentCommand14 + ' NORECOMPUTE' + + IF @CurrentStatisticsSample = 100 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'FULLSCAN' + END + + IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar) + ' PERCENT' + END + + IF @CurrentStatisticsResample = 'Y' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'RESAMPLE' + END + + IF @CurrentNoRecompute = 1 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'NORECOMPUTE' + END + + IF @CurrentMaxDOP IS NOT NULL AND @Version >= 14.030154 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) + END + + IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) + BEGIN + SET @CurrentUpdateStatisticsWithClause = ' WITH' + + SELECT @CurrentUpdateStatisticsWithClause = @CurrentUpdateStatisticsWithClause + ' ' + Argument + ',' + FROM @CurrentUpdateStatisticsWithClauseArguments + ORDER BY ID ASC + + SET @CurrentUpdateStatisticsWithClause = LEFT(@CurrentUpdateStatisticsWithClause,LEN(@CurrentUpdateStatisticsWithClause) - 1) + END + + IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand14 = @CurrentCommand14 + @CurrentUpdateStatisticsWithClause EXECUTE @CurrentCommandOutput14 = [dbo].[CommandExecute] @Command = @CurrentCommand14, @CommandType = @CurrentCommandType14, @Mode = 2, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -1602,8 +1677,10 @@ BEGIN SET @CurrentStatisticsResample = NULL SET @CurrentComment = NULL SET @CurrentExtendedInfo = NULL + SET @CurrentUpdateStatisticsWithClause = NULL DELETE FROM @CurrentActionsAllowed + DELETE FROM @CurrentUpdateStatisticsWithClauseArguments END diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 271db6b6..553be453 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 9 April, 2018. +Last updated 12 April, 2018. Ola Hallengren https://ola.hallengren.com @@ -351,6 +351,11 @@ BEGIN DECLARE @DatabaseMessage nvarchar(max) DECLARE @ErrorMessage nvarchar(max) + DECLARE @StartTime datetime + DECLARE @SchemaName nvarchar(max) + DECLARE @ObjectName nvarchar(max) + DECLARE @Parameters nvarchar(max) + DECLARE @Version numeric(18,10) DECLARE @HostPlatform nvarchar(max) DECLARE @DirectorySeparator nvarchar(max) @@ -490,7 +495,49 @@ BEGIN --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @StartTime = GETDATE() + SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + SET @ObjectName = OBJECT_NAME(@@PROCID) + + SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @BackupType = ' + ISNULL('''' + REPLACE(@BackupType,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Verify = ' + ISNULL('''' + REPLACE(@Verify,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @CleanupMode = ' + ISNULL('''' + REPLACE(@CleanupMode,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Compress = ' + ISNULL('''' + REPLACE(@Compress,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @CopyOnly = ' + ISNULL('''' + REPLACE(@CopyOnly,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ChangeBackupType = ' + ISNULL('''' + REPLACE(@ChangeBackupType,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @BackupSoftware = ' + ISNULL('''' + REPLACE(@BackupSoftware,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @CheckSum = ' + ISNULL('''' + REPLACE(@CheckSum,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @BlockSize = ' + ISNULL(CAST(@BlockSize AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @CompressionLevel = ' + ISNULL(CAST(@CompressionLevel AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @Encrypt = ' + ISNULL('''' + REPLACE(@Encrypt,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @EncryptionAlgorithm = ' + ISNULL('''' + REPLACE(@EncryptionAlgorithm,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ServerCertificate = ' + ISNULL('''' + REPLACE(@ServerCertificate,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ServerAsymmetricKey = ' + ISNULL('''' + REPLACE(@ServerAsymmetricKey,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @EncryptionKey = ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ReadWriteFileGroups = ' + ISNULL('''' + REPLACE(@ReadWriteFileGroups,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @OverrideBackupPreference = ' + ISNULL('''' + REPLACE(@OverrideBackupPreference,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @NoRecovery = ' + ISNULL('''' + REPLACE(@NoRecovery,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @URL = ' + ISNULL('''' + REPLACE(@URL,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Credential = ' + ISNULL('''' + REPLACE(@Credential,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @MirrorDirectory = ' + ISNULL('''' + REPLACE(@MirrorDirectory,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @MirrorCleanupTime = ' + ISNULL(CAST(@MirrorCleanupTime AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @MirrorCleanupMode = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) RAISERROR(@StartMessage,10,1) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) @@ -505,46 +552,10 @@ BEGIN SET @StartMessage = 'Platform: ' + @HostPlatform RAISERROR(@StartMessage,10,1) WITH NOWAIT - SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR(@StartMessage,10,1) WITH NOWAIT - SET @StartMessage = 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @BackupType = ' + ISNULL('''' + REPLACE(@BackupType,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Verify = ' + ISNULL('''' + REPLACE(@Verify,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @CleanupMode = ' + ISNULL('''' + REPLACE(@CleanupMode,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Compress = ' + ISNULL('''' + REPLACE(@Compress,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @CopyOnly = ' + ISNULL('''' + REPLACE(@CopyOnly,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @ChangeBackupType = ' + ISNULL('''' + REPLACE(@ChangeBackupType,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @BackupSoftware = ' + ISNULL('''' + REPLACE(@BackupSoftware,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @CheckSum = ' + ISNULL('''' + REPLACE(@CheckSum,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @BlockSize = ' + ISNULL(CAST(@BlockSize AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @CompressionLevel = ' + ISNULL(CAST(@CompressionLevel AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @Encrypt = ' + ISNULL('''' + REPLACE(@Encrypt,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @EncryptionAlgorithm = ' + ISNULL('''' + REPLACE(@EncryptionAlgorithm,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @ServerCertificate = ' + ISNULL('''' + REPLACE(@ServerCertificate,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @ServerAsymmetricKey = ' + ISNULL('''' + REPLACE(@ServerAsymmetricKey,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @EncryptionKey = ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @ReadWriteFileGroups = ' + ISNULL('''' + REPLACE(@ReadWriteFileGroups,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @OverrideBackupPreference = ' + ISNULL('''' + REPLACE(@OverrideBackupPreference,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @NoRecovery = ' + ISNULL('''' + REPLACE(@NoRecovery,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @URL = ' + ISNULL('''' + REPLACE(@URL,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Credential = ' + ISNULL('''' + REPLACE(@Credential,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @MirrorDirectory = ' + ISNULL('''' + REPLACE(@MirrorDirectory,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @MirrorCleanupTime = ' + ISNULL(CAST(@MirrorCleanupTime AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @MirrorCleanupMode = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @StartMessage = 'Parameters: ' + @Parameters SET @StartMessage = REPLACE(@StartMessage,'%','%%') RAISERROR(@StartMessage,10,1) WITH NOWAIT @@ -936,7 +947,7 @@ BEGIN IF @DirectoryCheck = 1 BEGIN - WHILE EXISTS(SELECT * FROM @Directories WHERE Completed = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentRootDirectoryID = ID, @CurrentRootDirectoryPath = DirectoryPath @@ -944,6 +955,11 @@ BEGIN WHERE Completed = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + INSERT INTO @DirectoryInfo (FileExists, FileIsADirectory, ParentDirectoryExists) EXECUTE [master].dbo.xp_fileexist @CurrentRootDirectoryPath @@ -1305,7 +1321,7 @@ BEGIN --// Execute backup commands //-- ---------------------------------------------------------------------------------------------------- - WHILE EXISTS (SELECT * FROM @tmpDatabases WHERE Selected = 1 AND Completed = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentDBID = ID, @@ -1316,6 +1332,11 @@ BEGIN AND Completed = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + SET @CurrentDatabaseID = DB_ID(@CurrentDatabaseName) IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' @@ -1654,34 +1675,42 @@ BEGIN END -- Create directory - WHILE EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateCompleted = 0) AND @HostPlatform = 'Windows' + IF @HostPlatform = 'Windows' BEGIN - SELECT TOP 1 @CurrentDirectoryID = ID, - @CurrentDirectoryPath = DirectoryPath - FROM @CurrentDirectories - WHERE CreateCompleted = 0 - ORDER BY ID ASC + WHILE (1 = 1) + BEGIN + SELECT TOP 1 @CurrentDirectoryID = ID, + @CurrentDirectoryPath = DirectoryPath + FROM @CurrentDirectories + WHERE CreateCompleted = 0 + ORDER BY ID ASC - SET @CurrentCommandType01 = 'xp_create_subdir' - SET @CurrentCommand01 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_create_subdir N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''' IF @ReturnCode <> 0 RAISERROR(''Error creating directory.'', 16, 1)' - EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute - SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput01 = @Error - IF @CurrentCommandOutput01 <> 0 SET @ReturnCode = @CurrentCommandOutput01 + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END - UPDATE @CurrentDirectories - SET CreateCompleted = 1, - CreateOutput = @CurrentCommandOutput01 - WHERE ID = @CurrentDirectoryID + SET @CurrentCommandType01 = 'xp_create_subdir' + SET @CurrentCommand01 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_create_subdir N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''' IF @ReturnCode <> 0 RAISERROR(''Error creating directory.'', 16, 1)' + EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + SET @Error = @@ERROR + IF @Error <> 0 SET @CurrentCommandOutput01 = @Error + IF @CurrentCommandOutput01 <> 0 SET @ReturnCode = @CurrentCommandOutput01 - SET @CurrentDirectoryID = NULL - SET @CurrentDirectoryPath = NULL + UPDATE @CurrentDirectories + SET CreateCompleted = 1, + CreateOutput = @CurrentCommandOutput01 + WHERE ID = @CurrentDirectoryID - SET @CurrentCommand01 = NULL + SET @CurrentDirectoryID = NULL + SET @CurrentDirectoryPath = NULL + + SET @CurrentCommand01 = NULL - SET @CurrentCommandOutput01 = NULL + SET @CurrentCommandOutput01 = NULL - SET @CurrentCommandType01 = NULL + SET @CurrentCommandType01 = NULL + END END IF @CleanupMode = 'BEFORE_BACKUP' @@ -1721,16 +1750,22 @@ BEGIN AND @HostPlatform = 'Windows' AND @CurrentBackupType = @BackupType BEGIN - WHILE EXISTS (SELECT * FROM @CurrentDirectories WHERE CleanupDate IS NOT NULL AND CleanupMode = 'BEFORE_BACKUP' AND CleanupCompleted = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentDirectoryID = ID, @CurrentDirectoryPath = DirectoryPath, @CurrentCleanupDate = CleanupDate FROM @CurrentDirectories WHERE CleanupDate IS NOT NULL + AND CleanupMode = 'BEFORE_BACKUP' AND CleanupCompleted = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + IF @BackupSoftware IS NULL BEGIN SET @CurrentCommandType02 = 'xp_delete_file' @@ -1989,7 +2024,7 @@ BEGIN -- Verify the backup IF @CurrentCommandOutput03 = 0 AND @Verify = 'Y' BEGIN - WHILE EXISTS (SELECT * FROM @CurrentBackupSet WHERE VerifyCompleted = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentBackupSetID = ID, @CurrentIsMirror = Mirror @@ -1997,6 +2032,11 @@ BEGIN WHERE VerifyCompleted = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + IF @BackupSoftware IS NULL BEGIN SET @CurrentCommandType04 = 'RESTORE_VERIFYONLY' @@ -2126,16 +2166,22 @@ BEGIN AND @HostPlatform = 'Windows' AND @CurrentBackupType = @BackupType BEGIN - WHILE EXISTS (SELECT * FROM @CurrentDirectories WHERE CleanupDate IS NOT NULL AND CleanupMode = 'AFTER_BACKUP' AND CleanupCompleted = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentDirectoryID = ID, @CurrentDirectoryPath = DirectoryPath, @CurrentCleanupDate = CleanupDate FROM @CurrentDirectories WHERE CleanupDate IS NOT NULL + AND CleanupMode = 'AFTER_BACKUP' AND CleanupCompleted = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + IF @BackupSoftware IS NULL BEGIN SET @CurrentCommandType05 = 'xp_delete_file' @@ -2299,7 +2345,13 @@ BEGIN DECLARE @DatabaseMessage nvarchar(max) DECLARE @ErrorMessage nvarchar(max) + DECLARE @StartTime datetime + DECLARE @SchemaName nvarchar(max) + DECLARE @ObjectName nvarchar(max) + DECLARE @Parameters nvarchar(max) + DECLARE @Version numeric(18,10) + DECLARE @HostPlatform nvarchar(max) DECLARE @AmazonRDS bit DECLARE @Cluster nvarchar(max) @@ -2407,13 +2459,43 @@ BEGIN SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) + IF @Version >= 14 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END + ELSE + BEGIN + SET @HostPlatform = 'Windows' + END + SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @StartTime = GETDATE() + SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + SET @ObjectName = OBJECT_NAME(@@PROCID) + + SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @CheckCommands = ' + ISNULL('''' + REPLACE(@CheckCommands,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @PhysicalOnly = ' + ISNULL('''' + REPLACE(@PhysicalOnly,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @NoIndex = ' + ISNULL('''' + REPLACE(@NoIndex,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ExtendedLogicalChecks = ' + ISNULL('''' + REPLACE(@ExtendedLogicalChecks,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @TabLock = ' + ISNULL('''' + REPLACE(@TabLock,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FileGroups = ' + ISNULL('''' + REPLACE(@FileGroups,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Objects = ' + ISNULL('''' + REPLACE(@Objects,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @AvailabilityGroupReplicas = ' + ISNULL('''' + REPLACE(@AvailabilityGroupReplicas,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) RAISERROR(@StartMessage,10,1) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) @@ -2425,24 +2507,13 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR(@StartMessage,10,1) WITH NOWAIT - SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + SET @StartMessage = 'Platform: ' + @HostPlatform RAISERROR(@StartMessage,10,1) WITH NOWAIT - SET @StartMessage = 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @CheckCommands = ' + ISNULL('''' + REPLACE(@CheckCommands,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @PhysicalOnly = ' + ISNULL('''' + REPLACE(@PhysicalOnly,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @NoIndex = ' + ISNULL('''' + REPLACE(@NoIndex,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @ExtendedLogicalChecks = ' + ISNULL('''' + REPLACE(@ExtendedLogicalChecks,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @TabLock = ' + ISNULL('''' + REPLACE(@TabLock,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @FileGroups = ' + ISNULL('''' + REPLACE(@FileGroups,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Objects = ' + ISNULL('''' + REPLACE(@Objects,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @AvailabilityGroupReplicas = ' + ISNULL('''' + REPLACE(@AvailabilityGroupReplicas,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Parameters: ' + @Parameters SET @StartMessage = REPLACE(@StartMessage,'%','%%') RAISERROR(@StartMessage,10,1) WITH NOWAIT @@ -3015,7 +3086,7 @@ BEGIN --// Execute commands //-- ---------------------------------------------------------------------------------------------------- - WHILE EXISTS (SELECT * FROM @tmpDatabases WHERE Selected = 1 AND Completed = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentDBID = ID, @@ -3025,6 +3096,11 @@ BEGIN AND Completed = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + SET @CurrentDatabaseID = DB_ID(@CurrentDatabaseName) IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 @@ -3181,7 +3257,7 @@ BEGIN SET @Error = @@ERROR END - WHILE EXISTS (SELECT * FROM @tmpFileGroups WHERE Selected = 1 AND Completed = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentFGID = ID, @CurrentFileGroupID = FileGroupID, @@ -3191,6 +3267,11 @@ BEGIN AND Completed = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + -- Does the filegroup exist? SET @CurrentCommand03 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' @@ -3313,7 +3394,7 @@ BEGIN SET @Error = @@ERROR END - WHILE EXISTS (SELECT * FROM @tmpObjects WHERE Selected = 1 AND Completed = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentOID = ID, @CurrentSchemaID = SchemaID, @@ -3326,6 +3407,11 @@ BEGIN AND Completed = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + -- Does the object exist? SET @CurrentCommand07 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' @@ -3527,13 +3613,17 @@ BEGIN DECLARE @DatabaseMessage nvarchar(max) DECLARE @ErrorMessage nvarchar(max) + DECLARE @StartTime datetime + DECLARE @SchemaName nvarchar(max) + DECLARE @ObjectName nvarchar(max) + DECLARE @Parameters nvarchar(max) + DECLARE @Version numeric(18,10) + DECLARE @HostPlatform nvarchar(max) DECLARE @AmazonRDS bit DECLARE @Cluster nvarchar(max) - DECLARE @StartTime datetime - DECLARE @CurrentDBID int DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -3661,6 +3751,11 @@ BEGIN DECLARE @CurrentActionsAllowed TABLE ([Action] nvarchar(max)) + DECLARE @CurrentUpdateStatisticsWithClauseArguments TABLE (ID int IDENTITY, + Argument nvarchar(max)) + + DECLARE @CurrentUpdateStatisticsWithClause nvarchar(max) + DECLARE @Error int DECLARE @ReturnCode int @@ -3669,13 +3764,53 @@ BEGIN SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) + IF @Version >= 14 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END + ELSE + BEGIN + SET @HostPlatform = 'Windows' + END + SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartTime = CONVERT(datetime,CONVERT(nvarchar,GETDATE(),120),120) + SET @StartTime = GETDATE() + SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + SET @ObjectName = OBJECT_NAME(@@PROCID) + + SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FragmentationLow = ' + ISNULL('''' + REPLACE(@FragmentationLow,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FragmentationMedium = ' + ISNULL('''' + REPLACE(@FragmentationMedium,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FragmentationHigh = ' + ISNULL('''' + REPLACE(@FragmentationHigh,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FragmentationLevel1 = ' + ISNULL(CAST(@FragmentationLevel1 AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @FragmentationLevel2 = ' + ISNULL(CAST(@FragmentationLevel2 AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @PageCountLevel = ' + ISNULL(CAST(@PageCountLevel AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @SortInTempdb = ' + ISNULL('''' + REPLACE(@SortInTempdb,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @PadIndex = ' + ISNULL('''' + REPLACE(@PadIndex,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @LOBCompaction = ' + ISNULL('''' + REPLACE(@LOBCompaction,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @UpdateStatistics = ' + ISNULL('''' + REPLACE(@UpdateStatistics,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @StatisticsResample = ' + ISNULL('''' + REPLACE(@StatisticsResample,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @PartitionLevel = ' + ISNULL('''' + REPLACE(@PartitionLevel,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @MSShippedObjects = ' + ISNULL('''' + REPLACE(@MSShippedObjects,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Indexes = ' + ISNULL('''' + REPLACE(@Indexes,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @WaitAtLowPriorityAbortAfterWait = ' + ISNULL('''' + REPLACE(@WaitAtLowPriorityAbortAfterWait,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) RAISERROR(@StartMessage,10,1) WITH NOWAIT @@ -3689,36 +3824,13 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR(@StartMessage,10,1) WITH NOWAIT - SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + (SELECT QUOTENAME(schemas.name) FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) + '.' + QUOTENAME(OBJECT_NAME(@@PROCID)) + SET @StartMessage = 'Platform: ' + @HostPlatform + RAISERROR(@StartMessage,10,1) WITH NOWAIT + + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR(@StartMessage,10,1) WITH NOWAIT - SET @StartMessage = 'Parameters: @Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @FragmentationLow = ' + ISNULL('''' + REPLACE(@FragmentationLow,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @FragmentationMedium = ' + ISNULL('''' + REPLACE(@FragmentationMedium,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @FragmentationHigh = ' + ISNULL('''' + REPLACE(@FragmentationHigh,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @FragmentationLevel1 = ' + ISNULL(CAST(@FragmentationLevel1 AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @FragmentationLevel2 = ' + ISNULL(CAST(@FragmentationLevel2 AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @PageCountLevel = ' + ISNULL(CAST(@PageCountLevel AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @SortInTempdb = ' + ISNULL('''' + REPLACE(@SortInTempdb,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @PadIndex = ' + ISNULL('''' + REPLACE(@PadIndex,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @LOBCompaction = ' + ISNULL('''' + REPLACE(@LOBCompaction,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @UpdateStatistics = ' + ISNULL('''' + REPLACE(@UpdateStatistics,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @StatisticsResample = ' + ISNULL('''' + REPLACE(@StatisticsResample,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @PartitionLevel = ' + ISNULL('''' + REPLACE(@PartitionLevel,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @MSShippedObjects = ' + ISNULL('''' + REPLACE(@MSShippedObjects,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Indexes = ' + ISNULL('''' + REPLACE(@Indexes,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @WaitAtLowPriorityAbortAfterWait = ' + ISNULL('''' + REPLACE(@WaitAtLowPriorityAbortAfterWait,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') - SET @StartMessage = @StartMessage + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @StartMessage = @StartMessage + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @StartMessage = 'Parameters: ' + @Parameters SET @StartMessage = REPLACE(@StartMessage,'%','%%') RAISERROR(@StartMessage,10,1) WITH NOWAIT @@ -4340,7 +4452,7 @@ BEGIN --// Execute commands //-- ---------------------------------------------------------------------------------------------------- - WHILE EXISTS (SELECT * FROM @tmpDatabases WHERE Selected = 1 AND Completed = 0) + WHILE (1 = 1) BEGIN SELECT TOP 1 @CurrentDBID = ID, @@ -4350,6 +4462,11 @@ BEGIN AND Completed = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + SET @CurrentDatabaseID = DB_ID(@CurrentDatabaseName) IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 @@ -4525,7 +4642,7 @@ BEGIN SET @Error = @@ERROR END - WHILE EXISTS (SELECT * FROM @tmpIndexesStatistics WHERE Selected = 1 AND Completed = 0 AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL)) + WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SELECT TOP 1 @CurrentIxID = ID, @@ -4548,6 +4665,11 @@ BEGIN AND Completed = 0 ORDER BY ID ASC + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + -- Is the index a partition? IF @CurrentPartitionNumber IS NULL OR @CurrentPartitionCount = 1 BEGIN SET @CurrentIsPartition = 0 END ELSE BEGIN SET @CurrentIsPartition = 1 END @@ -4987,6 +5109,8 @@ BEGIN END END + SET @CurrentMaxDOP = @MaxDOP + IF @CurrentStatisticsID IS NOT NULL AND @CurrentUpdateStatistics = 'Y' AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType14 = 'UPDATE_STATISTICS' @@ -4994,12 +5118,49 @@ BEGIN SET @CurrentCommand14 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand14 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand14 = @CurrentCommand14 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) - IF @CurrentStatisticsSample IS NOT NULL OR @CurrentStatisticsResample = 'Y' OR @CurrentNoRecompute = 1 SET @CurrentCommand14 = @CurrentCommand14 + ' WITH' - IF @CurrentStatisticsSample = 100 SET @CurrentCommand14 = @CurrentCommand14 + ' FULLSCAN' - IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 SET @CurrentCommand14 = @CurrentCommand14 + ' SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar) + ' PERCENT' - IF @CurrentStatisticsResample = 'Y' SET @CurrentCommand14 = @CurrentCommand14 + ' RESAMPLE' - IF (@CurrentStatisticsSample IS NOT NULL OR @CurrentStatisticsResample = 'Y') AND @CurrentNoRecompute = 1 SET @CurrentCommand14 = @CurrentCommand14 + ',' - IF @CurrentNoRecompute = 1 SET @CurrentCommand14 = @CurrentCommand14 + ' NORECOMPUTE' + + IF @CurrentStatisticsSample = 100 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'FULLSCAN' + END + + IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar) + ' PERCENT' + END + + IF @CurrentStatisticsResample = 'Y' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'RESAMPLE' + END + + IF @CurrentNoRecompute = 1 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'NORECOMPUTE' + END + + IF @CurrentMaxDOP IS NOT NULL AND @Version >= 14.030154 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) + END + + IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) + BEGIN + SET @CurrentUpdateStatisticsWithClause = ' WITH' + + SELECT @CurrentUpdateStatisticsWithClause = @CurrentUpdateStatisticsWithClause + ' ' + Argument + ',' + FROM @CurrentUpdateStatisticsWithClauseArguments + ORDER BY ID ASC + + SET @CurrentUpdateStatisticsWithClause = LEFT(@CurrentUpdateStatisticsWithClause,LEN(@CurrentUpdateStatisticsWithClause) - 1) + END + + IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand14 = @CurrentCommand14 + @CurrentUpdateStatisticsWithClause EXECUTE @CurrentCommandOutput14 = [dbo].[CommandExecute] @Command = @CurrentCommand14, @CommandType = @CurrentCommandType14, @Mode = 2, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -5073,8 +5234,10 @@ BEGIN SET @CurrentStatisticsResample = NULL SET @CurrentComment = NULL SET @CurrentExtendedInfo = NULL + SET @CurrentUpdateStatisticsWithClause = NULL DELETE FROM @CurrentActionsAllowed + DELETE FROM @CurrentUpdateStatisticsWithClauseArguments END From 0561706510096d1eed2ea6b64da4099838a81070 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 13 Apr 2018 21:00:30 +0200 Subject: [PATCH 016/188] Add files via upload --- DatabaseBackup.sql | 87 +++++++++++++++++++++++++++++++++++----- MaintenanceSolution.sql | 89 ++++++++++++++++++++++++++++++++++++----- 2 files changed, 157 insertions(+), 19 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 5d21d933..fe116bd7 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -44,6 +44,9 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @AvailabilityGroups nvarchar(max) = NULL, @Updateability nvarchar(max) = 'ALL', @AdaptiveCompression nvarchar(max) = NULL, +@ModificationLevel int = NULL, +@LogSizeSinceLastLogBackup int = NULL, +@TimeSinceLastLogBackup int = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -106,6 +109,10 @@ BEGIN DECLARE @CurrentIsReadOnly bit DECLARE @CurrentBackupSetID int DECLARE @CurrentIsMirror bit + DECLARE @CurrentLastLogBackup datetime + DECLARE @CurrentLogSizeSinceLastLogBackup float + DECLARE @CurrentAllocatedExtentPageCount bigint + DECLARE @CurrentModifiedExtentPageCount bigint DECLARE @CurrentCommand01 nvarchar(max) DECLARE @CurrentCommand02 nvarchar(max) @@ -113,6 +120,7 @@ BEGIN DECLARE @CurrentCommand04 nvarchar(max) DECLARE @CurrentCommand05 nvarchar(max) DECLARE @CurrentCommand06 nvarchar(max) + DECLARE @CurrentCommand07 nvarchar(max) DECLARE @CurrentCommandOutput01 int DECLARE @CurrentCommandOutput02 int @@ -245,6 +253,9 @@ BEGIN SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ModificationLevel = ' + ISNULL(CAST(@ModificationLevel AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -957,6 +968,27 @@ BEGIN SET @Error = @@ERROR END + IF (@ModificationLevel IS NOT NULL AND NOT (@Version >= 14)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') + BEGIN + SET @ErrorMessage = 'The value for the parameter @ModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 14)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + BEGIN + SET @ErrorMessage = 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 14)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + BEGIN + SET @ErrorMessage = 'The value for the parameter @TimeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1082,6 +1114,13 @@ BEGIN WHERE database_id = @CurrentDatabaseID END + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 14 + BEGIN + SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_file_space_usage' + + EXECUTE sp_executesql @statement = @CurrentCommand07, @params = N'@ParamAllocatedExtentPageCount bigint OUTPUT, @ParamModifiedExtentPageCount bigint OUTPUT', @ParamAllocatedExtentPageCount = @CurrentAllocatedExtentPageCount OUTPUT, @ParamModifiedExtentPageCount = @CurrentModifiedExtentPageCount OUTPUT + END + SET @CurrentBackupType = @BackupType IF @ChangeBackupType = 'Y' @@ -1090,20 +1129,17 @@ BEGIN BEGIN SET @CurrentBackupType = 'DIFF' END - IF @CurrentBackupType = 'DIFF' AND @CurrentDifferentialBaseLSN IS NULL AND @CurrentDatabaseName <> 'master' + IF @CurrentBackupType = 'DIFF' AND @CurrentDatabaseName <> 'master' AND (@CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @ModificationLevel)) BEGIN SET @CurrentBackupType = 'FULL' END END - IF @CurrentBackupType = 'LOG' AND (@CleanupTime IS NOT NULL OR @MirrorCleanupTime IS NOT NULL) + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 14 BEGIN - SELECT @CurrentLatestBackup = MAX(backup_finish_date) - FROM msdb.dbo.backupset - WHERE ([type] IN('D','I') - OR database_backup_lsn < @CurrentDifferentialBaseLSN) - AND is_damaged = 0 - AND database_name = @CurrentDatabaseName + SELECT @CurrentLastLogBackup = log_backup_time, + @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb + FROM sys.dm_db_log_stats (@CurrentDatabaseID) END IF @CurrentBackupType = 'DIFF' @@ -1226,6 +1262,24 @@ BEGIN SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + IF @CurrentBackupType IN('DIFF','FULL') AND @Version >= 14 + BEGIN + SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar),'N/A') + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Modified extent page count: ' + ISNULL(CAST(@CurrentModifiedExtentPageCount AS nvarchar),'N/A') + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + IF @CurrentBackupType = 'LOG' AND @Version >= 14 + BEGIN + SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),@CurrentLastLogBackup,120),'N/A') + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Log size since last log backup (MB): ' + ISNULL(CAST(@CurrentLogSizeSinceLastLogBackup AS nvarchar),'N/A') + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + RAISERROR('',10,1) WITH NOWAIT IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' @@ -1242,9 +1296,19 @@ BEGIN AND NOT ((@CurrentLogShippingRole = 'PRIMARY' AND @CurrentLogShippingRole IS NOT NULL) AND @CurrentBackupType = 'LOG') AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') + AND NOT (@CurrentBackupType = 'LOG' AND @LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NOT NULL AND NOT(@CurrentLogSizeSinceLastLogBackup >= @LogSizeSinceLastLogBackup OR @CurrentLogSizeSinceLastLogBackup IS NULL OR DATEDIFF(SECOND,@CurrentLastLogBackup,GETDATE()) >= @TimeSinceLastLogBackup OR @CurrentLastLogBackup IS NULL)) BEGIN - -- Set variables + IF @CurrentBackupType = 'LOG' AND (@CleanupTime IS NOT NULL OR @MirrorCleanupTime IS NOT NULL) + BEGIN + SELECT @CurrentLatestBackup = MAX(backup_finish_date) + FROM msdb.dbo.backupset + WHERE ([type] IN('D','I') + OR database_backup_lsn < @CurrentDifferentialBaseLSN) + AND is_damaged = 0 + AND database_name = @CurrentDatabaseName + END + SET @CurrentDate = GETDATE() INSERT INTO @CurrentCleanupDates (CleanupDate) @@ -1981,9 +2045,14 @@ BEGIN SET @CurrentLogShippingRole = NULL SET @CurrentIsEncrypted = NULL SET @CurrentIsReadOnly = NULL + SET @CurrentLastLogBackup = NULL + SET @CurrentLogSizeSinceLastLogBackup = NULL + SET @CurrentAllocatedExtentPageCount = NULL + SET @CurrentModifiedExtentPageCount = NULL SET @CurrentCommand03 = NULL SET @CurrentCommand06 = NULL + SET @CurrentCommand07 = NULL SET @CurrentCommandOutput03 = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 553be453..1d681baa 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 12 April, 2018. +Last updated 13 April, 2018. Ola Hallengren https://ola.hallengren.com @@ -333,6 +333,9 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @AvailabilityGroups nvarchar(max) = NULL, @Updateability nvarchar(max) = 'ALL', @AdaptiveCompression nvarchar(max) = NULL, +@ModificationLevel int = NULL, +@LogSizeSinceLastLogBackup int = NULL, +@TimeSinceLastLogBackup int = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -395,6 +398,10 @@ BEGIN DECLARE @CurrentIsReadOnly bit DECLARE @CurrentBackupSetID int DECLARE @CurrentIsMirror bit + DECLARE @CurrentLastLogBackup datetime + DECLARE @CurrentLogSizeSinceLastLogBackup float + DECLARE @CurrentAllocatedExtentPageCount bigint + DECLARE @CurrentModifiedExtentPageCount bigint DECLARE @CurrentCommand01 nvarchar(max) DECLARE @CurrentCommand02 nvarchar(max) @@ -402,6 +409,7 @@ BEGIN DECLARE @CurrentCommand04 nvarchar(max) DECLARE @CurrentCommand05 nvarchar(max) DECLARE @CurrentCommand06 nvarchar(max) + DECLARE @CurrentCommand07 nvarchar(max) DECLARE @CurrentCommandOutput01 int DECLARE @CurrentCommandOutput02 int @@ -534,6 +542,9 @@ BEGIN SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ModificationLevel = ' + ISNULL(CAST(@ModificationLevel AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -1246,6 +1257,27 @@ BEGIN SET @Error = @@ERROR END + IF (@ModificationLevel IS NOT NULL AND NOT (@Version >= 14)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') + BEGIN + SET @ErrorMessage = 'The value for the parameter @ModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 14)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + BEGIN + SET @ErrorMessage = 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 14)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + BEGIN + SET @ErrorMessage = 'The value for the parameter @TimeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1371,6 +1403,13 @@ BEGIN WHERE database_id = @CurrentDatabaseID END + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 14 + BEGIN + SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_file_space_usage' + + EXECUTE sp_executesql @statement = @CurrentCommand07, @params = N'@ParamAllocatedExtentPageCount bigint OUTPUT, @ParamModifiedExtentPageCount bigint OUTPUT', @ParamAllocatedExtentPageCount = @CurrentAllocatedExtentPageCount OUTPUT, @ParamModifiedExtentPageCount = @CurrentModifiedExtentPageCount OUTPUT + END + SET @CurrentBackupType = @BackupType IF @ChangeBackupType = 'Y' @@ -1379,20 +1418,17 @@ BEGIN BEGIN SET @CurrentBackupType = 'DIFF' END - IF @CurrentBackupType = 'DIFF' AND @CurrentDifferentialBaseLSN IS NULL AND @CurrentDatabaseName <> 'master' + IF @CurrentBackupType = 'DIFF' AND @CurrentDatabaseName <> 'master' AND (@CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @ModificationLevel)) BEGIN SET @CurrentBackupType = 'FULL' END END - IF @CurrentBackupType = 'LOG' AND (@CleanupTime IS NOT NULL OR @MirrorCleanupTime IS NOT NULL) + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 14 BEGIN - SELECT @CurrentLatestBackup = MAX(backup_finish_date) - FROM msdb.dbo.backupset - WHERE ([type] IN('D','I') - OR database_backup_lsn < @CurrentDifferentialBaseLSN) - AND is_damaged = 0 - AND database_name = @CurrentDatabaseName + SELECT @CurrentLastLogBackup = log_backup_time, + @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb + FROM sys.dm_db_log_stats (@CurrentDatabaseID) END IF @CurrentBackupType = 'DIFF' @@ -1515,6 +1551,24 @@ BEGIN SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + IF @CurrentBackupType IN('DIFF','FULL') AND @Version >= 14 + BEGIN + SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar),'N/A') + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Modified extent page count: ' + ISNULL(CAST(@CurrentModifiedExtentPageCount AS nvarchar),'N/A') + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + + IF @CurrentBackupType = 'LOG' AND @Version >= 14 + BEGIN + SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),@CurrentLastLogBackup,120),'N/A') + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Log size since last log backup (MB): ' + ISNULL(CAST(@CurrentLogSizeSinceLastLogBackup AS nvarchar),'N/A') + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END + RAISERROR('',10,1) WITH NOWAIT IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' @@ -1531,9 +1585,19 @@ BEGIN AND NOT ((@CurrentLogShippingRole = 'PRIMARY' AND @CurrentLogShippingRole IS NOT NULL) AND @CurrentBackupType = 'LOG') AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') + AND NOT (@CurrentBackupType = 'LOG' AND @LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NOT NULL AND NOT(@CurrentLogSizeSinceLastLogBackup >= @LogSizeSinceLastLogBackup OR @CurrentLogSizeSinceLastLogBackup IS NULL OR DATEDIFF(SECOND,@CurrentLastLogBackup,GETDATE()) >= @TimeSinceLastLogBackup OR @CurrentLastLogBackup IS NULL)) BEGIN - -- Set variables + IF @CurrentBackupType = 'LOG' AND (@CleanupTime IS NOT NULL OR @MirrorCleanupTime IS NOT NULL) + BEGIN + SELECT @CurrentLatestBackup = MAX(backup_finish_date) + FROM msdb.dbo.backupset + WHERE ([type] IN('D','I') + OR database_backup_lsn < @CurrentDifferentialBaseLSN) + AND is_damaged = 0 + AND database_name = @CurrentDatabaseName + END + SET @CurrentDate = GETDATE() INSERT INTO @CurrentCleanupDates (CleanupDate) @@ -2270,9 +2334,14 @@ BEGIN SET @CurrentLogShippingRole = NULL SET @CurrentIsEncrypted = NULL SET @CurrentIsReadOnly = NULL + SET @CurrentLastLogBackup = NULL + SET @CurrentLogSizeSinceLastLogBackup = NULL + SET @CurrentAllocatedExtentPageCount = NULL + SET @CurrentModifiedExtentPageCount = NULL SET @CurrentCommand03 = NULL SET @CurrentCommand06 = NULL + SET @CurrentCommand07 = NULL SET @CurrentCommandOutput03 = NULL From 9b557453435165c17ea08fa3f1f0ba9e5635dd96 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 20 Apr 2018 11:01:09 +0200 Subject: [PATCH 017/188] Add files via upload --- DatabaseBackup.sql | 40 +++++++++++++++++++-------------------- MaintenanceSolution.sql | 42 ++++++++++++++++++++--------------------- 2 files changed, 41 insertions(+), 41 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index fe116bd7..760407c0 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -788,14 +788,14 @@ BEGIN IF @BackupSoftware = 'LITESPEED' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_backup_database') BEGIN - SET @ErrorMessage = 'LiteSpeed for SQL Server is not installed. Download http://software.dell.com/products/litespeed-for-sql-server/.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN - SET @ErrorMessage = 'Red Gate SQL Backup Pro is not installed. Download http://www.red-gate.com/products/dba/sql-backup/.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END @@ -1094,6 +1094,23 @@ BEGIN END END + IF @Version >= 11 AND @Cluster IS NOT NULL + BEGIN + SELECT @CurrentAvailabilityGroup = availability_groups.name, + @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) + FROM sys.databases databases + INNER JOIN sys.availability_databases_cluster availability_databases_cluster ON databases.group_database_id = availability_databases_cluster.group_database_id + INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id + INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON availability_groups.group_id = dm_hadr_availability_replica_states.group_id AND databases.replica_id = dm_hadr_availability_replica_states.replica_id + WHERE databases.name = @CurrentDatabaseName + END + + IF @Version >= 11 AND @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) + END + SELECT @CurrentDifferentialBaseLSN = differential_base_lsn FROM sys.master_files WHERE database_id = @CurrentDatabaseID @@ -1114,7 +1131,7 @@ BEGIN WHERE database_id = @CurrentDatabaseID END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 14 + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 14 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) BEGIN SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_file_space_usage' @@ -1151,23 +1168,6 @@ BEGIN AND checkpoint_lsn = @CurrentDifferentialBaseLSN END - IF @Version >= 11 AND @Cluster IS NOT NULL - BEGIN - SELECT @CurrentAvailabilityGroup = availability_groups.name, - @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, - @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) - FROM sys.databases databases - INNER JOIN sys.availability_databases_cluster availability_databases_cluster ON databases.group_database_id = availability_databases_cluster.group_database_id - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON availability_groups.group_id = dm_hadr_availability_replica_states.group_id AND databases.replica_id = dm_hadr_availability_replica_states.replica_id - WHERE databases.name = @CurrentDatabaseName - END - - IF @Version >= 11 AND @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL - BEGIN - SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) - END - SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring WHERE database_id = @CurrentDatabaseID diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 1d681baa..43ccbc3d 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 13 April, 2018. +Last updated 20 April, 2018. Ola Hallengren https://ola.hallengren.com @@ -1077,14 +1077,14 @@ BEGIN IF @BackupSoftware = 'LITESPEED' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_backup_database') BEGIN - SET @ErrorMessage = 'LiteSpeed for SQL Server is not installed. Download http://software.dell.com/products/litespeed-for-sql-server/.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN - SET @ErrorMessage = 'Red Gate SQL Backup Pro is not installed. Download http://www.red-gate.com/products/dba/sql-backup/.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END @@ -1383,6 +1383,23 @@ BEGIN END END + IF @Version >= 11 AND @Cluster IS NOT NULL + BEGIN + SELECT @CurrentAvailabilityGroup = availability_groups.name, + @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) + FROM sys.databases databases + INNER JOIN sys.availability_databases_cluster availability_databases_cluster ON databases.group_database_id = availability_databases_cluster.group_database_id + INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id + INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON availability_groups.group_id = dm_hadr_availability_replica_states.group_id AND databases.replica_id = dm_hadr_availability_replica_states.replica_id + WHERE databases.name = @CurrentDatabaseName + END + + IF @Version >= 11 AND @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) + END + SELECT @CurrentDifferentialBaseLSN = differential_base_lsn FROM sys.master_files WHERE database_id = @CurrentDatabaseID @@ -1403,7 +1420,7 @@ BEGIN WHERE database_id = @CurrentDatabaseID END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 14 + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 14 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) BEGIN SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_file_space_usage' @@ -1440,23 +1457,6 @@ BEGIN AND checkpoint_lsn = @CurrentDifferentialBaseLSN END - IF @Version >= 11 AND @Cluster IS NOT NULL - BEGIN - SELECT @CurrentAvailabilityGroup = availability_groups.name, - @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, - @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) - FROM sys.databases databases - INNER JOIN sys.availability_databases_cluster availability_databases_cluster ON databases.group_database_id = availability_databases_cluster.group_database_id - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON availability_groups.group_id = dm_hadr_availability_replica_states.group_id AND databases.replica_id = dm_hadr_availability_replica_states.replica_id - WHERE databases.name = @CurrentDatabaseName - END - - IF @Version >= 11 AND @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL - BEGIN - SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) - END - SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring WHERE database_id = @CurrentDatabaseID From 503b14deb632310cf5f5eb218c6314d3c859fad8 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 20 Apr 2018 14:02:26 +0200 Subject: [PATCH 018/188] Add files via upload --- MaintenanceSolution.sql | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 43ccbc3d..39c1de16 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -5615,7 +5615,13 @@ BEGIN SET @CurrentJobStepCommand = @CurrentCommandTSQL SET @CurrentJobStepDatabaseName = @CurrentDatabaseName END - ELSE IF @CurrentCommandTSQL IS NOT NULL AND @HostPlatform = 'Windows' + ELSE IF @CurrentCommandTSQL IS NOT NULL AND @HostPlatform = 'Windows' AND @Version >= 11 + BEGIN + SET @CurrentJobStepSubSystem = 'TSQL' + SET @CurrentJobStepCommand = @CurrentCommandTSQL + SET @CurrentJobStepDatabaseName = @CurrentDatabaseName + END + ELSE IF @CurrentCommandTSQL IS NOT NULL AND @HostPlatform = 'Windows' AND @Version < 11 BEGIN SET @CurrentJobStepSubSystem = 'CMDEXEC' SET @CurrentJobStepCommand = 'sqlcmd -E -S ' + @TokenServer + ' -d ' + @CurrentDatabaseName + ' -Q "' + REPLACE(@CurrentCommandTSQL,(CHAR(13) + CHAR(10)),' ') + '" -b' From 4223da8f9a8880231c78354f7637a3d4cdefa9ff Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 24 Apr 2018 21:30:16 +0200 Subject: [PATCH 019/188] Add files via upload --- DatabaseBackup.sql | 14 +++++++------- IndexOptimize.sql | 4 ++-- MaintenanceSolution.sql | 20 ++++++++++---------- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 760407c0..12ebd5f6 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -968,21 +968,21 @@ BEGIN SET @Error = @@ERROR END - IF (@ModificationLevel IS NOT NULL AND NOT (@Version >= 14)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') + IF (@ModificationLevel IS NOT NULL AND NOT (@Version >= 13.05026)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN SET @ErrorMessage = 'The value for the parameter @ModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 14)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 13.05026)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 14)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 13.05026)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @TimeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1131,7 +1131,7 @@ BEGIN WHERE database_id = @CurrentDatabaseID END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 14 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 13.05026 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) BEGIN SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_file_space_usage' @@ -1152,7 +1152,7 @@ BEGIN END END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 14 + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 13.05026 BEGIN SELECT @CurrentLastLogBackup = log_backup_time, @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb @@ -1262,7 +1262,7 @@ BEGIN SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT - IF @CurrentBackupType IN('DIFF','FULL') AND @Version >= 14 + IF @CurrentBackupType IN('DIFF','FULL') AND @Version >= 13.05026 BEGIN SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT @@ -1271,7 +1271,7 @@ BEGIN RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT END - IF @CurrentBackupType = 'LOG' AND @Version >= 14 + IF @CurrentBackupType = 'LOG' AND @Version >= 13.05026 BEGIN SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),@CurrentLastLogBackup,120),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT diff --git a/IndexOptimize.sql b/IndexOptimize.sql index d6b3817d..6c02ac64 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -694,7 +694,7 @@ BEGIN SET @Error = @@ERROR END - IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP > 1 AND SERVERPROPERTY('EngineEdition') NOT IN (3,5)) + IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1586,7 +1586,7 @@ BEGIN SELECT 'NORECOMPUTE' END - IF @CurrentMaxDOP IS NOT NULL AND @Version >= 14.030154 + IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 39c1de16..76a02121 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 20 April, 2018. +Last updated 24 April, 2018. Ola Hallengren https://ola.hallengren.com @@ -1257,21 +1257,21 @@ BEGIN SET @Error = @@ERROR END - IF (@ModificationLevel IS NOT NULL AND NOT (@Version >= 14)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') + IF (@ModificationLevel IS NOT NULL AND NOT (@Version >= 13.05026)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN SET @ErrorMessage = 'The value for the parameter @ModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 14)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 13.05026)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 14)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 13.05026)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @TimeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1420,7 +1420,7 @@ BEGIN WHERE database_id = @CurrentDatabaseID END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 14 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 13.05026 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) BEGIN SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_file_space_usage' @@ -1441,7 +1441,7 @@ BEGIN END END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 14 + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 13.05026 BEGIN SELECT @CurrentLastLogBackup = log_backup_time, @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb @@ -1551,7 +1551,7 @@ BEGIN SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT - IF @CurrentBackupType IN('DIFF','FULL') AND @Version >= 14 + IF @CurrentBackupType IN('DIFF','FULL') AND @Version >= 13.05026 BEGIN SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT @@ -1560,7 +1560,7 @@ BEGIN RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT END - IF @CurrentBackupType = 'LOG' AND @Version >= 14 + IF @CurrentBackupType = 'LOG' AND @Version >= 13.05026 BEGIN SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),@CurrentLastLogBackup,120),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT @@ -4320,7 +4320,7 @@ BEGIN SET @Error = @@ERROR END - IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP > 1 AND SERVERPROPERTY('EngineEdition') NOT IN (3,5)) + IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -5212,7 +5212,7 @@ BEGIN SELECT 'NORECOMPUTE' END - IF @CurrentMaxDOP IS NOT NULL AND @Version >= 14.030154 + IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) From 5862c530346c15197ed9fe968c202225da7d5abc Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 27 Apr 2018 21:40:48 +0200 Subject: [PATCH 020/188] Add files via upload --- DatabaseBackup.sql | 88 ++++++++------- DatabaseIntegrityCheck.sql | 58 +++++----- IndexOptimize.sql | 61 +++++----- MaintenanceSolution.sql | 223 ++++++++++++++++++------------------- 4 files changed, 208 insertions(+), 222 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 12ebd5f6..fcb5c7c6 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -377,35 +377,35 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 AND SERVERPROPERTY('EngineEdition') <> 5 - BEGIN - INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, Selected, Completed) - SELECT [name] AS DatabaseName, - LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id) THEN 1 ELSE 0 END AS AvailabilityGroup, - 0 AS Selected, - 0 AS Completed - FROM sys.databases - WHERE [name] <> 'tempdb' - AND source_database_id IS NULL - ORDER BY [name] ASC - END - ELSE + IF @Version >= 11 BEGIN - INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, Selected, Completed) - SELECT [name] AS DatabaseName, - LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - NULL AS AvailabilityGroup, - 0 AS Selected, - 0 AS Completed - FROM sys.databases - WHERE [name] <> 'tempdb' - AND source_database_id IS NULL - ORDER BY [name] ASC + INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) + SELECT name AS AvailabilityGroupName, + 0 AS Selected + FROM sys.availability_groups + + INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) + SELECT availability_databases_cluster.database_name, availability_groups.name + FROM sys.availability_databases_cluster availability_databases_cluster + INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END + INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, Selected, Completed) + SELECT [name] AS DatabaseName, + LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, + CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + NULL AS AvailabilityGroup, + 0 AS Selected, + 0 AS Completed + FROM sys.databases + WHERE [name] <> 'tempdb' + AND source_database_id IS NULL + ORDER BY [name] ASC + + UPDATE tmpDatabases + SET AvailabilityGroup = CASE WHEN EXISTS (SELECT * FROM @tmpDatabasesAvailabilityGroups WHERE DatabaseName = tmpDatabases.DatabaseName) THEN 1 ELSE 0 END + FROM @tmpDatabases tmpDatabases + UPDATE tmpDatabases SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases @@ -482,11 +482,6 @@ BEGIN FROM AvailabilityGroups4 OPTION (MAXRECURSION 0) - INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT name AS AvailabilityGroupName, - 0 AS Selected - FROM sys.availability_groups - UPDATE tmpAvailabilityGroups SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups @@ -501,11 +496,6 @@ BEGIN ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 - INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) - SELECT availability_databases_cluster.database_name, availability_groups.name - FROM sys.availability_databases_cluster availability_databases_cluster - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id - UPDATE tmpDatabases SET Selected = 1 FROM @tmpDatabases tmpDatabases @@ -576,8 +566,15 @@ BEGIN BEGIN EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultDirectory OUTPUT - INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) - SELECT 1, @DefaultDirectory, 0, 0 + IF @DefaultDirectory LIKE 'http://%' OR @DefaultDirectory LIKE 'https://%' + BEGIN + SET @URL = @DefaultDirectory + END + ELSE + BEGIN + INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) + SELECT 1, @DefaultDirectory, 0, 0 + END END IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Linux' BEGIN @@ -651,7 +648,7 @@ BEGIN SET @DirectoryCheck = 1 - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) BEGIN SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -659,7 +656,7 @@ BEGIN SET @DirectoryCheck = 0 END - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -737,6 +734,13 @@ BEGIN SET @Error = @@ERROR END + IF SERVERPROPERTY('EngineEdition') = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') + BEGIN + SET @ErrorMessage = 'SQL Database Managed Instance only supports COPY_ONLY full backups.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') BEGIN SET @ErrorMessage = 'The value for the parameter @Verify is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -758,7 +762,7 @@ BEGIN SET @Error = @@ERROR END - IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') = 3 OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IS NOT NULL AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IS NOT NULL AND @CompressionLevel = 0) + IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IS NOT NULL AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IS NOT NULL AND @CompressionLevel = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @Compress is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -933,7 +937,7 @@ BEGIN SET @Error = @@ERROR END - IF (@Credential IS NULL AND @URL IS NOT NULL AND @Version < 13) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE credential_identity = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) + IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE credential_identity = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) BEGIN SET @ErrorMessage = 'The value for the parameter @Credential is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 0d49ebb6..8be38b6d 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -308,31 +308,33 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 AND SERVERPROPERTY('EngineEdition') <> 5 + IF @Version >= 11 BEGIN - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], Selected, Completed) - SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id) THEN 1 ELSE 0 END AS AvailabilityGroup, - CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], - 0 AS Selected, - 0 AS Completed - FROM sys.databases - ORDER BY [name] ASC - END - ELSE - BEGIN - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], Selected, Completed) - SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - NULL AS AvailabilityGroup, - CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], - 0 AS Selected, - 0 AS Completed - FROM sys.databases - ORDER BY [name] ASC + INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) + SELECT name AS AvailabilityGroupName, + 0 AS Selected + FROM sys.availability_groups + + INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) + SELECT availability_databases_cluster.database_name, availability_groups.name + FROM sys.availability_databases_cluster availability_databases_cluster + INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], Selected, Completed) + SELECT [name] AS DatabaseName, + CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + NULL AS AvailabilityGroup, + CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], + 0 AS Selected, + 0 AS Completed + FROM sys.databases + ORDER BY [name] ASC + + UPDATE tmpDatabases + SET AvailabilityGroup = CASE WHEN EXISTS (SELECT * FROM @tmpDatabasesAvailabilityGroups WHERE DatabaseName = tmpDatabases.DatabaseName) THEN 1 ELSE 0 END + FROM @tmpDatabases tmpDatabases + UPDATE tmpDatabases SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases @@ -411,11 +413,6 @@ BEGIN FROM AvailabilityGroups4 OPTION (MAXRECURSION 0) - INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT name AS AvailabilityGroupName, - 0 AS Selected - FROM sys.availability_groups - UPDATE tmpAvailabilityGroups SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups @@ -430,11 +427,6 @@ BEGIN ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 - INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) - SELECT availability_databases_cluster.database_name, availability_groups.name - FROM sys.availability_databases_cluster availability_databases_cluster - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id - UPDATE tmpDatabases SET Selected = 1 FROM @tmpDatabases tmpDatabases @@ -639,7 +631,7 @@ BEGIN SET @Error = @@ERROR END - IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP > 1 AND SERVERPROPERTY('EngineEdition') NOT IN (3,5)) OR (@MaxDOP IS NOT NULL AND @Version < 12.050000) + IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) BEGIN SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 6c02ac64..c4d1a957 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -366,33 +366,34 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 AND SERVERPROPERTY('EngineEdition') <> 5 + IF @Version >= 11 BEGIN - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected, Completed) - SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id) THEN 1 ELSE 0 END AS AvailabilityGroup, - 0 AS Selected, - 0 AS Completed - FROM sys.databases - WHERE [name] <> 'tempdb' - AND source_database_id IS NULL - ORDER BY [name] ASC - END - ELSE - BEGIN - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected, Completed) - SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - NULL AS AvailabilityGroup, - 0 AS Selected, - 0 AS Completed - FROM sys.databases - WHERE [name] <> 'tempdb' - AND source_database_id IS NULL - ORDER BY [name] ASC + INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) + SELECT name AS AvailabilityGroupName, + 0 AS Selected + FROM sys.availability_groups + + INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) + SELECT availability_databases_cluster.database_name, availability_groups.name + FROM sys.availability_databases_cluster availability_databases_cluster + INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected, Completed) + SELECT [name] AS DatabaseName, + CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + NULL AS AvailabilityGroup, + 0 AS Selected, + 0 AS Completed + FROM sys.databases + WHERE [name] <> 'tempdb' + AND source_database_id IS NULL + ORDER BY [name] ASC + + UPDATE tmpDatabases + SET AvailabilityGroup = CASE WHEN EXISTS (SELECT * FROM @tmpDatabasesAvailabilityGroups WHERE DatabaseName = tmpDatabases.DatabaseName) THEN 1 ELSE 0 END + FROM @tmpDatabases tmpDatabases + UPDATE tmpDatabases SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases @@ -469,11 +470,6 @@ BEGIN FROM AvailabilityGroups4 OPTION (MAXRECURSION 0) - INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT name AS AvailabilityGroupName, - 0 AS Selected - FROM sys.availability_groups - UPDATE tmpAvailabilityGroups SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups @@ -488,11 +484,6 @@ BEGIN ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 - INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) - SELECT availability_databases_cluster.database_name, availability_groups.name - FROM sys.availability_databases_cluster availability_databases_cluster - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id - UPDATE tmpDatabases SET Selected = 1 FROM @tmpDatabases tmpDatabases @@ -1417,7 +1408,7 @@ BEGIN OR (@CurrentIndexType = 1 AND @CurrentIsImageText = 0 AND @CurrentIsFileStream = 0 AND @Version >= 11) OR (@CurrentIndexType = 2 AND @Version >= 11)) AND (@CurrentIsColumnStore = 0 OR @Version < 11) - AND SERVERPROPERTY('EngineEdition') IN (3,5) + AND SERVERPROPERTY('EngineEdition') IN (3,5,8) BEGIN INSERT INTO @CurrentActionsAllowed ([Action]) VALUES ('INDEX_REBUILD_ONLINE') diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 76a02121..a69c050b 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 24 April, 2018. +Last updated 27 April, 2018. Ola Hallengren https://ola.hallengren.com @@ -666,35 +666,35 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 AND SERVERPROPERTY('EngineEdition') <> 5 - BEGIN - INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, Selected, Completed) - SELECT [name] AS DatabaseName, - LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id) THEN 1 ELSE 0 END AS AvailabilityGroup, - 0 AS Selected, - 0 AS Completed - FROM sys.databases - WHERE [name] <> 'tempdb' - AND source_database_id IS NULL - ORDER BY [name] ASC - END - ELSE + IF @Version >= 11 BEGIN - INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, Selected, Completed) - SELECT [name] AS DatabaseName, - LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - NULL AS AvailabilityGroup, - 0 AS Selected, - 0 AS Completed - FROM sys.databases - WHERE [name] <> 'tempdb' - AND source_database_id IS NULL - ORDER BY [name] ASC + INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) + SELECT name AS AvailabilityGroupName, + 0 AS Selected + FROM sys.availability_groups + + INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) + SELECT availability_databases_cluster.database_name, availability_groups.name + FROM sys.availability_databases_cluster availability_databases_cluster + INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END + INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, Selected, Completed) + SELECT [name] AS DatabaseName, + LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, + CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + NULL AS AvailabilityGroup, + 0 AS Selected, + 0 AS Completed + FROM sys.databases + WHERE [name] <> 'tempdb' + AND source_database_id IS NULL + ORDER BY [name] ASC + + UPDATE tmpDatabases + SET AvailabilityGroup = CASE WHEN EXISTS (SELECT * FROM @tmpDatabasesAvailabilityGroups WHERE DatabaseName = tmpDatabases.DatabaseName) THEN 1 ELSE 0 END + FROM @tmpDatabases tmpDatabases + UPDATE tmpDatabases SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases @@ -771,11 +771,6 @@ BEGIN FROM AvailabilityGroups4 OPTION (MAXRECURSION 0) - INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT name AS AvailabilityGroupName, - 0 AS Selected - FROM sys.availability_groups - UPDATE tmpAvailabilityGroups SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups @@ -790,11 +785,6 @@ BEGIN ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 - INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) - SELECT availability_databases_cluster.database_name, availability_groups.name - FROM sys.availability_databases_cluster availability_databases_cluster - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id - UPDATE tmpDatabases SET Selected = 1 FROM @tmpDatabases tmpDatabases @@ -865,8 +855,15 @@ BEGIN BEGIN EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultDirectory OUTPUT - INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) - SELECT 1, @DefaultDirectory, 0, 0 + IF @DefaultDirectory LIKE 'http://%' OR @DefaultDirectory LIKE 'https://%' + BEGIN + SET @URL = @DefaultDirectory + END + ELSE + BEGIN + INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) + SELECT 1, @DefaultDirectory, 0, 0 + END END IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Linux' BEGIN @@ -940,7 +937,7 @@ BEGIN SET @DirectoryCheck = 1 - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) BEGIN SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -948,7 +945,7 @@ BEGIN SET @DirectoryCheck = 0 END - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1026,6 +1023,13 @@ BEGIN SET @Error = @@ERROR END + IF SERVERPROPERTY('EngineEdition') = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') + BEGIN + SET @ErrorMessage = 'SQL Database Managed Instance only supports COPY_ONLY full backups.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') BEGIN SET @ErrorMessage = 'The value for the parameter @Verify is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1047,7 +1051,7 @@ BEGIN SET @Error = @@ERROR END - IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') = 3 OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IS NOT NULL AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IS NOT NULL AND @CompressionLevel = 0) + IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IS NOT NULL AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IS NOT NULL AND @CompressionLevel = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @Compress is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1222,7 +1226,7 @@ BEGIN SET @Error = @@ERROR END - IF (@Credential IS NULL AND @URL IS NOT NULL AND @Version < 13) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE credential_identity = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) + IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE credential_identity = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) BEGIN SET @ErrorMessage = 'The value for the parameter @Credential is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -2682,31 +2686,33 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 AND SERVERPROPERTY('EngineEdition') <> 5 - BEGIN - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], Selected, Completed) - SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id) THEN 1 ELSE 0 END AS AvailabilityGroup, - CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], - 0 AS Selected, - 0 AS Completed - FROM sys.databases - ORDER BY [name] ASC - END - ELSE + IF @Version >= 11 BEGIN - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], Selected, Completed) - SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - NULL AS AvailabilityGroup, - CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], - 0 AS Selected, - 0 AS Completed - FROM sys.databases - ORDER BY [name] ASC + INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) + SELECT name AS AvailabilityGroupName, + 0 AS Selected + FROM sys.availability_groups + + INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) + SELECT availability_databases_cluster.database_name, availability_groups.name + FROM sys.availability_databases_cluster availability_databases_cluster + INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], Selected, Completed) + SELECT [name] AS DatabaseName, + CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + NULL AS AvailabilityGroup, + CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], + 0 AS Selected, + 0 AS Completed + FROM sys.databases + ORDER BY [name] ASC + + UPDATE tmpDatabases + SET AvailabilityGroup = CASE WHEN EXISTS (SELECT * FROM @tmpDatabasesAvailabilityGroups WHERE DatabaseName = tmpDatabases.DatabaseName) THEN 1 ELSE 0 END + FROM @tmpDatabases tmpDatabases + UPDATE tmpDatabases SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases @@ -2785,11 +2791,6 @@ BEGIN FROM AvailabilityGroups4 OPTION (MAXRECURSION 0) - INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT name AS AvailabilityGroupName, - 0 AS Selected - FROM sys.availability_groups - UPDATE tmpAvailabilityGroups SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups @@ -2804,11 +2805,6 @@ BEGIN ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 - INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) - SELECT availability_databases_cluster.database_name, availability_groups.name - FROM sys.availability_databases_cluster availability_databases_cluster - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id - UPDATE tmpDatabases SET Selected = 1 FROM @tmpDatabases tmpDatabases @@ -3013,7 +3009,7 @@ BEGIN SET @Error = @@ERROR END - IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP > 1 AND SERVERPROPERTY('EngineEdition') NOT IN (3,5)) OR (@MaxDOP IS NOT NULL AND @Version < 12.050000) + IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) BEGIN SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -3992,33 +3988,34 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 AND SERVERPROPERTY('EngineEdition') <> 5 - BEGIN - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected, Completed) - SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - CASE WHEN name IN (SELECT availability_databases_cluster.database_name FROM sys.availability_databases_cluster availability_databases_cluster INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id) THEN 1 ELSE 0 END AS AvailabilityGroup, - 0 AS Selected, - 0 AS Completed - FROM sys.databases - WHERE [name] <> 'tempdb' - AND source_database_id IS NULL - ORDER BY [name] ASC - END - ELSE + IF @Version >= 11 BEGIN - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected, Completed) - SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - NULL AS AvailabilityGroup, - 0 AS Selected, - 0 AS Completed - FROM sys.databases - WHERE [name] <> 'tempdb' - AND source_database_id IS NULL - ORDER BY [name] ASC + INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) + SELECT name AS AvailabilityGroupName, + 0 AS Selected + FROM sys.availability_groups + + INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) + SELECT availability_databases_cluster.database_name, availability_groups.name + FROM sys.availability_databases_cluster availability_databases_cluster + INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected, Completed) + SELECT [name] AS DatabaseName, + CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + NULL AS AvailabilityGroup, + 0 AS Selected, + 0 AS Completed + FROM sys.databases + WHERE [name] <> 'tempdb' + AND source_database_id IS NULL + ORDER BY [name] ASC + + UPDATE tmpDatabases + SET AvailabilityGroup = CASE WHEN EXISTS (SELECT * FROM @tmpDatabasesAvailabilityGroups WHERE DatabaseName = tmpDatabases.DatabaseName) THEN 1 ELSE 0 END + FROM @tmpDatabases tmpDatabases + UPDATE tmpDatabases SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases @@ -4095,11 +4092,6 @@ BEGIN FROM AvailabilityGroups4 OPTION (MAXRECURSION 0) - INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT name AS AvailabilityGroupName, - 0 AS Selected - FROM sys.availability_groups - UPDATE tmpAvailabilityGroups SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups @@ -4114,11 +4106,6 @@ BEGIN ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 - INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) - SELECT availability_databases_cluster.database_name, availability_groups.name - FROM sys.availability_databases_cluster availability_databases_cluster - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id - UPDATE tmpDatabases SET Selected = 1 FROM @tmpDatabases tmpDatabases @@ -5043,7 +5030,7 @@ BEGIN OR (@CurrentIndexType = 1 AND @CurrentIsImageText = 0 AND @CurrentIsFileStream = 0 AND @Version >= 11) OR (@CurrentIndexType = 2 AND @Version >= 11)) AND (@CurrentIsColumnStore = 0 OR @Version < 11) - AND SERVERPROPERTY('EngineEdition') IN (3,5) + AND SERVERPROPERTY('EngineEdition') IN (3,5,8) BEGIN INSERT INTO @CurrentActionsAllowed ([Action]) VALUES ('INDEX_REBUILD_ONLINE') @@ -5577,6 +5564,12 @@ BEGIN SET Selected = 1 WHERE [Name] IN('DatabaseIntegrityCheck - USER_DATABASES','IndexOptimize - USER_DATABASES','CommandLog Cleanup') END + ELSE IF SERVERPROPERTY('EngineEdition') = 8 + BEGIN + UPDATE @Jobs + SET Selected = 1 + WHERE [Name] IN('DatabaseIntegrityCheck - SYSTEM_DATABASES','DatabaseIntegrityCheck - USER_DATABASES','IndexOptimize - USER_DATABASES','CommandLog Cleanup','sp_delete_backuphistory','sp_purge_jobhistory') + END ELSE IF @HostPlatform = 'Windows' BEGIN UPDATE @Jobs @@ -5609,6 +5602,12 @@ BEGIN SET @CurrentJobStepCommand = @CurrentCommandTSQL SET @CurrentJobStepDatabaseName = @CurrentDatabaseName END + ELSE IF @CurrentCommandTSQL IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8 + BEGIN + SET @CurrentJobStepSubSystem = 'TSQL' + SET @CurrentJobStepCommand = @CurrentCommandTSQL + SET @CurrentJobStepDatabaseName = @CurrentDatabaseName + END ELSE IF @CurrentCommandTSQL IS NOT NULL AND @HostPlatform = 'Linux' BEGIN SET @CurrentJobStepSubSystem = 'TSQL' @@ -5634,7 +5633,7 @@ BEGIN SET @CurrentJobStepDatabaseName = NULL END - IF @AmazonRDS = 0 + IF @AmazonRDS = 0 AND SERVERPROPERTY('EngineEdition') <> 8 BEGIN SET @CurrentOutputFileName = COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + @DirectorySeparator + ISNULL(@CurrentOutputFileNamePart01 + '_','') + ISNULL(@CurrentOutputFileNamePart02 + '_','') + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' IF LEN(@CurrentOutputFileName) > 200 SET @CurrentOutputFileName = COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + @DirectorySeparator + ISNULL(@CurrentOutputFileNamePart01 + '_','') + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' From 6e28025383ee0ee4c2167f20c798a73c827382c8 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 28 Apr 2018 12:14:31 +0200 Subject: [PATCH 021/188] Add files via upload --- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 10 +++++----- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index fcb5c7c6..a8117e77 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -377,7 +377,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 8be38b6d..dcb8d506 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -308,7 +308,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, diff --git a/IndexOptimize.sql b/IndexOptimize.sql index c4d1a957..d5d80d11 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -366,7 +366,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index a69c050b..2ed848eb 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 27 April, 2018. +Last updated 28 April, 2018. Ola Hallengren https://ola.hallengren.com @@ -666,7 +666,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, @@ -2686,7 +2686,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, @@ -3988,7 +3988,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, @@ -5348,7 +5348,7 @@ BEGIN END GO -IF (SELECT [Value] FROM #Config WHERE Name = 'CreateJobs') = 'Y' AND SERVERPROPERTY('EngineEdition') <> 4 AND (IS_SRVROLEMEMBER('sysadmin') = 1 OR (DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa')) +IF (SELECT [Value] FROM #Config WHERE Name = 'CreateJobs') = 'Y' AND SERVERPROPERTY('EngineEdition') NOT IN(4, 5) AND (IS_SRVROLEMEMBER('sysadmin') = 1 OR (DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa')) BEGIN DECLARE @BackupDirectory nvarchar(max) From e0fa1a9cb8e30ad939c03d23bc6e79737c68a984 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 9 May 2018 19:59:09 +0200 Subject: [PATCH 022/188] Add files via upload --- DatabaseBackup.sql | 122 +++++++++++++++++++++++++++++----- DatabaseIntegrityCheck.sql | 7 -- MaintenanceSolution.sql | 131 ++++++++++++++++++++++++++++++------- 3 files changed, 213 insertions(+), 47 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index a8117e77..eaca0cee 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -47,6 +47,10 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @ModificationLevel int = NULL, @LogSizeSinceLastLogBackup int = NULL, @TimeSinceLastLogBackup int = NULL, +@DataDomainBoostHost nvarchar(max) = NULL, +@DataDomainBoostUser nvarchar(max) = NULL, +@DataDomainBoostDevicePath nvarchar(max) = NULL, +@DataDomainBoostLockboxPath nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -256,6 +260,10 @@ BEGIN SET @Parameters = @Parameters + ', @ModificationLevel = ' + ISNULL(CAST(@ModificationLevel AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @DataDomainBoostHost = ' + ISNULL('''' + REPLACE(@DataDomainBoostHost,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DataDomainBoostUser = ' + ISNULL('''' + REPLACE(@DataDomainBoostUser,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DataDomainBoostDevicePath = ' + ISNULL('''' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DataDomainBoostLockboxPath = ' + ISNULL('''' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -562,7 +570,7 @@ BEGIN --// Select directories //-- ---------------------------------------------------------------------------------------------------- - IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Windows' + IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultDirectory OUTPUT @@ -648,7 +656,7 @@ BEGIN SET @DirectoryCheck = 1 - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -656,7 +664,7 @@ BEGIN SET @DirectoryCheck = 0 END - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -720,7 +728,7 @@ BEGIN IF @NumberOfFiles IS NULL BEGIN - SELECT @NumberOfFiles = CASE WHEN @URL IS NOT NULL THEN 1 ELSE (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) END + SELECT @NumberOfFiles = CASE WHEN @URL IS NOT NULL THEN 1 WHEN @BackupSoftware = 'DATA_DOMAIN_BOOST' THEN 1 ELSE (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) END END ---------------------------------------------------------------------------------------------------- @@ -741,7 +749,7 @@ BEGIN SET @Error = @@ERROR END - IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') + IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @Verify is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -762,7 +770,7 @@ BEGIN SET @Error = @@ERROR END - IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IS NOT NULL AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IS NOT NULL AND @CompressionLevel = 0) + IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @Compress is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -783,7 +791,7 @@ BEGIN SET @Error = @@ERROR END - IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') + IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN SET @ErrorMessage = 'The value for the parameter @BackupSoftware is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -811,6 +819,13 @@ BEGIN SET @Error = @@ERROR END + IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'PC' AND [name] = 'emc_run_backup') + BEGIN + SET @ErrorMessage = 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @CheckSum NOT IN ('Y','N') OR @CheckSum IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @CheckSum is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -818,7 +833,7 @@ BEGIN SET @Error = @@ERROR END - IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) + IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @BlockSize is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -832,28 +847,28 @@ BEGIN SET @Error = @@ERROR END - IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) + IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @MaxTransferSize is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) + IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @NumberOfFiles is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) + IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @CompressionLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF LEN(@Description) > 255 OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) + IF LEN(@Description) > 255 OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) BEGIN SET @ErrorMessage = 'The value for the parameter @Description is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -874,14 +889,14 @@ BEGIN SET @Error = @@ERROR END - IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) + IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @Encrypt is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) + IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @EncryptionAlgorithm is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -902,7 +917,7 @@ BEGIN SET @Error = @@ERROR END - IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) + IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @EncryptionKey is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -993,6 +1008,34 @@ BEGIN SET @Error = @@ERROR END + IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + BEGIN + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostHost is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + BEGIN + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostUser is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + BEGIN + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostDevicePath is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + BEGIN + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostLockboxPath is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1455,6 +1498,7 @@ BEGIN -- Create directory IF @HostPlatform = 'Windows' + AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN WHILE (1 = 1) BEGIN @@ -1527,6 +1571,7 @@ BEGIN -- Delete old backup files, before backup IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateOutput <> 0 OR CreateOutput IS NULL) AND @HostPlatform = 'Windows' + AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) AND @CurrentBackupType = @BackupType BEGIN WHILE (1 = 1) @@ -1793,13 +1838,57 @@ BEGIN SET @CurrentCommand03 = @CurrentCommand03 + ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' END + IF @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + SET @CurrentCommandType03 = 'emc_run_backup' + + SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.emc_run_backup ''' + + SET @CurrentCommand03 = @CurrentCommand03 + ' -c ' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar) END + + SET @CurrentCommand03 = @CurrentCommand03 + ' -l ' + CASE + WHEN @CurrentBackupType = 'FULL' THEN 'full' + WHEN @CurrentBackupType = 'DIFF' THEN 'diff' + WHEN @CurrentBackupType = 'LOG' THEN 'incr' + END + + IF @NoRecovery = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ' -H' + + IF @CleanupTime IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -y +' + CAST(@CleanupTime/24 + CASE WHEN @CleanupTime%24 > 0 THEN 1 ELSE 0 END AS nvarchar) + 'd' + + IF @CheckSum = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ' -k' + + SET @CurrentCommand03 = @CurrentCommand03 + ' -S ' + CAST(@NumberOfFiles AS nvarchar) + + IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -b "' + REPLACE(@Description,'''','''''') + '"' + + IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -O "BUFFERCOUNT=' + CAST(@BufferCount AS nvarchar) + '"' + + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ' -O "READ_WRITE_FILEGROUPS"' + + SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI=TRUE"' + SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_USE_DD=TRUE"' + IF @DataDomainBoostHost IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_HOST=' + REPLACE(@DataDomainBoostHost,'''','''''') + '"' + IF @DataDomainBoostUser IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_USER=' + REPLACE(@DataDomainBoostUser,'''','''''') + '"' + IF @DataDomainBoostDevicePath IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DEVICE_PATH=' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '"' + IF @DataDomainBoostLockboxPath IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_LOCKBOX_PATH=' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '"' + SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_SKIP_NON_BACKUPABLE_STATE_DB=TRUE"' + IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_COPY_ONLY=TRUE"' + + IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand03 = @CurrentCommand03 + ' "MSSQL' + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' + IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar) + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' + + SET @CurrentCommand03 = @CurrentCommand03 + '''' + + SET @CurrentCommand03 = @CurrentCommand03 + ' IF @ReturnCode <> 0 RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' + END + EXECUTE @CurrentCommandOutput03 = [dbo].[CommandExecute] @Command = @CurrentCommand03, @CommandType = @CurrentCommandType03, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput03 = @Error IF @CurrentCommandOutput03 <> 0 SET @ReturnCode = @CurrentCommandOutput03 END - -- Verify the backup IF @CurrentCommandOutput03 = 0 AND @Verify = 'Y' BEGIN @@ -1943,6 +2032,7 @@ BEGIN IF ((@CurrentCommandOutput03 = 0 AND @Verify = 'N') OR (@CurrentCommandOutput03 = 0 AND @Verify = 'Y' AND NOT EXISTS (SELECT * FROM @CurrentBackupSet WHERE VerifyOutput <> 0 OR VerifyOutput IS NULL))) AND @HostPlatform = 'Windows' + AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) AND @CurrentBackupType = @BackupType BEGIN WHILE (1 = 1) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index dcb8d506..a580ca06 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -240,13 +240,6 @@ BEGIN SET @Error = @@ERROR END - IF SERVERPROPERTY('EngineEdition') = 5 AND @Version < 12 - BEGIN - SET @ErrorMessage = 'The stored procedure DatabaseIntegrityCheck is not supported on this version of Azure SQL Database.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - SET @Error = @@ERROR - END - IF @Error <> 0 BEGIN SET @ReturnCode = @Error diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 2ed848eb..279b3770 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 28 April, 2018. +Last updated 9 May, 2018. Ola Hallengren https://ola.hallengren.com @@ -336,6 +336,10 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @ModificationLevel int = NULL, @LogSizeSinceLastLogBackup int = NULL, @TimeSinceLastLogBackup int = NULL, +@DataDomainBoostHost nvarchar(max) = NULL, +@DataDomainBoostUser nvarchar(max) = NULL, +@DataDomainBoostDevicePath nvarchar(max) = NULL, +@DataDomainBoostLockboxPath nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -545,6 +549,10 @@ BEGIN SET @Parameters = @Parameters + ', @ModificationLevel = ' + ISNULL(CAST(@ModificationLevel AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @DataDomainBoostHost = ' + ISNULL('''' + REPLACE(@DataDomainBoostHost,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DataDomainBoostUser = ' + ISNULL('''' + REPLACE(@DataDomainBoostUser,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DataDomainBoostDevicePath = ' + ISNULL('''' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DataDomainBoostLockboxPath = ' + ISNULL('''' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -851,7 +859,7 @@ BEGIN --// Select directories //-- ---------------------------------------------------------------------------------------------------- - IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Windows' + IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultDirectory OUTPUT @@ -937,7 +945,7 @@ BEGIN SET @DirectoryCheck = 1 - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -945,7 +953,7 @@ BEGIN SET @DirectoryCheck = 0 END - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1009,7 +1017,7 @@ BEGIN IF @NumberOfFiles IS NULL BEGIN - SELECT @NumberOfFiles = CASE WHEN @URL IS NOT NULL THEN 1 ELSE (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) END + SELECT @NumberOfFiles = CASE WHEN @URL IS NOT NULL THEN 1 WHEN @BackupSoftware = 'DATA_DOMAIN_BOOST' THEN 1 ELSE (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) END END ---------------------------------------------------------------------------------------------------- @@ -1030,7 +1038,7 @@ BEGIN SET @Error = @@ERROR END - IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') + IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @Verify is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1051,7 +1059,7 @@ BEGIN SET @Error = @@ERROR END - IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IS NOT NULL AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IS NOT NULL AND @CompressionLevel = 0) + IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @Compress is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1072,7 +1080,7 @@ BEGIN SET @Error = @@ERROR END - IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') + IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN SET @ErrorMessage = 'The value for the parameter @BackupSoftware is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1100,6 +1108,13 @@ BEGIN SET @Error = @@ERROR END + IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'PC' AND [name] = 'emc_run_backup') + BEGIN + SET @ErrorMessage = 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @CheckSum NOT IN ('Y','N') OR @CheckSum IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @CheckSum is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1107,7 +1122,7 @@ BEGIN SET @Error = @@ERROR END - IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) + IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @BlockSize is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1121,28 +1136,28 @@ BEGIN SET @Error = @@ERROR END - IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) + IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @MaxTransferSize is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) + IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @NumberOfFiles is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) + IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @CompressionLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF LEN(@Description) > 255 OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) + IF LEN(@Description) > 255 OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) BEGIN SET @ErrorMessage = 'The value for the parameter @Description is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1163,14 +1178,14 @@ BEGIN SET @Error = @@ERROR END - IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) + IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @Encrypt is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) + IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @EncryptionAlgorithm is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1191,7 +1206,7 @@ BEGIN SET @Error = @@ERROR END - IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) + IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @EncryptionKey is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1282,6 +1297,34 @@ BEGIN SET @Error = @@ERROR END + IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + BEGIN + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostHost is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + BEGIN + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostUser is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + BEGIN + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostDevicePath is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + BEGIN + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostLockboxPath is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1744,6 +1787,7 @@ BEGIN -- Create directory IF @HostPlatform = 'Windows' + AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN WHILE (1 = 1) BEGIN @@ -1816,6 +1860,7 @@ BEGIN -- Delete old backup files, before backup IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateOutput <> 0 OR CreateOutput IS NULL) AND @HostPlatform = 'Windows' + AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) AND @CurrentBackupType = @BackupType BEGIN WHILE (1 = 1) @@ -2082,13 +2127,57 @@ BEGIN SET @CurrentCommand03 = @CurrentCommand03 + ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' END + IF @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + SET @CurrentCommandType03 = 'emc_run_backup' + + SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.emc_run_backup ''' + + SET @CurrentCommand03 = @CurrentCommand03 + ' -c ' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar) END + + SET @CurrentCommand03 = @CurrentCommand03 + ' -l ' + CASE + WHEN @CurrentBackupType = 'FULL' THEN 'full' + WHEN @CurrentBackupType = 'DIFF' THEN 'diff' + WHEN @CurrentBackupType = 'LOG' THEN 'incr' + END + + IF @NoRecovery = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ' -H' + + IF @CleanupTime IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -y +' + CAST(@CleanupTime/24 + CASE WHEN @CleanupTime%24 > 0 THEN 1 ELSE 0 END AS nvarchar) + 'd' + + IF @CheckSum = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ' -k' + + SET @CurrentCommand03 = @CurrentCommand03 + ' -S ' + CAST(@NumberOfFiles AS nvarchar) + + IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -b "' + REPLACE(@Description,'''','''''') + '"' + + IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -O "BUFFERCOUNT=' + CAST(@BufferCount AS nvarchar) + '"' + + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ' -O "READ_WRITE_FILEGROUPS"' + + SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI=TRUE"' + SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_USE_DD=TRUE"' + IF @DataDomainBoostHost IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_HOST=' + REPLACE(@DataDomainBoostHost,'''','''''') + '"' + IF @DataDomainBoostUser IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_USER=' + REPLACE(@DataDomainBoostUser,'''','''''') + '"' + IF @DataDomainBoostDevicePath IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DEVICE_PATH=' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '"' + IF @DataDomainBoostLockboxPath IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_LOCKBOX_PATH=' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '"' + SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_SKIP_NON_BACKUPABLE_STATE_DB=TRUE"' + IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_COPY_ONLY=TRUE"' + + IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand03 = @CurrentCommand03 + ' "MSSQL' + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' + IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar) + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' + + SET @CurrentCommand03 = @CurrentCommand03 + '''' + + SET @CurrentCommand03 = @CurrentCommand03 + ' IF @ReturnCode <> 0 RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' + END + EXECUTE @CurrentCommandOutput03 = [dbo].[CommandExecute] @Command = @CurrentCommand03, @CommandType = @CurrentCommandType03, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput03 = @Error IF @CurrentCommandOutput03 <> 0 SET @ReturnCode = @CurrentCommandOutput03 END - -- Verify the backup IF @CurrentCommandOutput03 = 0 AND @Verify = 'Y' BEGIN @@ -2232,6 +2321,7 @@ BEGIN IF ((@CurrentCommandOutput03 = 0 AND @Verify = 'N') OR (@CurrentCommandOutput03 = 0 AND @Verify = 'Y' AND NOT EXISTS (SELECT * FROM @CurrentBackupSet WHERE VerifyOutput <> 0 OR VerifyOutput IS NULL))) AND @HostPlatform = 'Windows' + AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) AND @CurrentBackupType = @BackupType BEGIN WHILE (1 = 1) @@ -2618,13 +2708,6 @@ BEGIN SET @Error = @@ERROR END - IF SERVERPROPERTY('EngineEdition') = 5 AND @Version < 12 - BEGIN - SET @ErrorMessage = 'The stored procedure DatabaseIntegrityCheck is not supported on this version of Azure SQL Database.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - SET @Error = @@ERROR - END - IF @Error <> 0 BEGIN SET @ReturnCode = @Error From 625623fbc8c1dd0046821549aba47726e74ac80d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 10 May 2018 22:09:43 +0200 Subject: [PATCH 023/188] Add files via upload --- DatabaseBackup.sql | 43 +++++++++++++++++++-------------------- MaintenanceSolution.sql | 45 ++++++++++++++++++++--------------------- 2 files changed, 43 insertions(+), 45 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index eaca0cee..e4a1e053 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -1429,9 +1429,8 @@ BEGIN INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) SELECT 0, 0 END - ELSE - IF @URL IS NOT NULL + IF EXISTS (SELECT * FROM @CurrentDirectories WHERE Mirror = 1) BEGIN SET @CurrentFileNumber = 0 @@ -1439,27 +1438,36 @@ BEGIN BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SELECT @CurrentDirectoryPath = DirectoryPath + FROM @CurrentDirectories + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) + AND Mirror = 1 + + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) - SELECT 'URL', @CurrentFilePath, 0 + SELECT 'DISK', @CurrentFilePath, 1 + + SET @CurrentDirectoryPath = NULL + SET @CurrentFilePath = NULL END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) - SELECT 0, 0 + SELECT 1, 0 END - IF EXISTS (SELECT * FROM @CurrentDirectories WHERE Mirror = 1) + IF @URL IS NOT NULL BEGIN SET @CurrentFileNumber = 0 @@ -1467,33 +1475,24 @@ BEGIN BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 - SELECT @CurrentDirectoryPath = DirectoryPath - FROM @CurrentDirectories - WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) + 1 - AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) - AND Mirror = 1 - - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) - SELECT 'DISK', @CurrentFilePath, 1 - - SET @CurrentDirectoryPath = NULL - SET @CurrentFilePath = NULL + SELECT 'URL', @CurrentFilePath, 0 END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) - SELECT 1, 0 + SELECT 0, 0 END -- Create directory diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 279b3770..23e3e766 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 9 May, 2018. +Last updated 10 May, 2018. Ola Hallengren https://ola.hallengren.com @@ -1718,9 +1718,8 @@ BEGIN INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) SELECT 0, 0 END - ELSE - IF @URL IS NOT NULL + IF EXISTS (SELECT * FROM @CurrentDirectories WHERE Mirror = 1) BEGIN SET @CurrentFileNumber = 0 @@ -1728,27 +1727,36 @@ BEGIN BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SELECT @CurrentDirectoryPath = DirectoryPath + FROM @CurrentDirectories + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) + AND Mirror = 1 + + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) - SELECT 'URL', @CurrentFilePath, 0 + SELECT 'DISK', @CurrentFilePath, 1 + + SET @CurrentDirectoryPath = NULL + SET @CurrentFilePath = NULL END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) - SELECT 0, 0 + SELECT 1, 0 END - IF EXISTS (SELECT * FROM @CurrentDirectories WHERE Mirror = 1) + IF @URL IS NOT NULL BEGIN SET @CurrentFileNumber = 0 @@ -1756,33 +1764,24 @@ BEGIN BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 - SELECT @CurrentDirectoryPath = DirectoryPath - FROM @CurrentDirectories - WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) + 1 - AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) - AND Mirror = 1 - - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END IF LEN(@CurrentFilePath) > 259 BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension END INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) - SELECT 'DISK', @CurrentFilePath, 1 - - SET @CurrentDirectoryPath = NULL - SET @CurrentFilePath = NULL + SELECT 'URL', @CurrentFilePath, 0 END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) - SELECT 1, 0 + SELECT 0, 0 END -- Create directory From b63eb276086411f1e9bee9686b1b5df3d8d6739e Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 13 May 2018 13:32:40 +0200 Subject: [PATCH 024/188] Add files via upload --- MaintenanceSolution.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 23e3e766..082b7b21 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 10 May, 2018. +Last updated 13 May, 2018. Ola Hallengren https://ola.hallengren.com From 21ea6fc484fe3ab471dcc008f4a30c9f80f84008 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 21 May 2018 19:03:18 +0200 Subject: [PATCH 025/188] Add files via upload --- DatabaseBackup.sql | 2 +- MaintenanceSolution.sql | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index e4a1e053..f32a592e 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -1090,7 +1090,7 @@ BEGIN --// Check @@SERVERNAME //-- ---------------------------------------------------------------------------------------------------- - IF @@SERVERNAME <> SERVERPROPERTY('ServerName') AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 082b7b21..85963fb3 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 13 May, 2018. +Last updated 21 May, 2018. Ola Hallengren https://ola.hallengren.com @@ -1379,7 +1379,7 @@ BEGIN --// Check @@SERVERNAME //-- ---------------------------------------------------------------------------------------------------- - IF @@SERVERNAME <> SERVERPROPERTY('ServerName') AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT From 3743c78e4c01cb202559d8930ea04fdf512807ca Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 23 May 2018 19:47:55 +0200 Subject: [PATCH 026/188] Add files via upload --- DatabaseBackup.sql | 563 +++++++++++++++++++++++++++++++++++---- MaintenanceSolution.sql | 565 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 1031 insertions(+), 97 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index f32a592e..af8d9a96 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -51,6 +51,13 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @DataDomainBoostUser nvarchar(max) = NULL, @DataDomainBoostDevicePath nvarchar(max) = NULL, @DataDomainBoostLockboxPath nvarchar(max) = NULL, +@DirectoryStructure nvarchar(max) = '{ServerName}${InstanceName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}', +@AvailabilityGroupDirectoryStructure nvarchar(max) = '{ClusterName}${AvailabilityGroupName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}', +@FileName nvarchar(max) = '{ServerName}${InstanceName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension}', +@AvailabilityGroupFileName nvarchar(max) = '{ClusterName}${AvailabilityGroupName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension}', +@FileExtensionFull nvarchar(max) = NULL, +@FileExtensionDiff nvarchar(max) = NULL, +@FileExtensionLog nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -79,6 +86,8 @@ BEGIN DECLARE @DirectorySeparator nvarchar(max) DECLARE @AmazonRDS bit + DECLARE @Updated bit + DECLARE @Cluster nvarchar(max) DECLARE @DefaultDirectory nvarchar(4000) @@ -97,6 +106,10 @@ BEGIN DECLARE @CurrentLogLSN numeric(25,0) DECLARE @CurrentLatestBackup datetime DECLARE @CurrentDatabaseNameFS nvarchar(max) + DECLARE @CurrentDirectoryStructure nvarchar(max) + DECLARE @CurrentDatabaseFileName nvarchar(max) + DECLARE @CurrentMaxFilePathLength nvarchar(max) + DECLARE @CurrentFileName nvarchar(max) DECLARE @CurrentDirectoryID int DECLARE @CurrentDirectoryPath nvarchar(max) DECLARE @CurrentFilePath nvarchar(max) @@ -264,6 +277,13 @@ BEGIN SET @Parameters = @Parameters + ', @DataDomainBoostUser = ' + ISNULL('''' + REPLACE(@DataDomainBoostUser,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DataDomainBoostDevicePath = ' + ISNULL('''' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DataDomainBoostLockboxPath = ' + ISNULL('''' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DirectoryStructure = ' + ISNULL('''' + REPLACE(@DirectoryStructure,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @AvailabilityGroupDirectoryStructure = ' + ISNULL('''' + REPLACE(@AvailabilityGroupDirectoryStructure,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FileName = ' + ISNULL('''' + REPLACE(@FileName,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @AvailabilityGroupFileName = ' + ISNULL('''' + REPLACE(@AvailabilityGroupFileName,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FileExtensionFull = ' + ISNULL('''' + REPLACE(@FileExtensionFull,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FileExtensionDiff = ' + ISNULL('''' + REPLACE(@FileExtensionDiff,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -708,6 +728,59 @@ BEGIN END END + ---------------------------------------------------------------------------------------------------- + --// Get directory separator //-- + ---------------------------------------------------------------------------------------------------- + + SELECT @DirectorySeparator = CASE + WHEN @URL IS NOT NULL THEN '/' + WHEN @HostPlatform = 'Windows' THEN '\' + WHEN @HostPlatform = 'Linux' THEN '/' + END + + UPDATE @Directories + SET DirectoryPath = LEFT(DirectoryPath,LEN(DirectoryPath) - 1) + WHERE RIGHT(DirectoryPath,1) = @DirectorySeparator + + IF RIGHT(@URL,1) = @DirectorySeparator + BEGIN + SET @URL = LEFT(@URL,LEN(@URL) - 1) + END + + ---------------------------------------------------------------------------------------------------- + --// Get file extension //-- + ---------------------------------------------------------------------------------------------------- + + IF @FileExtensionFull IS NULL + BEGIN + SELECT @FileExtensionFull = CASE + WHEN @BackupSoftware IS NULL THEN 'bak' + WHEN @BackupSoftware = 'LITESPEED' THEN 'bak' + WHEN @BackupSoftware = 'SQLBACKUP' THEN 'sqb' + WHEN @BackupSoftware = 'SQLSAFE' THEN 'safe' + END + END + + IF @FileExtensionDiff IS NULL + BEGIN + SELECT @FileExtensionDiff = CASE + WHEN @BackupSoftware IS NULL THEN 'bak' + WHEN @BackupSoftware = 'LITESPEED' THEN 'bak' + WHEN @BackupSoftware = 'SQLBACKUP' THEN 'sqb' + WHEN @BackupSoftware = 'SQLSAFE' THEN 'safe' + END + END + + IF @FileExtensionLog IS NULL + BEGIN + SELECT @FileExtensionLog = CASE + WHEN @BackupSoftware IS NULL THEN 'trn' + WHEN @BackupSoftware = 'LITESPEED' THEN 'trn' + WHEN @BackupSoftware = 'SQLBACKUP' THEN 'sqb' + WHEN @BackupSoftware = 'SQLSAFE' THEN 'safe' + END + END + ---------------------------------------------------------------------------------------------------- --// Get default compression //-- ---------------------------------------------------------------------------------------------------- @@ -756,13 +829,48 @@ BEGIN SET @Error = @@ERROR END - IF @CleanupTime < 0 OR (@CleanupTime IS NOT NULL AND @URL IS NOT NULL) OR (@CleanupTime IS NOT NULL AND @HostPlatform = 'Linux') + IF @CleanupTime < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END + IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL + BEGIN + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @CleanupTime IS NOT NULL AND @HostPlatform = 'Linux' + BEGIN + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) + BEGIN + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) + BEGIN + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) + BEGIN + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupMode is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1036,6 +1144,87 @@ BEGIN SET @Error = @@ERROR END + IF @DirectoryStructure = '' + BEGIN + SET @ErrorMessage = 'The value for the parameter @DirectoryStructure is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @AvailabilityGroupDirectoryStructure = '' + BEGIN + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @FileName IS NULL OR @FileName = '' OR @FileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') OR @FileName LIKE '%{DirectorySeperator}%' OR @FileName LIKE '%/%' OR @FileName LIKE '%\%' + BEGIN + SET @ErrorMessage = 'The value for the parameter @FileName is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) OR @AvailabilityGroupFileName = '' OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' OR @AvailabilityGroupFileName LIKE '%/%' OR @AvailabilityGroupFileName LIKE '%\%' + BEGIN + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupFileName is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' + BEGIN + SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' + BEGIN + SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' + BEGIN + SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' + BEGIN + SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @FileExtensionFull LIKE '%.%' + BEGIN + SET @ErrorMessage = 'The value for the parameter @FileExtensionFull is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @FileExtensionDiff LIKE '%.%' + BEGIN + SET @ErrorMessage = 'The value for the parameter @FileExtensionDiff is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @FileExtensionLog LIKE '%.%' + BEGIN + SET @ErrorMessage = 'The value for the parameter @FileExtensionLog is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1367,32 +1556,323 @@ BEGIN SELECT @CurrentLatestBackup END - SELECT @CurrentFileExtension = CASE - WHEN @BackupSoftware IS NULL AND @CurrentBackupType = 'FULL' THEN 'bak' - WHEN @BackupSoftware IS NULL AND @CurrentBackupType = 'DIFF' THEN 'bak' - WHEN @BackupSoftware IS NULL AND @CurrentBackupType = 'LOG' THEN 'trn' - WHEN @BackupSoftware = 'LITESPEED' AND @CurrentBackupType = 'FULL' THEN 'bak' - WHEN @BackupSoftware = 'LITESPEED' AND @CurrentBackupType = 'DIFF' THEN 'bak' - WHEN @BackupSoftware = 'LITESPEED' AND @CurrentBackupType = 'LOG' THEN 'trn' - WHEN @BackupSoftware = 'SQLBACKUP' AND @CurrentBackupType = 'FULL' THEN 'sqb' - WHEN @BackupSoftware = 'SQLBACKUP' AND @CurrentBackupType = 'DIFF' THEN 'sqb' - WHEN @BackupSoftware = 'SQLBACKUP' AND @CurrentBackupType = 'LOG' THEN 'sqb' - WHEN @BackupSoftware = 'SQLSAFE' AND @CurrentBackupType = 'FULL' THEN 'safe' - WHEN @BackupSoftware = 'SQLSAFE' AND @CurrentBackupType = 'DIFF' THEN 'safe' - WHEN @BackupSoftware = 'SQLSAFE' AND @CurrentBackupType = 'LOG' THEN 'safe' + SELECT @CurrentDirectoryStructure = CASE + WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @AvailabilityGroupDirectoryStructure + ELSE @DirectoryStructure END - SELECT @DirectorySeparator = CASE - WHEN @URL IS NOT NULL THEN '/' - WHEN @HostPlatform = 'Windows' THEN '\' - WHEN @HostPlatform = 'Linux' THEN '/' + IF @CurrentDirectoryStructure IS NOT NULL + BEGIN + -- Directory structure - remove tokens that are not needed + IF @ReadWriteFileGroups = 'N' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Partial}','') + IF @CopyOnly = 'N' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{CopyOnly}','') + IF @Cluster IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}','') + IF @CurrentAvailabilityGroup IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}','') + IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}','') + + WHILE (@Updated = 1 OR @Updated IS NULL) + BEGIN + SET @Updated = 0 + + IF CHARINDEX('\',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'\','{DirectorySeparator}') + SET @Updated = 1 + END + + IF CHARINDEX('/',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'/','{DirectorySeparator}') + SET @Updated = 1 + END + + IF CHARINDEX('__',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'__','_') + SET @Updated = 1 + END + + IF CHARINDEX('--',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'--','-') + SET @Updated = 1 + END + + IF CHARINDEX('{DirectorySeparator}{DirectorySeparator}',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}{DirectorySeparator}','{DirectorySeparator}') + SET @Updated = 1 + END + + IF CHARINDEX('{DirectorySeparator}$',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}$','{DirectorySeparator}') + SET @Updated = 1 + END + IF CHARINDEX('${DirectorySeparator}',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'${DirectorySeparator}','{DirectorySeparator}') + SET @Updated = 1 + END + + IF CHARINDEX('{DirectorySeparator}_',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}_','{DirectorySeparator}') + SET @Updated = 1 + END + IF CHARINDEX('_{DirectorySeparator}',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'_{DirectorySeparator}','{DirectorySeparator}') + SET @Updated = 1 + END + + IF CHARINDEX('{DirectorySeparator}-',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}-','{DirectorySeparator}') + SET @Updated = 1 + END + IF CHARINDEX('-{DirectorySeparator}',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'-{DirectorySeparator}','{DirectorySeparator}') + SET @Updated = 1 + END + + IF CHARINDEX('_$',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'_$','_') + SET @Updated = 1 + END + IF CHARINDEX('$_',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'$_','_') + SET @Updated = 1 + END + + IF CHARINDEX('-$',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'-$','-') + SET @Updated = 1 + END + IF CHARINDEX('$-',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'$-','-') + SET @Updated = 1 + END + + IF LEFT(@CurrentDirectoryStructure,1) = '_' + BEGIN + SET @CurrentDirectoryStructure = RIGHT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 1) + SET @Updated = 1 + END + IF RIGHT(@CurrentDirectoryStructure,1) = '_' + BEGIN + SET @CurrentDirectoryStructure = LEFT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 1) + SET @Updated = 1 + END + + IF LEFT(@CurrentDirectoryStructure,1) = '-' + BEGIN + SET @CurrentDirectoryStructure = RIGHT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 1) + SET @Updated = 1 + END + IF RIGHT(@CurrentDirectoryStructure,1) = '-' + BEGIN + SET @CurrentDirectoryStructure = LEFT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 1) + SET @Updated = 1 + END + + IF LEFT(@CurrentDirectoryStructure,1) = '$' + BEGIN + SET @CurrentDirectoryStructure = RIGHT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 1) + SET @Updated = 1 + END + IF RIGHT(@CurrentDirectoryStructure,1) = '$' + BEGIN + SET @CurrentDirectoryStructure = LEFT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 1) + SET @Updated = 1 + END + + IF LEFT(@CurrentDirectoryStructure,20) = '{DirectorySeparator}' + BEGIN + SET @CurrentDirectoryStructure = RIGHT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 20) + SET @Updated = 1 + END + IF RIGHT(@CurrentDirectoryStructure,20) = '{DirectorySeparator}' + BEGIN + SET @CurrentDirectoryStructure = LEFT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 20) + SET @Updated = 1 + END + END + + SET @Updated = NULL + + -- Directory structure - replace tokens with real values + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}',@DirectorySeparator) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}',CAST(SERVERPROPERTY('MachineName') AS nvarchar(max))) + IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}',CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max))) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}',@@SERVICENAME) + IF @Cluster IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}',@Cluster) + IF @CurrentAvailabilityGroup IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}',@CurrentAvailabilityGroup) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DatabaseName}',@CurrentDatabaseNameFS) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupType}',@CurrentBackupType) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Partial}','PARTIAL') + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{CopyOnly}','COPY_ONLY') + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,@CurrentDate) AS nvarchar),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) END INSERT INTO @CurrentDirectories (ID, DirectoryPath, Mirror, DirectoryNumber, CreateCompleted, CleanupCompleted) - SELECT ROW_NUMBER() OVER (ORDER BY ID), DirectoryPath + CASE WHEN RIGHT(DirectoryPath,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + @DirectorySeparator + @CurrentDatabaseNameFS + @DirectorySeparator + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END, Mirror, ROW_NUMBER() OVER (PARTITION BY Mirror ORDER BY ID ASC), 0, 0 + SELECT ROW_NUMBER() OVER (ORDER BY ID), + DirectoryPath + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END, + Mirror, + ROW_NUMBER() OVER (PARTITION BY Mirror ORDER BY ID ASC), + 0, + 0 FROM @Directories ORDER BY ID ASC + SELECT @CurrentDatabaseFileName = CASE + WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @AvailabilityGroupFileName + ELSE @FileName + END + + -- File name - remove tokens that are not needed + IF @ReadWriteFileGroups = 'N' SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Partial}','') + IF @CopyOnly = 'N' SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{CopyOnly}','') + IF @Cluster IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}','') + IF @CurrentAvailabilityGroup IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{AvailabilityGroupName}','') + IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}','') + IF @NumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileNumber}','') + + WHILE (@Updated = 1 OR @Updated IS NULL) + BEGIN + SET @Updated = 0 + + IF CHARINDEX('__',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'__','_') + SET @Updated = 1 + END + + IF CHARINDEX('--',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'--','-') + SET @Updated = 1 + END + + IF CHARINDEX('_$',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'_$','_') + SET @Updated = 1 + END + IF CHARINDEX('$_',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'$_','_') + SET @Updated = 1 + END + + IF CHARINDEX('-$',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'-$','-') + SET @Updated = 1 + END + IF CHARINDEX('$-',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'$-','-') + SET @Updated = 1 + END + + IF CHARINDEX('_.',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'_.','.') + SET @Updated = 1 + END + + IF CHARINDEX('-.',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'-.','.') + SET @Updated = 1 + END + + IF LEFT(@CurrentDatabaseFileName,1) = '_' + BEGIN + SET @CurrentDatabaseFileName = RIGHT(@CurrentDatabaseFileName,LEN(@CurrentDatabaseFileName) - 1) + SET @Updated = 1 + END + IF RIGHT(@CurrentDatabaseFileName,1) = '_' + BEGIN + SET @CurrentDatabaseFileName = LEFT(@CurrentDatabaseFileName,LEN(@CurrentDatabaseFileName) - 1) + SET @Updated = 1 + END + + IF LEFT(@CurrentDatabaseFileName,1) = '-' + BEGIN + SET @CurrentDatabaseFileName = RIGHT(@CurrentDatabaseFileName,LEN(@CurrentDatabaseFileName) - 1) + SET @Updated = 1 + END + IF RIGHT(@CurrentDatabaseFileName,1) = '-' + BEGIN + SET @CurrentDatabaseFileName = LEFT(@CurrentDatabaseFileName,LEN(@CurrentDatabaseFileName) - 1) + SET @Updated = 1 + END + + IF LEFT(@CurrentDatabaseFileName,1) = '$' + BEGIN + SET @CurrentDatabaseFileName = RIGHT(@CurrentDatabaseFileName,LEN(@CurrentDatabaseFileName) - 1) + SET @Updated = 1 + END + IF RIGHT(@CurrentDatabaseFileName,1) = '$' + BEGIN + SET @CurrentDatabaseFileName = LEFT(@CurrentDatabaseFileName,LEN(@CurrentDatabaseFileName) - 1) + SET @Updated = 1 + END + END + + SET @Updated = NULL + + SELECT @CurrentFileExtension = CASE + WHEN @CurrentBackupType = 'FULL' THEN @FileExtensionFull + WHEN @CurrentBackupType = 'DIFF' THEN @FileExtensionDiff + WHEN @CurrentBackupType = 'LOG' THEN @FileExtensionLog + END + + -- File name - replace tokens with real values + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServerName}',CAST(SERVERPROPERTY('MachineName') AS nvarchar(max))) + IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}',CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max))) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}',@@SERVICENAME) + IF @Cluster IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}',@Cluster) + IF @CurrentAvailabilityGroup IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{AvailabilityGroupName}',@CurrentAvailabilityGroup) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{BackupType}',@CurrentBackupType) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Partial}','PARTIAL') + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{CopyOnly}','COPY_ONLY') + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,@CurrentDate) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension); + + SELECT @CurrentMaxFilePathLength = CASE + WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) + WHEN @URL IS NOT NULL THEN LEN(@URL + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END + @DirectorySeparator) + END + + LEN(REPLACE(REPLACE(@CurrentFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '1' WHEN @NumberOfFiles >= 10 THEN '01' ELSE '' END)) + + -- The maximum length of a backup device is 259 characters + IF @CurrentMaxFilePathLength > 259 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - @CurrentMaxFilePathLength - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - @CurrentMaxFilePathLength - 3) END) + '...') + END + ELSE + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',@CurrentDatabaseNameFS) + END + IF EXISTS (SELECT * FROM @CurrentDirectories WHERE Mirror = 0) BEGIN SET @CurrentFileNumber = 0 @@ -1407,22 +1887,15 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 0) AND Mirror = 0 - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - - IF LEN(@CurrentFilePath) > 259 - BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - END + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) - IF LEN(@CurrentFilePath) > 259 - BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - END + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) SELECT 'DISK', @CurrentFilePath, 0 SET @CurrentDirectoryPath = NULL + SET @CurrentFileName = NULL SET @CurrentFilePath = NULL END @@ -1444,22 +1917,15 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) AND Mirror = 1 - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - - IF LEN(@CurrentFilePath) > 259 - BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - END + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) - IF LEN(@CurrentFilePath) > 259 - BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - END + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) SELECT 'DISK', @CurrentFilePath, 1 SET @CurrentDirectoryPath = NULL + SET @CurrentFileName = NULL SET @CurrentFilePath = NULL END @@ -1475,20 +1941,18 @@ BEGIN BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentDirectoryPath = @URL + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END - IF LEN(@CurrentFilePath) > 259 - BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - END + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) - IF LEN(@CurrentFilePath) > 259 - BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - END + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) SELECT 'URL', @CurrentFilePath, 0 + + SET @CurrentDirectoryPath = NULL + SET @CurrentFileName = NULL + SET @CurrentFilePath = NULL END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) @@ -2127,6 +2591,9 @@ BEGIN SET @CurrentLogLSN = NULL SET @CurrentLatestBackup = NULL SET @CurrentDatabaseNameFS = NULL + SET @CurrentDirectoryStructure = NULL + SET @CurrentDatabaseFileName = NULL + SET @CurrentMaxFilePathLength = NULL SET @CurrentDate = NULL SET @CurrentCleanupDate = NULL SET @CurrentIsDatabaseAccessible = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 85963fb3..6d2254c3 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 21 May, 2018. +Last updated 23 May, 2018. Ola Hallengren https://ola.hallengren.com @@ -340,6 +340,13 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @DataDomainBoostUser nvarchar(max) = NULL, @DataDomainBoostDevicePath nvarchar(max) = NULL, @DataDomainBoostLockboxPath nvarchar(max) = NULL, +@DirectoryStructure nvarchar(max) = '{ServerName}${InstanceName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}', +@AvailabilityGroupDirectoryStructure nvarchar(max) = '{ClusterName}${AvailabilityGroupName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}', +@FileName nvarchar(max) = '{ServerName}${InstanceName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension}', +@AvailabilityGroupFileName nvarchar(max) = '{ClusterName}${AvailabilityGroupName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension}', +@FileExtensionFull nvarchar(max) = NULL, +@FileExtensionDiff nvarchar(max) = NULL, +@FileExtensionLog nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -368,6 +375,8 @@ BEGIN DECLARE @DirectorySeparator nvarchar(max) DECLARE @AmazonRDS bit + DECLARE @Updated bit + DECLARE @Cluster nvarchar(max) DECLARE @DefaultDirectory nvarchar(4000) @@ -386,6 +395,10 @@ BEGIN DECLARE @CurrentLogLSN numeric(25,0) DECLARE @CurrentLatestBackup datetime DECLARE @CurrentDatabaseNameFS nvarchar(max) + DECLARE @CurrentDirectoryStructure nvarchar(max) + DECLARE @CurrentDatabaseFileName nvarchar(max) + DECLARE @CurrentMaxFilePathLength nvarchar(max) + DECLARE @CurrentFileName nvarchar(max) DECLARE @CurrentDirectoryID int DECLARE @CurrentDirectoryPath nvarchar(max) DECLARE @CurrentFilePath nvarchar(max) @@ -553,6 +566,13 @@ BEGIN SET @Parameters = @Parameters + ', @DataDomainBoostUser = ' + ISNULL('''' + REPLACE(@DataDomainBoostUser,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DataDomainBoostDevicePath = ' + ISNULL('''' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DataDomainBoostLockboxPath = ' + ISNULL('''' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DirectoryStructure = ' + ISNULL('''' + REPLACE(@DirectoryStructure,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @AvailabilityGroupDirectoryStructure = ' + ISNULL('''' + REPLACE(@AvailabilityGroupDirectoryStructure,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FileName = ' + ISNULL('''' + REPLACE(@FileName,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @AvailabilityGroupFileName = ' + ISNULL('''' + REPLACE(@AvailabilityGroupFileName,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FileExtensionFull = ' + ISNULL('''' + REPLACE(@FileExtensionFull,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FileExtensionDiff = ' + ISNULL('''' + REPLACE(@FileExtensionDiff,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -997,6 +1017,59 @@ BEGIN END END + ---------------------------------------------------------------------------------------------------- + --// Get directory separator //-- + ---------------------------------------------------------------------------------------------------- + + SELECT @DirectorySeparator = CASE + WHEN @URL IS NOT NULL THEN '/' + WHEN @HostPlatform = 'Windows' THEN '\' + WHEN @HostPlatform = 'Linux' THEN '/' + END + + UPDATE @Directories + SET DirectoryPath = LEFT(DirectoryPath,LEN(DirectoryPath) - 1) + WHERE RIGHT(DirectoryPath,1) = @DirectorySeparator + + IF RIGHT(@URL,1) = @DirectorySeparator + BEGIN + SET @URL = LEFT(@URL,LEN(@URL) - 1) + END + + ---------------------------------------------------------------------------------------------------- + --// Get file extension //-- + ---------------------------------------------------------------------------------------------------- + + IF @FileExtensionFull IS NULL + BEGIN + SELECT @FileExtensionFull = CASE + WHEN @BackupSoftware IS NULL THEN 'bak' + WHEN @BackupSoftware = 'LITESPEED' THEN 'bak' + WHEN @BackupSoftware = 'SQLBACKUP' THEN 'sqb' + WHEN @BackupSoftware = 'SQLSAFE' THEN 'safe' + END + END + + IF @FileExtensionDiff IS NULL + BEGIN + SELECT @FileExtensionDiff = CASE + WHEN @BackupSoftware IS NULL THEN 'bak' + WHEN @BackupSoftware = 'LITESPEED' THEN 'bak' + WHEN @BackupSoftware = 'SQLBACKUP' THEN 'sqb' + WHEN @BackupSoftware = 'SQLSAFE' THEN 'safe' + END + END + + IF @FileExtensionLog IS NULL + BEGIN + SELECT @FileExtensionLog = CASE + WHEN @BackupSoftware IS NULL THEN 'trn' + WHEN @BackupSoftware = 'LITESPEED' THEN 'trn' + WHEN @BackupSoftware = 'SQLBACKUP' THEN 'sqb' + WHEN @BackupSoftware = 'SQLSAFE' THEN 'safe' + END + END + ---------------------------------------------------------------------------------------------------- --// Get default compression //-- ---------------------------------------------------------------------------------------------------- @@ -1045,13 +1118,48 @@ BEGIN SET @Error = @@ERROR END - IF @CleanupTime < 0 OR (@CleanupTime IS NOT NULL AND @URL IS NOT NULL) OR (@CleanupTime IS NOT NULL AND @HostPlatform = 'Linux') + IF @CleanupTime < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END + IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL + BEGIN + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @CleanupTime IS NOT NULL AND @HostPlatform = 'Linux' + BEGIN + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) + BEGIN + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) + BEGIN + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) + BEGIN + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupMode is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1325,6 +1433,87 @@ BEGIN SET @Error = @@ERROR END + IF @DirectoryStructure = '' + BEGIN + SET @ErrorMessage = 'The value for the parameter @DirectoryStructure is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @AvailabilityGroupDirectoryStructure = '' + BEGIN + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @FileName IS NULL OR @FileName = '' OR @FileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') OR @FileName LIKE '%{DirectorySeperator}%' OR @FileName LIKE '%/%' OR @FileName LIKE '%\%' + BEGIN + SET @ErrorMessage = 'The value for the parameter @FileName is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) OR @AvailabilityGroupFileName = '' OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' OR @AvailabilityGroupFileName LIKE '%/%' OR @AvailabilityGroupFileName LIKE '%\%' + BEGIN + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupFileName is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' + BEGIN + SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' + BEGIN + SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' + BEGIN + SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' + BEGIN + SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @FileExtensionFull LIKE '%.%' + BEGIN + SET @ErrorMessage = 'The value for the parameter @FileExtensionFull is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @FileExtensionDiff LIKE '%.%' + BEGIN + SET @ErrorMessage = 'The value for the parameter @FileExtensionDiff is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @FileExtensionLog LIKE '%.%' + BEGIN + SET @ErrorMessage = 'The value for the parameter @FileExtensionLog is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1656,32 +1845,323 @@ BEGIN SELECT @CurrentLatestBackup END - SELECT @CurrentFileExtension = CASE - WHEN @BackupSoftware IS NULL AND @CurrentBackupType = 'FULL' THEN 'bak' - WHEN @BackupSoftware IS NULL AND @CurrentBackupType = 'DIFF' THEN 'bak' - WHEN @BackupSoftware IS NULL AND @CurrentBackupType = 'LOG' THEN 'trn' - WHEN @BackupSoftware = 'LITESPEED' AND @CurrentBackupType = 'FULL' THEN 'bak' - WHEN @BackupSoftware = 'LITESPEED' AND @CurrentBackupType = 'DIFF' THEN 'bak' - WHEN @BackupSoftware = 'LITESPEED' AND @CurrentBackupType = 'LOG' THEN 'trn' - WHEN @BackupSoftware = 'SQLBACKUP' AND @CurrentBackupType = 'FULL' THEN 'sqb' - WHEN @BackupSoftware = 'SQLBACKUP' AND @CurrentBackupType = 'DIFF' THEN 'sqb' - WHEN @BackupSoftware = 'SQLBACKUP' AND @CurrentBackupType = 'LOG' THEN 'sqb' - WHEN @BackupSoftware = 'SQLSAFE' AND @CurrentBackupType = 'FULL' THEN 'safe' - WHEN @BackupSoftware = 'SQLSAFE' AND @CurrentBackupType = 'DIFF' THEN 'safe' - WHEN @BackupSoftware = 'SQLSAFE' AND @CurrentBackupType = 'LOG' THEN 'safe' + SELECT @CurrentDirectoryStructure = CASE + WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @AvailabilityGroupDirectoryStructure + ELSE @DirectoryStructure END - SELECT @DirectorySeparator = CASE - WHEN @URL IS NOT NULL THEN '/' - WHEN @HostPlatform = 'Windows' THEN '\' - WHEN @HostPlatform = 'Linux' THEN '/' + IF @CurrentDirectoryStructure IS NOT NULL + BEGIN + -- Directory structure - remove tokens that are not needed + IF @ReadWriteFileGroups = 'N' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Partial}','') + IF @CopyOnly = 'N' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{CopyOnly}','') + IF @Cluster IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}','') + IF @CurrentAvailabilityGroup IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}','') + IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}','') + + WHILE (@Updated = 1 OR @Updated IS NULL) + BEGIN + SET @Updated = 0 + + IF CHARINDEX('\',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'\','{DirectorySeparator}') + SET @Updated = 1 + END + + IF CHARINDEX('/',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'/','{DirectorySeparator}') + SET @Updated = 1 + END + + IF CHARINDEX('__',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'__','_') + SET @Updated = 1 + END + + IF CHARINDEX('--',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'--','-') + SET @Updated = 1 + END + + IF CHARINDEX('{DirectorySeparator}{DirectorySeparator}',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}{DirectorySeparator}','{DirectorySeparator}') + SET @Updated = 1 + END + + IF CHARINDEX('{DirectorySeparator}$',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}$','{DirectorySeparator}') + SET @Updated = 1 + END + IF CHARINDEX('${DirectorySeparator}',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'${DirectorySeparator}','{DirectorySeparator}') + SET @Updated = 1 + END + + IF CHARINDEX('{DirectorySeparator}_',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}_','{DirectorySeparator}') + SET @Updated = 1 + END + IF CHARINDEX('_{DirectorySeparator}',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'_{DirectorySeparator}','{DirectorySeparator}') + SET @Updated = 1 + END + + IF CHARINDEX('{DirectorySeparator}-',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}-','{DirectorySeparator}') + SET @Updated = 1 + END + IF CHARINDEX('-{DirectorySeparator}',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'-{DirectorySeparator}','{DirectorySeparator}') + SET @Updated = 1 + END + + IF CHARINDEX('_$',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'_$','_') + SET @Updated = 1 + END + IF CHARINDEX('$_',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'$_','_') + SET @Updated = 1 + END + + IF CHARINDEX('-$',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'-$','-') + SET @Updated = 1 + END + IF CHARINDEX('$-',@CurrentDirectoryStructure) > 0 + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'$-','-') + SET @Updated = 1 + END + + IF LEFT(@CurrentDirectoryStructure,1) = '_' + BEGIN + SET @CurrentDirectoryStructure = RIGHT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 1) + SET @Updated = 1 + END + IF RIGHT(@CurrentDirectoryStructure,1) = '_' + BEGIN + SET @CurrentDirectoryStructure = LEFT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 1) + SET @Updated = 1 + END + + IF LEFT(@CurrentDirectoryStructure,1) = '-' + BEGIN + SET @CurrentDirectoryStructure = RIGHT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 1) + SET @Updated = 1 + END + IF RIGHT(@CurrentDirectoryStructure,1) = '-' + BEGIN + SET @CurrentDirectoryStructure = LEFT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 1) + SET @Updated = 1 + END + + IF LEFT(@CurrentDirectoryStructure,1) = '$' + BEGIN + SET @CurrentDirectoryStructure = RIGHT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 1) + SET @Updated = 1 + END + IF RIGHT(@CurrentDirectoryStructure,1) = '$' + BEGIN + SET @CurrentDirectoryStructure = LEFT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 1) + SET @Updated = 1 + END + + IF LEFT(@CurrentDirectoryStructure,20) = '{DirectorySeparator}' + BEGIN + SET @CurrentDirectoryStructure = RIGHT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 20) + SET @Updated = 1 + END + IF RIGHT(@CurrentDirectoryStructure,20) = '{DirectorySeparator}' + BEGIN + SET @CurrentDirectoryStructure = LEFT(@CurrentDirectoryStructure,LEN(@CurrentDirectoryStructure) - 20) + SET @Updated = 1 + END + END + + SET @Updated = NULL + + -- Directory structure - replace tokens with real values + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}',@DirectorySeparator) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}',CAST(SERVERPROPERTY('MachineName') AS nvarchar(max))) + IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}',CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max))) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}',@@SERVICENAME) + IF @Cluster IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}',@Cluster) + IF @CurrentAvailabilityGroup IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}',@CurrentAvailabilityGroup) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DatabaseName}',@CurrentDatabaseNameFS) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupType}',@CurrentBackupType) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Partial}','PARTIAL') + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{CopyOnly}','COPY_ONLY') + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,@CurrentDate) AS nvarchar),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) END INSERT INTO @CurrentDirectories (ID, DirectoryPath, Mirror, DirectoryNumber, CreateCompleted, CleanupCompleted) - SELECT ROW_NUMBER() OVER (ORDER BY ID), DirectoryPath + CASE WHEN RIGHT(DirectoryPath,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + @DirectorySeparator + @CurrentDatabaseNameFS + @DirectorySeparator + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END, Mirror, ROW_NUMBER() OVER (PARTITION BY Mirror ORDER BY ID ASC), 0, 0 + SELECT ROW_NUMBER() OVER (ORDER BY ID), + DirectoryPath + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END, + Mirror, + ROW_NUMBER() OVER (PARTITION BY Mirror ORDER BY ID ASC), + 0, + 0 FROM @Directories ORDER BY ID ASC + SELECT @CurrentDatabaseFileName = CASE + WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @AvailabilityGroupFileName + ELSE @FileName + END + + -- File name - remove tokens that are not needed + IF @ReadWriteFileGroups = 'N' SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Partial}','') + IF @CopyOnly = 'N' SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{CopyOnly}','') + IF @Cluster IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}','') + IF @CurrentAvailabilityGroup IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{AvailabilityGroupName}','') + IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}','') + IF @NumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileNumber}','') + + WHILE (@Updated = 1 OR @Updated IS NULL) + BEGIN + SET @Updated = 0 + + IF CHARINDEX('__',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'__','_') + SET @Updated = 1 + END + + IF CHARINDEX('--',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'--','-') + SET @Updated = 1 + END + + IF CHARINDEX('_$',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'_$','_') + SET @Updated = 1 + END + IF CHARINDEX('$_',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'$_','_') + SET @Updated = 1 + END + + IF CHARINDEX('-$',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'-$','-') + SET @Updated = 1 + END + IF CHARINDEX('$-',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'$-','-') + SET @Updated = 1 + END + + IF CHARINDEX('_.',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'_.','.') + SET @Updated = 1 + END + + IF CHARINDEX('-.',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'-.','.') + SET @Updated = 1 + END + + IF LEFT(@CurrentDatabaseFileName,1) = '_' + BEGIN + SET @CurrentDatabaseFileName = RIGHT(@CurrentDatabaseFileName,LEN(@CurrentDatabaseFileName) - 1) + SET @Updated = 1 + END + IF RIGHT(@CurrentDatabaseFileName,1) = '_' + BEGIN + SET @CurrentDatabaseFileName = LEFT(@CurrentDatabaseFileName,LEN(@CurrentDatabaseFileName) - 1) + SET @Updated = 1 + END + + IF LEFT(@CurrentDatabaseFileName,1) = '-' + BEGIN + SET @CurrentDatabaseFileName = RIGHT(@CurrentDatabaseFileName,LEN(@CurrentDatabaseFileName) - 1) + SET @Updated = 1 + END + IF RIGHT(@CurrentDatabaseFileName,1) = '-' + BEGIN + SET @CurrentDatabaseFileName = LEFT(@CurrentDatabaseFileName,LEN(@CurrentDatabaseFileName) - 1) + SET @Updated = 1 + END + + IF LEFT(@CurrentDatabaseFileName,1) = '$' + BEGIN + SET @CurrentDatabaseFileName = RIGHT(@CurrentDatabaseFileName,LEN(@CurrentDatabaseFileName) - 1) + SET @Updated = 1 + END + IF RIGHT(@CurrentDatabaseFileName,1) = '$' + BEGIN + SET @CurrentDatabaseFileName = LEFT(@CurrentDatabaseFileName,LEN(@CurrentDatabaseFileName) - 1) + SET @Updated = 1 + END + END + + SET @Updated = NULL + + SELECT @CurrentFileExtension = CASE + WHEN @CurrentBackupType = 'FULL' THEN @FileExtensionFull + WHEN @CurrentBackupType = 'DIFF' THEN @FileExtensionDiff + WHEN @CurrentBackupType = 'LOG' THEN @FileExtensionLog + END + + -- File name - replace tokens with real values + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServerName}',CAST(SERVERPROPERTY('MachineName') AS nvarchar(max))) + IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}',CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max))) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}',@@SERVICENAME) + IF @Cluster IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}',@Cluster) + IF @CurrentAvailabilityGroup IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{AvailabilityGroupName}',@CurrentAvailabilityGroup) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{BackupType}',@CurrentBackupType) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Partial}','PARTIAL') + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{CopyOnly}','COPY_ONLY') + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,@CurrentDate) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension); + + SELECT @CurrentMaxFilePathLength = CASE + WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) + WHEN @URL IS NOT NULL THEN LEN(@URL + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END + @DirectorySeparator) + END + + LEN(REPLACE(REPLACE(@CurrentFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '1' WHEN @NumberOfFiles >= 10 THEN '01' ELSE '' END)) + + -- The maximum length of a backup device is 259 characters + IF @CurrentMaxFilePathLength > 259 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - @CurrentMaxFilePathLength - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - @CurrentMaxFilePathLength - 3) END) + '...') + END + ELSE + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',@CurrentDatabaseNameFS) + END + IF EXISTS (SELECT * FROM @CurrentDirectories WHERE Mirror = 0) BEGIN SET @CurrentFileNumber = 0 @@ -1696,22 +2176,15 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 0) AND Mirror = 0 - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - - IF LEN(@CurrentFilePath) > 259 - BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - END + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) - IF LEN(@CurrentFilePath) > 259 - BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - END + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) SELECT 'DISK', @CurrentFilePath, 0 SET @CurrentDirectoryPath = NULL + SET @CurrentFileName = NULL SET @CurrentFilePath = NULL END @@ -1733,22 +2206,15 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) AND Mirror = 1 - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - - IF LEN(@CurrentFilePath) > 259 - BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - END + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) - IF LEN(@CurrentFilePath) > 259 - BEGIN - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - END + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) SELECT 'DISK', @CurrentFilePath, 1 SET @CurrentDirectoryPath = NULL + SET @CurrentFileName = NULL SET @CurrentFilePath = NULL END @@ -1764,20 +2230,18 @@ BEGIN BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster + '$' + @CurrentAvailabilityGroup ELSE REPLACE(CAST(SERVERPROPERTY('servername') AS nvarchar(max)),'\','$') END + '_' + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension + SET @CurrentDirectoryPath = @URL + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END - IF LEN(@CurrentFilePath) > 259 - BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + @CurrentDatabaseNameFS + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - END + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) - IF LEN(@CurrentFilePath) > 259 - BEGIN - SET @CurrentFilePath = @URL + CASE WHEN RIGHT(@URL,1) = @DirectorySeparator THEN '' ELSE @DirectorySeparator END + LEFT(@CurrentDatabaseNameFS,CASE WHEN (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) < 20 THEN 20 ELSE (LEN(@CurrentDatabaseNameFS) + 259 - LEN(@CurrentFilePath) - 3) END) + '...' + '_' + UPPER(@CurrentBackupType) + CASE WHEN @ReadWriteFileGroups = 'Y' THEN '_PARTIAL' ELSE '' END + CASE WHEN @CopyOnly = 'Y' THEN '_COPY_ONLY' ELSE '' END + '_' + REPLACE(REPLACE(REPLACE((CONVERT(nvarchar,@CurrentDate,120)),'-',''),' ','_'),':','') + CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '_' + CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN '_' + RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END + '.' + @CurrentFileExtension - END + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) SELECT 'URL', @CurrentFilePath, 0 + + SET @CurrentDirectoryPath = NULL + SET @CurrentFileName = NULL + SET @CurrentFilePath = NULL END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) @@ -2416,6 +2880,9 @@ BEGIN SET @CurrentLogLSN = NULL SET @CurrentLatestBackup = NULL SET @CurrentDatabaseNameFS = NULL + SET @CurrentDirectoryStructure = NULL + SET @CurrentDatabaseFileName = NULL + SET @CurrentMaxFilePathLength = NULL SET @CurrentDate = NULL SET @CurrentCleanupDate = NULL SET @CurrentIsDatabaseAccessible = NULL From b7f333b13809ff7991fb36ce53875066033f4008 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 28 May 2018 20:07:26 +0200 Subject: [PATCH 027/188] Add files via upload --- DatabaseBackup.sql | 81 ++++++-- DatabaseIntegrityCheck.sql | 167 ++++++++++++---- IndexOptimize.sql | 139 ++++++++++--- MaintenanceSolution.sql | 389 +++++++++++++++++++++++++++++-------- 4 files changed, 615 insertions(+), 161 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index af8d9a96..e5a689bd 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -165,22 +165,28 @@ BEGIN DatabaseNameFS nvarchar(max), DatabaseType nvarchar(max), AvailabilityGroup bit, + StartPosition int, + [Order] int, Selected bit, Completed bit, - PRIMARY KEY(Selected, Completed, ID)) + PRIMARY KEY(Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, AvailabilityGroupName nvarchar(max), + StartPosition int, Selected bit) - DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), AvailabilityGroupName nvarchar(max)) + DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), + AvailabilityGroupName nvarchar(max)) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), DatabaseType nvarchar(max), AvailabilityGroup nvarchar(max), + StartPosition int, Selected bit) DECLARE @SelectedAvailabilityGroups TABLE (AvailabilityGroupName nvarchar(max), + StartPosition int, Selected bit) DECLARE @CurrentBackupSet TABLE (ID int IDENTITY PRIMARY KEY, @@ -375,32 +381,36 @@ BEGIN FROM Databases1 WHERE EndPosition < LEN(@Databases) + 1 ), - Databases2 (DatabaseItem, Selected) AS + Databases2 (DatabaseItem, StartPosition, Selected) AS ( SELECT CASE WHEN DatabaseItem LIKE '-%' THEN RIGHT(DatabaseItem,LEN(DatabaseItem) - 1) ELSE DatabaseItem END AS DatabaseItem, + StartPosition, CASE WHEN DatabaseItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM Databases1 ), - Databases3 (DatabaseItem, DatabaseType, AvailabilityGroup, Selected) AS + Databases3 (DatabaseItem, DatabaseType, AvailabilityGroup, StartPosition, Selected) AS ( SELECT CASE WHEN DatabaseItem IN('ALL_DATABASES','SYSTEM_DATABASES','USER_DATABASES','AVAILABILITY_GROUP_DATABASES') THEN '%' ELSE DatabaseItem END AS DatabaseItem, CASE WHEN DatabaseItem = 'SYSTEM_DATABASES' THEN 'S' WHEN DatabaseItem = 'USER_DATABASES' THEN 'U' ELSE NULL END AS DatabaseType, CASE WHEN DatabaseItem = 'AVAILABILITY_GROUP_DATABASES' THEN 1 ELSE NULL END AvailabilityGroup, + StartPosition, Selected FROM Databases2 ), - Databases4 (DatabaseName, DatabaseType, AvailabilityGroup, Selected) AS + Databases4 (DatabaseName, DatabaseType, AvailabilityGroup, StartPosition, Selected) AS ( SELECT CASE WHEN LEFT(DatabaseItem,1) = '[' AND RIGHT(DatabaseItem,1) = ']' THEN PARSENAME(DatabaseItem,1) ELSE DatabaseItem END AS DatabaseItem, DatabaseType, AvailabilityGroup, + StartPosition, Selected FROM Databases3 ) - INSERT INTO @SelectedDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected) + INSERT INTO @SelectedDatabases (DatabaseName, DatabaseType, AvailabilityGroup, StartPosition, Selected) SELECT DatabaseName, DatabaseType, AvailabilityGroup, + StartPosition, Selected FROM Databases4 OPTION (MAXRECURSION 0) @@ -418,11 +428,12 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, + 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.databases @@ -452,6 +463,19 @@ BEGIN AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) WHERE SelectedDatabases.Selected = 0 + UPDATE tmpDatabases + SET tmpDatabases.StartPosition = SelectedDatabases2.StartPosition + FROM @tmpDatabases tmpDatabases + INNER JOIN (SELECT tmpDatabases.DatabaseName, MIN(SelectedDatabases.StartPosition) AS StartPosition + FROM @tmpDatabases tmpDatabases + INNER JOIN @SelectedDatabases SelectedDatabases + ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL) + AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) + WHERE SelectedDatabases.Selected = 1 + GROUP BY tmpDatabases.DatabaseName) SelectedDatabases2 + ON tmpDatabases.DatabaseName = SelectedDatabases2.DatabaseName + IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -487,26 +511,29 @@ BEGIN FROM AvailabilityGroups1 WHERE EndPosition < LEN(@AvailabilityGroups) + 1 ), - AvailabilityGroups2 (AvailabilityGroupItem, Selected) AS + AvailabilityGroups2 (AvailabilityGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN AvailabilityGroupItem LIKE '-%' THEN RIGHT(AvailabilityGroupItem,LEN(AvailabilityGroupItem) - 1) ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, CASE WHEN AvailabilityGroupItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM AvailabilityGroups1 ), - AvailabilityGroups3 (AvailabilityGroupItem, Selected) AS + AvailabilityGroups3 (AvailabilityGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN AvailabilityGroupItem = 'ALL_AVAILABILITY_GROUPS' THEN '%' ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, Selected FROM AvailabilityGroups2 ), - AvailabilityGroups4 (AvailabilityGroupName, Selected) AS + AvailabilityGroups4 (AvailabilityGroupName, StartPosition, Selected) AS ( SELECT CASE WHEN LEFT(AvailabilityGroupItem,1) = '[' AND RIGHT(AvailabilityGroupItem,1) = ']' THEN PARSENAME(AvailabilityGroupItem,1) ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, Selected FROM AvailabilityGroups3 ) - INSERT INTO @SelectedAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT AvailabilityGroupName, Selected + INSERT INTO @SelectedAvailabilityGroups (AvailabilityGroupName, StartPosition, Selected) + SELECT AvailabilityGroupName, StartPosition, Selected FROM AvailabilityGroups4 OPTION (MAXRECURSION 0) @@ -524,8 +551,20 @@ BEGIN ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 + UPDATE tmpAvailabilityGroups + SET tmpAvailabilityGroups.StartPosition = SelectedAvailabilityGroups2.StartPosition + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN (SELECT tmpAvailabilityGroups.AvailabilityGroupName, MIN(SelectedAvailabilityGroups.StartPosition) AS StartPosition + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + WHERE SelectedAvailabilityGroups.Selected = 1 + GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2 + ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName + UPDATE tmpDatabases - SET Selected = 1 + SET tmpDatabases.StartPosition = tmpAvailabilityGroups.StartPosition, + tmpDatabases.Selected = 1 FROM @tmpDatabases tmpDatabases INNER JOIN @tmpDatabasesAvailabilityGroups tmpDatabasesAvailabilityGroups ON tmpDatabases.DatabaseName = tmpDatabasesAvailabilityGroups.DatabaseName INNER JOIN @tmpAvailabilityGroups tmpAvailabilityGroups ON tmpDatabasesAvailabilityGroups.AvailabilityGroupName = tmpAvailabilityGroups.AvailabilityGroupName @@ -552,7 +591,19 @@ BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR - END + END; + + ---------------------------------------------------------------------------------------------------- + --// Update database order //-- + ---------------------------------------------------------------------------------------------------- + + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber ---------------------------------------------------------------------------------------------------- --// Check database names //-- @@ -1309,7 +1360,7 @@ BEGIN FROM @tmpDatabases WHERE Selected = 1 AND Completed = 0 - ORDER BY ID ASC + ORDER BY [Order] ASC IF @@ROWCOUNT = 0 BEGIN diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index a580ca06..c85e207b 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -100,22 +100,28 @@ BEGIN DatabaseType nvarchar(max), AvailabilityGroup bit, [Snapshot] bit, + StartPosition int, + [Order] int, Selected bit, Completed bit, - PRIMARY KEY(Selected, Completed, ID)) + PRIMARY KEY(Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, AvailabilityGroupName nvarchar(max), + StartPosition int, Selected bit) - DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), AvailabilityGroupName nvarchar(max)) + DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), + AvailabilityGroupName nvarchar(max)) DECLARE @tmpFileGroups TABLE (ID int IDENTITY, FileGroupID int, FileGroupName nvarchar(max), + StartPosition int, + [Order] int, Selected bit, Completed bit, - PRIMARY KEY(Selected, Completed, ID)) + PRIMARY KEY(Selected, Completed, [Order], ID)) DECLARE @tmpObjects TABLE (ID int IDENTITY, SchemaID int, @@ -123,25 +129,31 @@ BEGIN ObjectID int, ObjectName nvarchar(max), ObjectType nvarchar(max), + StartPosition int, + [Order] int, Selected bit, Completed bit, - PRIMARY KEY(Selected, Completed, ID)) + PRIMARY KEY(Selected, Completed, [Order], ID)) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), DatabaseType nvarchar(max), AvailabilityGroup nvarchar(max), + StartPosition int, Selected bit) DECLARE @SelectedAvailabilityGroups TABLE (AvailabilityGroupName nvarchar(max), + StartPosition int, Selected bit) DECLARE @SelectedFileGroups TABLE (DatabaseName nvarchar(max), FileGroupName nvarchar(max), + StartPosition int, Selected bit) DECLARE @SelectedObjects TABLE (DatabaseName nvarchar(max), SchemaName nvarchar(max), ObjectName nvarchar(max), + StartPosition int, Selected bit) DECLARE @SelectedCheckCommands TABLE (CheckCommand nvarchar(max)) @@ -271,32 +283,36 @@ BEGIN FROM Databases1 WHERE EndPosition < LEN(@Databases) + 1 ), - Databases2 (DatabaseItem, Selected) AS + Databases2 (DatabaseItem, StartPosition, Selected) AS ( SELECT CASE WHEN DatabaseItem LIKE '-%' THEN RIGHT(DatabaseItem,LEN(DatabaseItem) - 1) ELSE DatabaseItem END AS DatabaseItem, + StartPosition, CASE WHEN DatabaseItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM Databases1 ), - Databases3 (DatabaseItem, DatabaseType, AvailabilityGroup, Selected) AS + Databases3 (DatabaseItem, DatabaseType, AvailabilityGroup, StartPosition, Selected) AS ( SELECT CASE WHEN DatabaseItem IN('ALL_DATABASES','SYSTEM_DATABASES','USER_DATABASES','AVAILABILITY_GROUP_DATABASES') THEN '%' ELSE DatabaseItem END AS DatabaseItem, CASE WHEN DatabaseItem = 'SYSTEM_DATABASES' THEN 'S' WHEN DatabaseItem = 'USER_DATABASES' THEN 'U' ELSE NULL END AS DatabaseType, CASE WHEN DatabaseItem = 'AVAILABILITY_GROUP_DATABASES' THEN 1 ELSE NULL END AvailabilityGroup, + StartPosition, Selected FROM Databases2 ), - Databases4 (DatabaseName, DatabaseType, AvailabilityGroup, Selected) AS + Databases4 (DatabaseName, DatabaseType, AvailabilityGroup, StartPosition, Selected) AS ( SELECT CASE WHEN LEFT(DatabaseItem,1) = '[' AND RIGHT(DatabaseItem,1) = ']' THEN PARSENAME(DatabaseItem,1) ELSE DatabaseItem END AS DatabaseItem, DatabaseType, AvailabilityGroup, + StartPosition, Selected FROM Databases3 ) - INSERT INTO @SelectedDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected) + INSERT INTO @SelectedDatabases (DatabaseName, DatabaseType, AvailabilityGroup, StartPosition, Selected) SELECT DatabaseName, DatabaseType, AvailabilityGroup, + StartPosition, Selected FROM Databases4 OPTION (MAXRECURSION 0) @@ -314,11 +330,12 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], [Order], Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], + 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.databases @@ -348,6 +365,19 @@ BEGIN AND NOT ((tmpDatabases.DatabaseName = 'tempdb' OR tmpDatabases.[Snapshot] = 1) AND tmpDatabases.DatabaseName <> SelectedDatabases.DatabaseName) WHERE SelectedDatabases.Selected = 0 + UPDATE tmpDatabases + SET tmpDatabases.StartPosition = SelectedDatabases2.StartPosition + FROM @tmpDatabases tmpDatabases + INNER JOIN (SELECT tmpDatabases.DatabaseName, MIN(SelectedDatabases.StartPosition) AS StartPosition + FROM @tmpDatabases tmpDatabases + INNER JOIN @SelectedDatabases SelectedDatabases + ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL) + AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) + WHERE SelectedDatabases.Selected = 1 + GROUP BY tmpDatabases.DatabaseName) SelectedDatabases2 + ON tmpDatabases.DatabaseName = SelectedDatabases2.DatabaseName + IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -383,26 +413,29 @@ BEGIN FROM AvailabilityGroups1 WHERE EndPosition < LEN(@AvailabilityGroups) + 1 ), - AvailabilityGroups2 (AvailabilityGroupItem, Selected) AS + AvailabilityGroups2 (AvailabilityGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN AvailabilityGroupItem LIKE '-%' THEN RIGHT(AvailabilityGroupItem,LEN(AvailabilityGroupItem) - 1) ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, CASE WHEN AvailabilityGroupItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM AvailabilityGroups1 ), - AvailabilityGroups3 (AvailabilityGroupItem, Selected) AS + AvailabilityGroups3 (AvailabilityGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN AvailabilityGroupItem = 'ALL_AVAILABILITY_GROUPS' THEN '%' ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, Selected FROM AvailabilityGroups2 ), - AvailabilityGroups4 (AvailabilityGroupName, Selected) AS + AvailabilityGroups4 (AvailabilityGroupName, StartPosition, Selected) AS ( SELECT CASE WHEN LEFT(AvailabilityGroupItem,1) = '[' AND RIGHT(AvailabilityGroupItem,1) = ']' THEN PARSENAME(AvailabilityGroupItem,1) ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, Selected FROM AvailabilityGroups3 ) - INSERT INTO @SelectedAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT AvailabilityGroupName, Selected + INSERT INTO @SelectedAvailabilityGroups (AvailabilityGroupName, StartPosition, Selected) + SELECT AvailabilityGroupName, StartPosition, Selected FROM AvailabilityGroups4 OPTION (MAXRECURSION 0) @@ -420,8 +453,20 @@ BEGIN ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 + UPDATE tmpAvailabilityGroups + SET tmpAvailabilityGroups.StartPosition = SelectedAvailabilityGroups2.StartPosition + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN (SELECT tmpAvailabilityGroups.AvailabilityGroupName, MIN(SelectedAvailabilityGroups.StartPosition) AS StartPosition + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + WHERE SelectedAvailabilityGroups.Selected = 1 + GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2 + ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName + UPDATE tmpDatabases - SET Selected = 1 + SET tmpDatabases.StartPosition = tmpAvailabilityGroups.StartPosition, + tmpDatabases.Selected = 1 FROM @tmpDatabases tmpDatabases INNER JOIN @tmpDatabasesAvailabilityGroups tmpDatabasesAvailabilityGroups ON tmpDatabases.DatabaseName = tmpDatabasesAvailabilityGroups.DatabaseName INNER JOIN @tmpAvailabilityGroups tmpAvailabilityGroups ON tmpDatabasesAvailabilityGroups.AvailabilityGroupName = tmpAvailabilityGroups.AvailabilityGroupName @@ -448,7 +493,19 @@ BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR - END + END; + + ---------------------------------------------------------------------------------------------------- + --// Update database order //-- + ---------------------------------------------------------------------------------------------------- + + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber ---------------------------------------------------------------------------------------------------- --// Select filegroups //-- @@ -475,27 +532,30 @@ BEGIN FROM FileGroups1 WHERE EndPosition < LEN(@FileGroups) + 1 ), - FileGroups2 (FileGroupItem, Selected) AS + FileGroups2 (FileGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN FileGroupItem LIKE '-%' THEN RIGHT(FileGroupItem,LEN(FileGroupItem) - 1) ELSE FileGroupItem END AS FileGroupItem, + StartPosition, CASE WHEN FileGroupItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM FileGroups1 ), - FileGroups3 (FileGroupItem, Selected) AS + FileGroups3 (FileGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN FileGroupItem = 'ALL_FILEGROUPS' THEN '%.%' ELSE FileGroupItem END AS FileGroupItem, + StartPosition, Selected FROM FileGroups2 ), - FileGroups4 (DatabaseName, FileGroupName, Selected) AS + FileGroups4 (DatabaseName, FileGroupName, StartPosition, Selected) AS ( SELECT CASE WHEN PARSENAME(FileGroupItem,4) IS NULL AND PARSENAME(FileGroupItem,3) IS NULL THEN PARSENAME(FileGroupItem,2) ELSE NULL END AS DatabaseName, CASE WHEN PARSENAME(FileGroupItem,4) IS NULL AND PARSENAME(FileGroupItem,3) IS NULL THEN PARSENAME(FileGroupItem,1) ELSE NULL END AS FileGroupName, + StartPosition, Selected FROM FileGroups3 ) - INSERT INTO @SelectedFileGroups (DatabaseName, FileGroupName, Selected) - SELECT DatabaseName, FileGroupName, Selected + INSERT INTO @SelectedFileGroups (DatabaseName, FileGroupName, StartPosition, Selected) + SELECT DatabaseName, FileGroupName, StartPosition, Selected FROM FileGroups4 OPTION (MAXRECURSION 0) @@ -524,28 +584,31 @@ BEGIN FROM Objects1 WHERE EndPosition < LEN(@Objects) + 1 ), - Objects2 (ObjectItem, Selected) AS + Objects2 (ObjectItem, StartPosition, Selected) AS ( SELECT CASE WHEN ObjectItem LIKE '-%' THEN RIGHT(ObjectItem,LEN(ObjectItem) - 1) ELSE ObjectItem END AS ObjectItem, + StartPosition, CASE WHEN ObjectItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM Objects1 ), - Objects3 (ObjectItem, Selected) AS + Objects3 (ObjectItem, StartPosition, Selected) AS ( SELECT CASE WHEN ObjectItem = 'ALL_OBJECTS' THEN '%.%.%' ELSE ObjectItem END AS ObjectItem, + StartPosition, Selected FROM Objects2 ), - Objects4 (DatabaseName, SchemaName, ObjectName, Selected) AS + Objects4 (DatabaseName, SchemaName, ObjectName, StartPosition, Selected) AS ( SELECT CASE WHEN PARSENAME(ObjectItem,4) IS NULL THEN PARSENAME(ObjectItem,3) ELSE NULL END AS DatabaseName, CASE WHEN PARSENAME(ObjectItem,4) IS NULL THEN PARSENAME(ObjectItem,2) ELSE NULL END AS SchemaName, CASE WHEN PARSENAME(ObjectItem,4) IS NULL THEN PARSENAME(ObjectItem,1) ELSE NULL END AS ObjectName, + StartPosition, Selected FROM Objects3 ) - INSERT INTO @SelectedObjects (DatabaseName, SchemaName, ObjectName, Selected) - SELECT DatabaseName, SchemaName, ObjectName, Selected + INSERT INTO @SelectedObjects (DatabaseName, SchemaName, ObjectName, StartPosition, Selected) + SELECT DatabaseName, SchemaName, ObjectName, StartPosition, Selected FROM Objects4 OPTION (MAXRECURSION 0); @@ -774,7 +837,7 @@ BEGIN FROM @tmpDatabases WHERE Selected = 1 AND Completed = 0 - ORDER BY ID ASC + ORDER BY [Order] ASC IF @@ROWCOUNT = 0 BEGIN @@ -894,9 +957,9 @@ BEGIN -- Check filegroups IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') BEGIN - SET @CurrentCommand02 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' + SET @CurrentCommand02 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' - INSERT INTO @tmpFileGroups (FileGroupID, FileGroupName, Selected, Completed) + INSERT INTO @tmpFileGroups (FileGroupID, FileGroupName, [Order], Selected, Completed) EXECUTE sp_executesql @statement = @CurrentCommand02 SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -922,6 +985,25 @@ BEGIN INNER JOIN @SelectedFileGroups SelectedFileGroups ON @CurrentDatabaseName LIKE REPLACE(SelectedFileGroups.DatabaseName,'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(SelectedFileGroups.FileGroupName,'_','[_]') WHERE SelectedFileGroups.Selected = 0 + + UPDATE tmpFileGroups + SET tmpFileGroups.StartPosition = SelectedFileGroups2.StartPosition + FROM @tmpFileGroups tmpFileGroups + INNER JOIN (SELECT tmpFileGroups.FileGroupName, MIN(SelectedFileGroups.StartPosition) AS StartPosition + FROM @tmpFileGroups tmpFileGroups + INNER JOIN @SelectedFileGroups SelectedFileGroups + ON @CurrentDatabaseName LIKE REPLACE(SelectedFileGroups.DatabaseName,'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(SelectedFileGroups.FileGroupName,'_','[_]') + WHERE SelectedFileGroups.Selected = 1 + GROUP BY tmpFileGroups.FileGroupName) SelectedFileGroups2 + ON tmpFileGroups.FileGroupName = SelectedFileGroups2.FileGroupName; + + WITH tmpFileGroups AS ( + SELECT FileGroupName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, FileGroupName ASC) AS RowNumber + FROM @tmpFileGroups tmpFileGroups + WHERE Selected = 1 + ) + UPDATE tmpFileGroups + SET [Order] = RowNumber END SET @ErrorMessage = '' @@ -945,7 +1027,7 @@ BEGIN FROM @tmpFileGroups WHERE Selected = 1 AND Completed = 0 - ORDER BY ID ASC + ORDER BY [Order] ASC IF @@ROWCOUNT = 0 BEGIN @@ -1030,9 +1112,9 @@ BEGIN -- Check objects IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') BEGIN - SET @CurrentCommand06 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' + SET @CurrentCommand06 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' - INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, Selected, Completed) + INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, [Order], Selected, Completed) EXECUTE sp_executesql @statement = @CurrentCommand06 SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -1058,6 +1140,25 @@ BEGIN INNER JOIN @SelectedObjects SelectedObjects ON @CurrentDatabaseName LIKE REPLACE(SelectedObjects.DatabaseName,'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(SelectedObjects.SchemaName,'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(SelectedObjects.ObjectName,'_','[_]') WHERE SelectedObjects.Selected = 0 + + UPDATE tmpObjects + SET tmpObjects.StartPosition = SelectedObjects2.StartPosition + FROM @tmpObjects tmpObjects + INNER JOIN (SELECT tmpObjects.SchemaName, tmpObjects.ObjectName, MIN(SelectedObjects.StartPosition) AS StartPosition + FROM @tmpObjects tmpObjects + INNER JOIN @SelectedObjects SelectedObjects + ON @CurrentDatabaseName LIKE REPLACE(SelectedObjects.DatabaseName,'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(SelectedObjects.SchemaName,'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(SelectedObjects.ObjectName,'_','[_]') + WHERE SelectedObjects.Selected = 1 + GROUP BY tmpObjects.SchemaName, tmpObjects.ObjectName) SelectedObjects2 + ON tmpObjects.SchemaName = SelectedObjects2.SchemaName AND tmpObjects.ObjectName = SelectedObjects2.ObjectName; + + WITH tmpObjects AS ( + SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, SchemaName ASC, ObjectName ASC) AS RowNumber + FROM @tmpObjects tmpObjects + WHERE Selected = 1 + ) + UPDATE tmpObjects + SET [Order] = RowNumber END SET @ErrorMessage = '' @@ -1085,7 +1186,7 @@ BEGIN FROM @tmpObjects WHERE Selected = 1 AND Completed = 0 - ORDER BY ID ASC + ORDER BY [Order] ASC IF @@ROWCOUNT = 0 BEGIN diff --git a/IndexOptimize.sql b/IndexOptimize.sql index d5d80d11..47a1adbb 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -139,15 +139,19 @@ BEGIN DatabaseName nvarchar(max), DatabaseType nvarchar(max), AvailabilityGroup bit, + StartPosition int, + [Order] int, Selected bit, Completed bit, - PRIMARY KEY(Selected, Completed, ID)) + PRIMARY KEY(Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, AvailabilityGroupName nvarchar(max), + StartPosition int, Selected bit) - DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), AvailabilityGroupName nvarchar(max)) + DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), + AvailabilityGroupName nvarchar(max)) DECLARE @tmpIndexesStatistics TABLE (ID int IDENTITY, SchemaID int, @@ -164,22 +168,27 @@ BEGIN PartitionID bigint, PartitionNumber int, PartitionCount int, + StartPosition int, + [Order] int, Selected bit, Completed bit, - PRIMARY KEY(Selected, Completed, ID)) + PRIMARY KEY(Selected, Completed, [Order], ID)) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), DatabaseType nvarchar(max), AvailabilityGroup nvarchar(max), + StartPosition int, Selected bit) DECLARE @SelectedAvailabilityGroups TABLE (AvailabilityGroupName nvarchar(max), + StartPosition int, Selected bit) DECLARE @SelectedIndexes TABLE (DatabaseName nvarchar(max), SchemaName nvarchar(max), ObjectName nvarchar(max), IndexName nvarchar(max), + StartPosition int, Selected bit) DECLARE @Actions TABLE ([Action] nvarchar(max)) @@ -336,32 +345,36 @@ BEGIN FROM Databases1 WHERE EndPosition < LEN(@Databases) + 1 ), - Databases2 (DatabaseItem, Selected) AS + Databases2 (DatabaseItem, StartPosition, Selected) AS ( SELECT CASE WHEN DatabaseItem LIKE '-%' THEN RIGHT(DatabaseItem,LEN(DatabaseItem) - 1) ELSE DatabaseItem END AS DatabaseItem, + StartPosition, CASE WHEN DatabaseItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM Databases1 ), - Databases3 (DatabaseItem, DatabaseType, AvailabilityGroup, Selected) AS + Databases3 (DatabaseItem, DatabaseType, AvailabilityGroup, StartPosition, Selected) AS ( SELECT CASE WHEN DatabaseItem IN('ALL_DATABASES','SYSTEM_DATABASES','USER_DATABASES','AVAILABILITY_GROUP_DATABASES') THEN '%' ELSE DatabaseItem END AS DatabaseItem, CASE WHEN DatabaseItem = 'SYSTEM_DATABASES' THEN 'S' WHEN DatabaseItem = 'USER_DATABASES' THEN 'U' ELSE NULL END AS DatabaseType, CASE WHEN DatabaseItem = 'AVAILABILITY_GROUP_DATABASES' THEN 1 ELSE NULL END AvailabilityGroup, + StartPosition, Selected FROM Databases2 ), - Databases4 (DatabaseName, DatabaseType, AvailabilityGroup, Selected) AS + Databases4 (DatabaseName, DatabaseType, AvailabilityGroup, StartPosition, Selected) AS ( SELECT CASE WHEN LEFT(DatabaseItem,1) = '[' AND RIGHT(DatabaseItem,1) = ']' THEN PARSENAME(DatabaseItem,1) ELSE DatabaseItem END AS DatabaseItem, DatabaseType, AvailabilityGroup, + StartPosition, Selected FROM Databases3 ) - INSERT INTO @SelectedDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected) + INSERT INTO @SelectedDatabases (DatabaseName, DatabaseType, AvailabilityGroup, StartPosition, Selected) SELECT DatabaseName, DatabaseType, AvailabilityGroup, + StartPosition, Selected FROM Databases4 OPTION (MAXRECURSION 0) @@ -379,10 +392,11 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, + 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.databases @@ -412,6 +426,19 @@ BEGIN AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) WHERE SelectedDatabases.Selected = 0 + UPDATE tmpDatabases + SET tmpDatabases.StartPosition = SelectedDatabases2.StartPosition + FROM @tmpDatabases tmpDatabases + INNER JOIN (SELECT tmpDatabases.DatabaseName, MIN(SelectedDatabases.StartPosition) AS StartPosition + FROM @tmpDatabases tmpDatabases + INNER JOIN @SelectedDatabases SelectedDatabases + ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL) + AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) + WHERE SelectedDatabases.Selected = 1 + GROUP BY tmpDatabases.DatabaseName) SelectedDatabases2 + ON tmpDatabases.DatabaseName = SelectedDatabases2.DatabaseName + IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -447,26 +474,29 @@ BEGIN FROM AvailabilityGroups1 WHERE EndPosition < LEN(@AvailabilityGroups) + 1 ), - AvailabilityGroups2 (AvailabilityGroupItem, Selected) AS + AvailabilityGroups2 (AvailabilityGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN AvailabilityGroupItem LIKE '-%' THEN RIGHT(AvailabilityGroupItem,LEN(AvailabilityGroupItem) - 1) ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, CASE WHEN AvailabilityGroupItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM AvailabilityGroups1 ), - AvailabilityGroups3 (AvailabilityGroupItem, Selected) AS + AvailabilityGroups3 (AvailabilityGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN AvailabilityGroupItem = 'ALL_AVAILABILITY_GROUPS' THEN '%' ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, Selected FROM AvailabilityGroups2 ), - AvailabilityGroups4 (AvailabilityGroupName, Selected) AS + AvailabilityGroups4 (AvailabilityGroupName, StartPosition, Selected) AS ( SELECT CASE WHEN LEFT(AvailabilityGroupItem,1) = '[' AND RIGHT(AvailabilityGroupItem,1) = ']' THEN PARSENAME(AvailabilityGroupItem,1) ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, Selected FROM AvailabilityGroups3 ) - INSERT INTO @SelectedAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT AvailabilityGroupName, Selected + INSERT INTO @SelectedAvailabilityGroups (AvailabilityGroupName, StartPosition, Selected) + SELECT AvailabilityGroupName, StartPosition, Selected FROM AvailabilityGroups4 OPTION (MAXRECURSION 0) @@ -484,8 +514,20 @@ BEGIN ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 + UPDATE tmpAvailabilityGroups + SET tmpAvailabilityGroups.StartPosition = SelectedAvailabilityGroups2.StartPosition + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN (SELECT tmpAvailabilityGroups.AvailabilityGroupName, MIN(SelectedAvailabilityGroups.StartPosition) AS StartPosition + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + WHERE SelectedAvailabilityGroups.Selected = 1 + GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2 + ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName + UPDATE tmpDatabases - SET Selected = 1 + SET tmpDatabases.StartPosition = tmpAvailabilityGroups.StartPosition, + tmpDatabases.Selected = 1 FROM @tmpDatabases tmpDatabases INNER JOIN @tmpDatabasesAvailabilityGroups tmpDatabasesAvailabilityGroups ON tmpDatabases.DatabaseName = tmpDatabasesAvailabilityGroups.DatabaseName INNER JOIN @tmpAvailabilityGroups tmpAvailabilityGroups ON tmpDatabasesAvailabilityGroups.AvailabilityGroupName = tmpAvailabilityGroups.AvailabilityGroupName @@ -512,7 +554,19 @@ BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR - END + END; + + ---------------------------------------------------------------------------------------------------- + --// Update database order //-- + ---------------------------------------------------------------------------------------------------- + + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber ---------------------------------------------------------------------------------------------------- --// Select indexes //-- @@ -539,29 +593,32 @@ BEGIN FROM Indexes1 WHERE EndPosition < LEN(@Indexes) + 1 ), - Indexes2 (IndexItem, Selected) AS + Indexes2 (IndexItem, StartPosition, Selected) AS ( SELECT CASE WHEN IndexItem LIKE '-%' THEN RIGHT(IndexItem,LEN(IndexItem) - 1) ELSE IndexItem END AS IndexItem, + StartPosition, CASE WHEN IndexItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM Indexes1 ), - Indexes3 (IndexItem, Selected) AS + Indexes3 (IndexItem, StartPosition, Selected) AS ( SELECT CASE WHEN IndexItem = 'ALL_INDEXES' THEN '%.%.%.%' ELSE IndexItem END AS IndexItem, + StartPosition, Selected FROM Indexes2 ), - Indexes4 (DatabaseName, SchemaName, ObjectName, IndexName, Selected) AS + Indexes4 (DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected) AS ( SELECT CASE WHEN PARSENAME(IndexItem,4) IS NULL THEN PARSENAME(IndexItem,3) ELSE PARSENAME(IndexItem,4) END AS DatabaseName, CASE WHEN PARSENAME(IndexItem,4) IS NULL THEN PARSENAME(IndexItem,2) ELSE PARSENAME(IndexItem,3) END AS SchemaName, CASE WHEN PARSENAME(IndexItem,4) IS NULL THEN PARSENAME(IndexItem,1) ELSE PARSENAME(IndexItem,2) END AS ObjectName, CASE WHEN PARSENAME(IndexItem,4) IS NULL THEN '%' ELSE PARSENAME(IndexItem,1) END AS IndexName, + StartPosition, Selected FROM Indexes3 ) - INSERT INTO @SelectedIndexes (DatabaseName, SchemaName, ObjectName, IndexName, Selected) - SELECT DatabaseName, SchemaName, ObjectName, IndexName, Selected + INSERT INTO @SelectedIndexes (DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected) + SELECT DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected FROM Indexes4 OPTION (MAXRECURSION 0); @@ -894,7 +951,7 @@ BEGIN FROM @tmpDatabases WHERE Selected = 1 AND Completed = 0 - ORDER BY ID ASC + ORDER BY [Order] ASC IF @@ROWCOUNT = 0 BEGIN @@ -989,15 +1046,15 @@ BEGIN -- Select indexes in the current database IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, StatisticsID, StatisticsName, PartitionID, PartitionNumber, PartitionCount, Selected, Completed FROM (' + SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, StatisticsID, StatisticsName, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed FROM (' IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') BEGIN SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized, indexes.index_id AS IndexID, indexes.[name] AS IndexName, indexes.[type] AS IndexType, stats.stats_id AS StatisticsID, stats.name AS StatisticsName' IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', partitions.partition_id AS PartitionID, partitions.partition_number AS PartitionNumber, IndexPartitions.partition_count AS PartitionCount' IF @PartitionLevel = 'N' SET @CurrentCommand01 = @CurrentCommand01 + ', NULL AS PartitionID, NULL AS PartitionNumber, NULL AS PartitionCount' - SET @CurrentCommand01 = @CurrentCommand01 + ', 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.[object_id] = tables.[object_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' - IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id LEFT OUTER JOIN (SELECT partitions.[object_id], partitions.index_id, COUNT(*) AS partition_count FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions GROUP BY partitions.[object_id], partitions.index_id) IndexPartitions ON partitions.[object_id] = IndexPartitions.[object_id] AND partitions.[index_id] = IndexPartitions.[index_id]' + SET @CurrentCommand01 = @CurrentCommand01 + ', 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.[object_id] = tables.[object_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' + IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id LEFT OUTER JOIN (SELECT partitions.[object_id], partitions.index_id, COUNT(DISTINCT partitions.partition_number) AS partition_count FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions GROUP BY partitions.[object_id], partitions.index_id) IndexPartitions ON partitions.[object_id] = IndexPartitions.[object_id] AND partitions.[index_id] = IndexPartitions.[index_id]' IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_partition_stats dm_db_partition_stats ON indexes.[object_id] = dm_db_partition_stats.[object_id] AND indexes.[index_id] = dm_db_partition_stats.[index_id] AND partitions.partition_id = dm_db_partition_stats.partition_id' IF @PartitionLevel = 'N' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN (SELECT dm_db_partition_stats.[object_id], dm_db_partition_stats.[index_id], SUM(dm_db_partition_stats.in_row_data_page_count) AS in_row_data_page_count FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_partition_stats dm_db_partition_stats GROUP BY dm_db_partition_stats.[object_id], dm_db_partition_stats.[index_id]) dm_db_partition_stats ON indexes.[object_id] = dm_db_partition_stats.[object_id] AND indexes.[index_id] = dm_db_partition_stats.[index_id]' SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0' @@ -1006,15 +1063,11 @@ BEGIN IF (EXISTS(SELECT * FROM @ActionsPreferred) AND @UpdateStatistics = 'COLUMNS') OR @UpdateStatistics = 'ALL' SET @CurrentCommand01 = @CurrentCommand01 + ' UNION ' - IF @UpdateStatistics IN('ALL','COLUMNS') SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized, NULL AS IndexID, NULL AS IndexName, NULL AS IndexType, stats.stats_id AS StatisticsID, stats.name AS StatisticsName, NULL AS PartitionID, NULL AS PartitionNumber, NULL AS PartitionCount, 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.[object_id] = tables.[object_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND NOT EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id)' + IF @UpdateStatistics IN('ALL','COLUMNS') SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized, NULL AS IndexID, NULL AS IndexName, NULL AS IndexType, stats.stats_id AS StatisticsID, stats.name AS StatisticsName, NULL AS PartitionID, NULL AS PartitionNumber, NULL AS PartitionCount, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.[object_id] = tables.[object_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND NOT EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id)' - SET @CurrentCommand01 = @CurrentCommand01 + ') IndexesStatistics ORDER BY SchemaName ASC, ObjectName ASC' - IF (EXISTS(SELECT * FROM @ActionsPreferred) AND @UpdateStatistics = 'COLUMNS') OR @UpdateStatistics = 'ALL' SET @CurrentCommand01 = @CurrentCommand01 + ', CASE WHEN IndexType IS NULL THEN 1 ELSE 0 END ASC' - IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') SET @CurrentCommand01 = @CurrentCommand01 + ', IndexType ASC, IndexName ASC' - IF @UpdateStatistics IN('ALL','COLUMNS') SET @CurrentCommand01 = @CurrentCommand01 + ', StatisticsName ASC' - IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', PartitionNumber ASC' + SET @CurrentCommand01 = @CurrentCommand01 + ') IndexesStatistics' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, StatisticsID, StatisticsName, PartitionID, PartitionNumber, PartitionCount, Selected, Completed) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, StatisticsID, StatisticsName, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) EXECUTE sp_executesql @statement = @CurrentCommand01 SET @Error = @@ERROR IF @Error <> 0 @@ -1044,6 +1097,28 @@ BEGIN INNER JOIN @SelectedIndexes SelectedIndexes ON @CurrentDatabaseName LIKE REPLACE(SelectedIndexes.DatabaseName,'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(SelectedIndexes.SchemaName,'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(SelectedIndexes.ObjectName,'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(SelectedIndexes.IndexName,'_','[_]') WHERE SelectedIndexes.Selected = 0 + + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.StartPosition = SelectedIndexes2.StartPosition + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN (SELECT tmpIndexesStatistics.SchemaName, tmpIndexesStatistics.ObjectName, tmpIndexesStatistics.IndexName, tmpIndexesStatistics.StatisticsName, MIN(SelectedIndexes.StartPosition) AS StartPosition + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @SelectedIndexes SelectedIndexes + ON @CurrentDatabaseName LIKE REPLACE(SelectedIndexes.DatabaseName,'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(SelectedIndexes.SchemaName,'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(SelectedIndexes.ObjectName,'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(SelectedIndexes.IndexName,'_','[_]') + WHERE SelectedIndexes.Selected = 1 + GROUP BY tmpIndexesStatistics.SchemaName, tmpIndexesStatistics.ObjectName, tmpIndexesStatistics.IndexName, tmpIndexesStatistics.StatisticsName) SelectedIndexes2 + ON tmpIndexesStatistics.SchemaName = SelectedIndexes2.SchemaName + AND tmpIndexesStatistics.ObjectName = SelectedIndexes2.ObjectName + AND (tmpIndexesStatistics.IndexName = SelectedIndexes2.IndexName OR tmpIndexesStatistics.IndexName IS NULL) + AND (tmpIndexesStatistics.StatisticsName = SelectedIndexes2.StatisticsName OR tmpIndexesStatistics.StatisticsName IS NULL); + + WITH tmpIndexesStatistics AS ( + SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, SchemaName ASC, ObjectName ASC, CASE WHEN IndexType IS NULL THEN 1 ELSE 0 END ASC, IndexType ASC, IndexName ASC, StatisticsName ASC, PartitionNumber ASC) AS RowNumber + FROM @tmpIndexesStatistics tmpIndexesStatistics + WHERE Selected = 1 + ) + UPDATE tmpIndexesStatistics + SET [Order] = RowNumber END SET @ErrorMessage = '' @@ -1097,7 +1172,7 @@ BEGIN FROM @tmpIndexesStatistics WHERE Selected = 1 AND Completed = 0 - ORDER BY ID ASC + ORDER BY [Order] ASC IF @@ROWCOUNT = 0 BEGIN diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 6d2254c3..f16a4335 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 23 May, 2018. +Last updated 28 May, 2018. Ola Hallengren https://ola.hallengren.com @@ -454,22 +454,28 @@ BEGIN DatabaseNameFS nvarchar(max), DatabaseType nvarchar(max), AvailabilityGroup bit, + StartPosition int, + [Order] int, Selected bit, Completed bit, - PRIMARY KEY(Selected, Completed, ID)) + PRIMARY KEY(Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, AvailabilityGroupName nvarchar(max), + StartPosition int, Selected bit) - DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), AvailabilityGroupName nvarchar(max)) + DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), + AvailabilityGroupName nvarchar(max)) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), DatabaseType nvarchar(max), AvailabilityGroup nvarchar(max), + StartPosition int, Selected bit) DECLARE @SelectedAvailabilityGroups TABLE (AvailabilityGroupName nvarchar(max), + StartPosition int, Selected bit) DECLARE @CurrentBackupSet TABLE (ID int IDENTITY PRIMARY KEY, @@ -664,32 +670,36 @@ BEGIN FROM Databases1 WHERE EndPosition < LEN(@Databases) + 1 ), - Databases2 (DatabaseItem, Selected) AS + Databases2 (DatabaseItem, StartPosition, Selected) AS ( SELECT CASE WHEN DatabaseItem LIKE '-%' THEN RIGHT(DatabaseItem,LEN(DatabaseItem) - 1) ELSE DatabaseItem END AS DatabaseItem, + StartPosition, CASE WHEN DatabaseItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM Databases1 ), - Databases3 (DatabaseItem, DatabaseType, AvailabilityGroup, Selected) AS + Databases3 (DatabaseItem, DatabaseType, AvailabilityGroup, StartPosition, Selected) AS ( SELECT CASE WHEN DatabaseItem IN('ALL_DATABASES','SYSTEM_DATABASES','USER_DATABASES','AVAILABILITY_GROUP_DATABASES') THEN '%' ELSE DatabaseItem END AS DatabaseItem, CASE WHEN DatabaseItem = 'SYSTEM_DATABASES' THEN 'S' WHEN DatabaseItem = 'USER_DATABASES' THEN 'U' ELSE NULL END AS DatabaseType, CASE WHEN DatabaseItem = 'AVAILABILITY_GROUP_DATABASES' THEN 1 ELSE NULL END AvailabilityGroup, + StartPosition, Selected FROM Databases2 ), - Databases4 (DatabaseName, DatabaseType, AvailabilityGroup, Selected) AS + Databases4 (DatabaseName, DatabaseType, AvailabilityGroup, StartPosition, Selected) AS ( SELECT CASE WHEN LEFT(DatabaseItem,1) = '[' AND RIGHT(DatabaseItem,1) = ']' THEN PARSENAME(DatabaseItem,1) ELSE DatabaseItem END AS DatabaseItem, DatabaseType, AvailabilityGroup, + StartPosition, Selected FROM Databases3 ) - INSERT INTO @SelectedDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected) + INSERT INTO @SelectedDatabases (DatabaseName, DatabaseType, AvailabilityGroup, StartPosition, Selected) SELECT DatabaseName, DatabaseType, AvailabilityGroup, + StartPosition, Selected FROM Databases4 OPTION (MAXRECURSION 0) @@ -707,11 +717,12 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, + 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.databases @@ -741,6 +752,19 @@ BEGIN AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) WHERE SelectedDatabases.Selected = 0 + UPDATE tmpDatabases + SET tmpDatabases.StartPosition = SelectedDatabases2.StartPosition + FROM @tmpDatabases tmpDatabases + INNER JOIN (SELECT tmpDatabases.DatabaseName, MIN(SelectedDatabases.StartPosition) AS StartPosition + FROM @tmpDatabases tmpDatabases + INNER JOIN @SelectedDatabases SelectedDatabases + ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL) + AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) + WHERE SelectedDatabases.Selected = 1 + GROUP BY tmpDatabases.DatabaseName) SelectedDatabases2 + ON tmpDatabases.DatabaseName = SelectedDatabases2.DatabaseName + IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -776,26 +800,29 @@ BEGIN FROM AvailabilityGroups1 WHERE EndPosition < LEN(@AvailabilityGroups) + 1 ), - AvailabilityGroups2 (AvailabilityGroupItem, Selected) AS + AvailabilityGroups2 (AvailabilityGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN AvailabilityGroupItem LIKE '-%' THEN RIGHT(AvailabilityGroupItem,LEN(AvailabilityGroupItem) - 1) ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, CASE WHEN AvailabilityGroupItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM AvailabilityGroups1 ), - AvailabilityGroups3 (AvailabilityGroupItem, Selected) AS + AvailabilityGroups3 (AvailabilityGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN AvailabilityGroupItem = 'ALL_AVAILABILITY_GROUPS' THEN '%' ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, Selected FROM AvailabilityGroups2 ), - AvailabilityGroups4 (AvailabilityGroupName, Selected) AS + AvailabilityGroups4 (AvailabilityGroupName, StartPosition, Selected) AS ( SELECT CASE WHEN LEFT(AvailabilityGroupItem,1) = '[' AND RIGHT(AvailabilityGroupItem,1) = ']' THEN PARSENAME(AvailabilityGroupItem,1) ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, Selected FROM AvailabilityGroups3 ) - INSERT INTO @SelectedAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT AvailabilityGroupName, Selected + INSERT INTO @SelectedAvailabilityGroups (AvailabilityGroupName, StartPosition, Selected) + SELECT AvailabilityGroupName, StartPosition, Selected FROM AvailabilityGroups4 OPTION (MAXRECURSION 0) @@ -813,8 +840,20 @@ BEGIN ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 + UPDATE tmpAvailabilityGroups + SET tmpAvailabilityGroups.StartPosition = SelectedAvailabilityGroups2.StartPosition + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN (SELECT tmpAvailabilityGroups.AvailabilityGroupName, MIN(SelectedAvailabilityGroups.StartPosition) AS StartPosition + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + WHERE SelectedAvailabilityGroups.Selected = 1 + GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2 + ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName + UPDATE tmpDatabases - SET Selected = 1 + SET tmpDatabases.StartPosition = tmpAvailabilityGroups.StartPosition, + tmpDatabases.Selected = 1 FROM @tmpDatabases tmpDatabases INNER JOIN @tmpDatabasesAvailabilityGroups tmpDatabasesAvailabilityGroups ON tmpDatabases.DatabaseName = tmpDatabasesAvailabilityGroups.DatabaseName INNER JOIN @tmpAvailabilityGroups tmpAvailabilityGroups ON tmpDatabasesAvailabilityGroups.AvailabilityGroupName = tmpAvailabilityGroups.AvailabilityGroupName @@ -841,7 +880,19 @@ BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR - END + END; + + ---------------------------------------------------------------------------------------------------- + --// Update database order //-- + ---------------------------------------------------------------------------------------------------- + + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber ---------------------------------------------------------------------------------------------------- --// Check database names //-- @@ -1598,7 +1649,7 @@ BEGIN FROM @tmpDatabases WHERE Selected = 1 AND Completed = 0 - ORDER BY ID ASC + ORDER BY [Order] ASC IF @@ROWCOUNT = 0 BEGIN @@ -3034,22 +3085,28 @@ BEGIN DatabaseType nvarchar(max), AvailabilityGroup bit, [Snapshot] bit, + StartPosition int, + [Order] int, Selected bit, Completed bit, - PRIMARY KEY(Selected, Completed, ID)) + PRIMARY KEY(Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, AvailabilityGroupName nvarchar(max), + StartPosition int, Selected bit) - DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), AvailabilityGroupName nvarchar(max)) + DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), + AvailabilityGroupName nvarchar(max)) DECLARE @tmpFileGroups TABLE (ID int IDENTITY, FileGroupID int, FileGroupName nvarchar(max), + StartPosition int, + [Order] int, Selected bit, Completed bit, - PRIMARY KEY(Selected, Completed, ID)) + PRIMARY KEY(Selected, Completed, [Order], ID)) DECLARE @tmpObjects TABLE (ID int IDENTITY, SchemaID int, @@ -3057,25 +3114,31 @@ BEGIN ObjectID int, ObjectName nvarchar(max), ObjectType nvarchar(max), + StartPosition int, + [Order] int, Selected bit, Completed bit, - PRIMARY KEY(Selected, Completed, ID)) + PRIMARY KEY(Selected, Completed, [Order], ID)) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), DatabaseType nvarchar(max), AvailabilityGroup nvarchar(max), + StartPosition int, Selected bit) DECLARE @SelectedAvailabilityGroups TABLE (AvailabilityGroupName nvarchar(max), + StartPosition int, Selected bit) DECLARE @SelectedFileGroups TABLE (DatabaseName nvarchar(max), FileGroupName nvarchar(max), + StartPosition int, Selected bit) DECLARE @SelectedObjects TABLE (DatabaseName nvarchar(max), SchemaName nvarchar(max), ObjectName nvarchar(max), + StartPosition int, Selected bit) DECLARE @SelectedCheckCommands TABLE (CheckCommand nvarchar(max)) @@ -3205,32 +3268,36 @@ BEGIN FROM Databases1 WHERE EndPosition < LEN(@Databases) + 1 ), - Databases2 (DatabaseItem, Selected) AS + Databases2 (DatabaseItem, StartPosition, Selected) AS ( SELECT CASE WHEN DatabaseItem LIKE '-%' THEN RIGHT(DatabaseItem,LEN(DatabaseItem) - 1) ELSE DatabaseItem END AS DatabaseItem, + StartPosition, CASE WHEN DatabaseItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM Databases1 ), - Databases3 (DatabaseItem, DatabaseType, AvailabilityGroup, Selected) AS + Databases3 (DatabaseItem, DatabaseType, AvailabilityGroup, StartPosition, Selected) AS ( SELECT CASE WHEN DatabaseItem IN('ALL_DATABASES','SYSTEM_DATABASES','USER_DATABASES','AVAILABILITY_GROUP_DATABASES') THEN '%' ELSE DatabaseItem END AS DatabaseItem, CASE WHEN DatabaseItem = 'SYSTEM_DATABASES' THEN 'S' WHEN DatabaseItem = 'USER_DATABASES' THEN 'U' ELSE NULL END AS DatabaseType, CASE WHEN DatabaseItem = 'AVAILABILITY_GROUP_DATABASES' THEN 1 ELSE NULL END AvailabilityGroup, + StartPosition, Selected FROM Databases2 ), - Databases4 (DatabaseName, DatabaseType, AvailabilityGroup, Selected) AS + Databases4 (DatabaseName, DatabaseType, AvailabilityGroup, StartPosition, Selected) AS ( SELECT CASE WHEN LEFT(DatabaseItem,1) = '[' AND RIGHT(DatabaseItem,1) = ']' THEN PARSENAME(DatabaseItem,1) ELSE DatabaseItem END AS DatabaseItem, DatabaseType, AvailabilityGroup, + StartPosition, Selected FROM Databases3 ) - INSERT INTO @SelectedDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected) + INSERT INTO @SelectedDatabases (DatabaseName, DatabaseType, AvailabilityGroup, StartPosition, Selected) SELECT DatabaseName, DatabaseType, AvailabilityGroup, + StartPosition, Selected FROM Databases4 OPTION (MAXRECURSION 0) @@ -3248,11 +3315,12 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], [Order], Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], + 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.databases @@ -3282,6 +3350,19 @@ BEGIN AND NOT ((tmpDatabases.DatabaseName = 'tempdb' OR tmpDatabases.[Snapshot] = 1) AND tmpDatabases.DatabaseName <> SelectedDatabases.DatabaseName) WHERE SelectedDatabases.Selected = 0 + UPDATE tmpDatabases + SET tmpDatabases.StartPosition = SelectedDatabases2.StartPosition + FROM @tmpDatabases tmpDatabases + INNER JOIN (SELECT tmpDatabases.DatabaseName, MIN(SelectedDatabases.StartPosition) AS StartPosition + FROM @tmpDatabases tmpDatabases + INNER JOIN @SelectedDatabases SelectedDatabases + ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL) + AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) + WHERE SelectedDatabases.Selected = 1 + GROUP BY tmpDatabases.DatabaseName) SelectedDatabases2 + ON tmpDatabases.DatabaseName = SelectedDatabases2.DatabaseName + IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -3317,26 +3398,29 @@ BEGIN FROM AvailabilityGroups1 WHERE EndPosition < LEN(@AvailabilityGroups) + 1 ), - AvailabilityGroups2 (AvailabilityGroupItem, Selected) AS + AvailabilityGroups2 (AvailabilityGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN AvailabilityGroupItem LIKE '-%' THEN RIGHT(AvailabilityGroupItem,LEN(AvailabilityGroupItem) - 1) ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, CASE WHEN AvailabilityGroupItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM AvailabilityGroups1 ), - AvailabilityGroups3 (AvailabilityGroupItem, Selected) AS + AvailabilityGroups3 (AvailabilityGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN AvailabilityGroupItem = 'ALL_AVAILABILITY_GROUPS' THEN '%' ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, Selected FROM AvailabilityGroups2 ), - AvailabilityGroups4 (AvailabilityGroupName, Selected) AS + AvailabilityGroups4 (AvailabilityGroupName, StartPosition, Selected) AS ( SELECT CASE WHEN LEFT(AvailabilityGroupItem,1) = '[' AND RIGHT(AvailabilityGroupItem,1) = ']' THEN PARSENAME(AvailabilityGroupItem,1) ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, Selected FROM AvailabilityGroups3 ) - INSERT INTO @SelectedAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT AvailabilityGroupName, Selected + INSERT INTO @SelectedAvailabilityGroups (AvailabilityGroupName, StartPosition, Selected) + SELECT AvailabilityGroupName, StartPosition, Selected FROM AvailabilityGroups4 OPTION (MAXRECURSION 0) @@ -3354,8 +3438,20 @@ BEGIN ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 + UPDATE tmpAvailabilityGroups + SET tmpAvailabilityGroups.StartPosition = SelectedAvailabilityGroups2.StartPosition + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN (SELECT tmpAvailabilityGroups.AvailabilityGroupName, MIN(SelectedAvailabilityGroups.StartPosition) AS StartPosition + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + WHERE SelectedAvailabilityGroups.Selected = 1 + GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2 + ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName + UPDATE tmpDatabases - SET Selected = 1 + SET tmpDatabases.StartPosition = tmpAvailabilityGroups.StartPosition, + tmpDatabases.Selected = 1 FROM @tmpDatabases tmpDatabases INNER JOIN @tmpDatabasesAvailabilityGroups tmpDatabasesAvailabilityGroups ON tmpDatabases.DatabaseName = tmpDatabasesAvailabilityGroups.DatabaseName INNER JOIN @tmpAvailabilityGroups tmpAvailabilityGroups ON tmpDatabasesAvailabilityGroups.AvailabilityGroupName = tmpAvailabilityGroups.AvailabilityGroupName @@ -3382,7 +3478,19 @@ BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR - END + END; + + ---------------------------------------------------------------------------------------------------- + --// Update database order //-- + ---------------------------------------------------------------------------------------------------- + + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber ---------------------------------------------------------------------------------------------------- --// Select filegroups //-- @@ -3409,27 +3517,30 @@ BEGIN FROM FileGroups1 WHERE EndPosition < LEN(@FileGroups) + 1 ), - FileGroups2 (FileGroupItem, Selected) AS + FileGroups2 (FileGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN FileGroupItem LIKE '-%' THEN RIGHT(FileGroupItem,LEN(FileGroupItem) - 1) ELSE FileGroupItem END AS FileGroupItem, + StartPosition, CASE WHEN FileGroupItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM FileGroups1 ), - FileGroups3 (FileGroupItem, Selected) AS + FileGroups3 (FileGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN FileGroupItem = 'ALL_FILEGROUPS' THEN '%.%' ELSE FileGroupItem END AS FileGroupItem, + StartPosition, Selected FROM FileGroups2 ), - FileGroups4 (DatabaseName, FileGroupName, Selected) AS + FileGroups4 (DatabaseName, FileGroupName, StartPosition, Selected) AS ( SELECT CASE WHEN PARSENAME(FileGroupItem,4) IS NULL AND PARSENAME(FileGroupItem,3) IS NULL THEN PARSENAME(FileGroupItem,2) ELSE NULL END AS DatabaseName, CASE WHEN PARSENAME(FileGroupItem,4) IS NULL AND PARSENAME(FileGroupItem,3) IS NULL THEN PARSENAME(FileGroupItem,1) ELSE NULL END AS FileGroupName, + StartPosition, Selected FROM FileGroups3 ) - INSERT INTO @SelectedFileGroups (DatabaseName, FileGroupName, Selected) - SELECT DatabaseName, FileGroupName, Selected + INSERT INTO @SelectedFileGroups (DatabaseName, FileGroupName, StartPosition, Selected) + SELECT DatabaseName, FileGroupName, StartPosition, Selected FROM FileGroups4 OPTION (MAXRECURSION 0) @@ -3458,28 +3569,31 @@ BEGIN FROM Objects1 WHERE EndPosition < LEN(@Objects) + 1 ), - Objects2 (ObjectItem, Selected) AS + Objects2 (ObjectItem, StartPosition, Selected) AS ( SELECT CASE WHEN ObjectItem LIKE '-%' THEN RIGHT(ObjectItem,LEN(ObjectItem) - 1) ELSE ObjectItem END AS ObjectItem, + StartPosition, CASE WHEN ObjectItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM Objects1 ), - Objects3 (ObjectItem, Selected) AS + Objects3 (ObjectItem, StartPosition, Selected) AS ( SELECT CASE WHEN ObjectItem = 'ALL_OBJECTS' THEN '%.%.%' ELSE ObjectItem END AS ObjectItem, + StartPosition, Selected FROM Objects2 ), - Objects4 (DatabaseName, SchemaName, ObjectName, Selected) AS + Objects4 (DatabaseName, SchemaName, ObjectName, StartPosition, Selected) AS ( SELECT CASE WHEN PARSENAME(ObjectItem,4) IS NULL THEN PARSENAME(ObjectItem,3) ELSE NULL END AS DatabaseName, CASE WHEN PARSENAME(ObjectItem,4) IS NULL THEN PARSENAME(ObjectItem,2) ELSE NULL END AS SchemaName, CASE WHEN PARSENAME(ObjectItem,4) IS NULL THEN PARSENAME(ObjectItem,1) ELSE NULL END AS ObjectName, + StartPosition, Selected FROM Objects3 ) - INSERT INTO @SelectedObjects (DatabaseName, SchemaName, ObjectName, Selected) - SELECT DatabaseName, SchemaName, ObjectName, Selected + INSERT INTO @SelectedObjects (DatabaseName, SchemaName, ObjectName, StartPosition, Selected) + SELECT DatabaseName, SchemaName, ObjectName, StartPosition, Selected FROM Objects4 OPTION (MAXRECURSION 0); @@ -3708,7 +3822,7 @@ BEGIN FROM @tmpDatabases WHERE Selected = 1 AND Completed = 0 - ORDER BY ID ASC + ORDER BY [Order] ASC IF @@ROWCOUNT = 0 BEGIN @@ -3828,9 +3942,9 @@ BEGIN -- Check filegroups IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') BEGIN - SET @CurrentCommand02 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' + SET @CurrentCommand02 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' - INSERT INTO @tmpFileGroups (FileGroupID, FileGroupName, Selected, Completed) + INSERT INTO @tmpFileGroups (FileGroupID, FileGroupName, [Order], Selected, Completed) EXECUTE sp_executesql @statement = @CurrentCommand02 SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -3856,6 +3970,25 @@ BEGIN INNER JOIN @SelectedFileGroups SelectedFileGroups ON @CurrentDatabaseName LIKE REPLACE(SelectedFileGroups.DatabaseName,'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(SelectedFileGroups.FileGroupName,'_','[_]') WHERE SelectedFileGroups.Selected = 0 + + UPDATE tmpFileGroups + SET tmpFileGroups.StartPosition = SelectedFileGroups2.StartPosition + FROM @tmpFileGroups tmpFileGroups + INNER JOIN (SELECT tmpFileGroups.FileGroupName, MIN(SelectedFileGroups.StartPosition) AS StartPosition + FROM @tmpFileGroups tmpFileGroups + INNER JOIN @SelectedFileGroups SelectedFileGroups + ON @CurrentDatabaseName LIKE REPLACE(SelectedFileGroups.DatabaseName,'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(SelectedFileGroups.FileGroupName,'_','[_]') + WHERE SelectedFileGroups.Selected = 1 + GROUP BY tmpFileGroups.FileGroupName) SelectedFileGroups2 + ON tmpFileGroups.FileGroupName = SelectedFileGroups2.FileGroupName; + + WITH tmpFileGroups AS ( + SELECT FileGroupName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, FileGroupName ASC) AS RowNumber + FROM @tmpFileGroups tmpFileGroups + WHERE Selected = 1 + ) + UPDATE tmpFileGroups + SET [Order] = RowNumber END SET @ErrorMessage = '' @@ -3879,7 +4012,7 @@ BEGIN FROM @tmpFileGroups WHERE Selected = 1 AND Completed = 0 - ORDER BY ID ASC + ORDER BY [Order] ASC IF @@ROWCOUNT = 0 BEGIN @@ -3964,9 +4097,9 @@ BEGIN -- Check objects IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') BEGIN - SET @CurrentCommand06 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' + SET @CurrentCommand06 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' - INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, Selected, Completed) + INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, [Order], Selected, Completed) EXECUTE sp_executesql @statement = @CurrentCommand06 SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -3992,6 +4125,25 @@ BEGIN INNER JOIN @SelectedObjects SelectedObjects ON @CurrentDatabaseName LIKE REPLACE(SelectedObjects.DatabaseName,'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(SelectedObjects.SchemaName,'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(SelectedObjects.ObjectName,'_','[_]') WHERE SelectedObjects.Selected = 0 + + UPDATE tmpObjects + SET tmpObjects.StartPosition = SelectedObjects2.StartPosition + FROM @tmpObjects tmpObjects + INNER JOIN (SELECT tmpObjects.SchemaName, tmpObjects.ObjectName, MIN(SelectedObjects.StartPosition) AS StartPosition + FROM @tmpObjects tmpObjects + INNER JOIN @SelectedObjects SelectedObjects + ON @CurrentDatabaseName LIKE REPLACE(SelectedObjects.DatabaseName,'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(SelectedObjects.SchemaName,'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(SelectedObjects.ObjectName,'_','[_]') + WHERE SelectedObjects.Selected = 1 + GROUP BY tmpObjects.SchemaName, tmpObjects.ObjectName) SelectedObjects2 + ON tmpObjects.SchemaName = SelectedObjects2.SchemaName AND tmpObjects.ObjectName = SelectedObjects2.ObjectName; + + WITH tmpObjects AS ( + SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, SchemaName ASC, ObjectName ASC) AS RowNumber + FROM @tmpObjects tmpObjects + WHERE Selected = 1 + ) + UPDATE tmpObjects + SET [Order] = RowNumber END SET @ErrorMessage = '' @@ -4019,7 +4171,7 @@ BEGIN FROM @tmpObjects WHERE Selected = 1 AND Completed = 0 - ORDER BY ID ASC + ORDER BY [Order] ASC IF @@ROWCOUNT = 0 BEGIN @@ -4310,15 +4462,19 @@ BEGIN DatabaseName nvarchar(max), DatabaseType nvarchar(max), AvailabilityGroup bit, + StartPosition int, + [Order] int, Selected bit, Completed bit, - PRIMARY KEY(Selected, Completed, ID)) + PRIMARY KEY(Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, AvailabilityGroupName nvarchar(max), + StartPosition int, Selected bit) - DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), AvailabilityGroupName nvarchar(max)) + DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), + AvailabilityGroupName nvarchar(max)) DECLARE @tmpIndexesStatistics TABLE (ID int IDENTITY, SchemaID int, @@ -4335,22 +4491,27 @@ BEGIN PartitionID bigint, PartitionNumber int, PartitionCount int, + StartPosition int, + [Order] int, Selected bit, Completed bit, - PRIMARY KEY(Selected, Completed, ID)) + PRIMARY KEY(Selected, Completed, [Order], ID)) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), DatabaseType nvarchar(max), AvailabilityGroup nvarchar(max), + StartPosition int, Selected bit) DECLARE @SelectedAvailabilityGroups TABLE (AvailabilityGroupName nvarchar(max), + StartPosition int, Selected bit) DECLARE @SelectedIndexes TABLE (DatabaseName nvarchar(max), SchemaName nvarchar(max), ObjectName nvarchar(max), IndexName nvarchar(max), + StartPosition int, Selected bit) DECLARE @Actions TABLE ([Action] nvarchar(max)) @@ -4507,32 +4668,36 @@ BEGIN FROM Databases1 WHERE EndPosition < LEN(@Databases) + 1 ), - Databases2 (DatabaseItem, Selected) AS + Databases2 (DatabaseItem, StartPosition, Selected) AS ( SELECT CASE WHEN DatabaseItem LIKE '-%' THEN RIGHT(DatabaseItem,LEN(DatabaseItem) - 1) ELSE DatabaseItem END AS DatabaseItem, + StartPosition, CASE WHEN DatabaseItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM Databases1 ), - Databases3 (DatabaseItem, DatabaseType, AvailabilityGroup, Selected) AS + Databases3 (DatabaseItem, DatabaseType, AvailabilityGroup, StartPosition, Selected) AS ( SELECT CASE WHEN DatabaseItem IN('ALL_DATABASES','SYSTEM_DATABASES','USER_DATABASES','AVAILABILITY_GROUP_DATABASES') THEN '%' ELSE DatabaseItem END AS DatabaseItem, CASE WHEN DatabaseItem = 'SYSTEM_DATABASES' THEN 'S' WHEN DatabaseItem = 'USER_DATABASES' THEN 'U' ELSE NULL END AS DatabaseType, CASE WHEN DatabaseItem = 'AVAILABILITY_GROUP_DATABASES' THEN 1 ELSE NULL END AvailabilityGroup, + StartPosition, Selected FROM Databases2 ), - Databases4 (DatabaseName, DatabaseType, AvailabilityGroup, Selected) AS + Databases4 (DatabaseName, DatabaseType, AvailabilityGroup, StartPosition, Selected) AS ( SELECT CASE WHEN LEFT(DatabaseItem,1) = '[' AND RIGHT(DatabaseItem,1) = ']' THEN PARSENAME(DatabaseItem,1) ELSE DatabaseItem END AS DatabaseItem, DatabaseType, AvailabilityGroup, + StartPosition, Selected FROM Databases3 ) - INSERT INTO @SelectedDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected) + INSERT INTO @SelectedDatabases (DatabaseName, DatabaseType, AvailabilityGroup, StartPosition, Selected) SELECT DatabaseName, DatabaseType, AvailabilityGroup, + StartPosition, Selected FROM Databases4 OPTION (MAXRECURSION 0) @@ -4550,10 +4715,11 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, + 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.databases @@ -4583,6 +4749,19 @@ BEGIN AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) WHERE SelectedDatabases.Selected = 0 + UPDATE tmpDatabases + SET tmpDatabases.StartPosition = SelectedDatabases2.StartPosition + FROM @tmpDatabases tmpDatabases + INNER JOIN (SELECT tmpDatabases.DatabaseName, MIN(SelectedDatabases.StartPosition) AS StartPosition + FROM @tmpDatabases tmpDatabases + INNER JOIN @SelectedDatabases SelectedDatabases + ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL) + AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) + WHERE SelectedDatabases.Selected = 1 + GROUP BY tmpDatabases.DatabaseName) SelectedDatabases2 + ON tmpDatabases.DatabaseName = SelectedDatabases2.DatabaseName + IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -4618,26 +4797,29 @@ BEGIN FROM AvailabilityGroups1 WHERE EndPosition < LEN(@AvailabilityGroups) + 1 ), - AvailabilityGroups2 (AvailabilityGroupItem, Selected) AS + AvailabilityGroups2 (AvailabilityGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN AvailabilityGroupItem LIKE '-%' THEN RIGHT(AvailabilityGroupItem,LEN(AvailabilityGroupItem) - 1) ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, CASE WHEN AvailabilityGroupItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM AvailabilityGroups1 ), - AvailabilityGroups3 (AvailabilityGroupItem, Selected) AS + AvailabilityGroups3 (AvailabilityGroupItem, StartPosition, Selected) AS ( SELECT CASE WHEN AvailabilityGroupItem = 'ALL_AVAILABILITY_GROUPS' THEN '%' ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, Selected FROM AvailabilityGroups2 ), - AvailabilityGroups4 (AvailabilityGroupName, Selected) AS + AvailabilityGroups4 (AvailabilityGroupName, StartPosition, Selected) AS ( SELECT CASE WHEN LEFT(AvailabilityGroupItem,1) = '[' AND RIGHT(AvailabilityGroupItem,1) = ']' THEN PARSENAME(AvailabilityGroupItem,1) ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, Selected FROM AvailabilityGroups3 ) - INSERT INTO @SelectedAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT AvailabilityGroupName, Selected + INSERT INTO @SelectedAvailabilityGroups (AvailabilityGroupName, StartPosition, Selected) + SELECT AvailabilityGroupName, StartPosition, Selected FROM AvailabilityGroups4 OPTION (MAXRECURSION 0) @@ -4655,8 +4837,20 @@ BEGIN ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 + UPDATE tmpAvailabilityGroups + SET tmpAvailabilityGroups.StartPosition = SelectedAvailabilityGroups2.StartPosition + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN (SELECT tmpAvailabilityGroups.AvailabilityGroupName, MIN(SelectedAvailabilityGroups.StartPosition) AS StartPosition + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + WHERE SelectedAvailabilityGroups.Selected = 1 + GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2 + ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName + UPDATE tmpDatabases - SET Selected = 1 + SET tmpDatabases.StartPosition = tmpAvailabilityGroups.StartPosition, + tmpDatabases.Selected = 1 FROM @tmpDatabases tmpDatabases INNER JOIN @tmpDatabasesAvailabilityGroups tmpDatabasesAvailabilityGroups ON tmpDatabases.DatabaseName = tmpDatabasesAvailabilityGroups.DatabaseName INNER JOIN @tmpAvailabilityGroups tmpAvailabilityGroups ON tmpDatabasesAvailabilityGroups.AvailabilityGroupName = tmpAvailabilityGroups.AvailabilityGroupName @@ -4683,7 +4877,19 @@ BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR - END + END; + + ---------------------------------------------------------------------------------------------------- + --// Update database order //-- + ---------------------------------------------------------------------------------------------------- + + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber ---------------------------------------------------------------------------------------------------- --// Select indexes //-- @@ -4710,29 +4916,32 @@ BEGIN FROM Indexes1 WHERE EndPosition < LEN(@Indexes) + 1 ), - Indexes2 (IndexItem, Selected) AS + Indexes2 (IndexItem, StartPosition, Selected) AS ( SELECT CASE WHEN IndexItem LIKE '-%' THEN RIGHT(IndexItem,LEN(IndexItem) - 1) ELSE IndexItem END AS IndexItem, + StartPosition, CASE WHEN IndexItem LIKE '-%' THEN 0 ELSE 1 END AS Selected FROM Indexes1 ), - Indexes3 (IndexItem, Selected) AS + Indexes3 (IndexItem, StartPosition, Selected) AS ( SELECT CASE WHEN IndexItem = 'ALL_INDEXES' THEN '%.%.%.%' ELSE IndexItem END AS IndexItem, + StartPosition, Selected FROM Indexes2 ), - Indexes4 (DatabaseName, SchemaName, ObjectName, IndexName, Selected) AS + Indexes4 (DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected) AS ( SELECT CASE WHEN PARSENAME(IndexItem,4) IS NULL THEN PARSENAME(IndexItem,3) ELSE PARSENAME(IndexItem,4) END AS DatabaseName, CASE WHEN PARSENAME(IndexItem,4) IS NULL THEN PARSENAME(IndexItem,2) ELSE PARSENAME(IndexItem,3) END AS SchemaName, CASE WHEN PARSENAME(IndexItem,4) IS NULL THEN PARSENAME(IndexItem,1) ELSE PARSENAME(IndexItem,2) END AS ObjectName, CASE WHEN PARSENAME(IndexItem,4) IS NULL THEN '%' ELSE PARSENAME(IndexItem,1) END AS IndexName, + StartPosition, Selected FROM Indexes3 ) - INSERT INTO @SelectedIndexes (DatabaseName, SchemaName, ObjectName, IndexName, Selected) - SELECT DatabaseName, SchemaName, ObjectName, IndexName, Selected + INSERT INTO @SelectedIndexes (DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected) + SELECT DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected FROM Indexes4 OPTION (MAXRECURSION 0); @@ -5065,7 +5274,7 @@ BEGIN FROM @tmpDatabases WHERE Selected = 1 AND Completed = 0 - ORDER BY ID ASC + ORDER BY [Order] ASC IF @@ROWCOUNT = 0 BEGIN @@ -5160,15 +5369,15 @@ BEGIN -- Select indexes in the current database IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, StatisticsID, StatisticsName, PartitionID, PartitionNumber, PartitionCount, Selected, Completed FROM (' + SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, StatisticsID, StatisticsName, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed FROM (' IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') BEGIN SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized, indexes.index_id AS IndexID, indexes.[name] AS IndexName, indexes.[type] AS IndexType, stats.stats_id AS StatisticsID, stats.name AS StatisticsName' IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', partitions.partition_id AS PartitionID, partitions.partition_number AS PartitionNumber, IndexPartitions.partition_count AS PartitionCount' IF @PartitionLevel = 'N' SET @CurrentCommand01 = @CurrentCommand01 + ', NULL AS PartitionID, NULL AS PartitionNumber, NULL AS PartitionCount' - SET @CurrentCommand01 = @CurrentCommand01 + ', 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.[object_id] = tables.[object_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' - IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id LEFT OUTER JOIN (SELECT partitions.[object_id], partitions.index_id, COUNT(*) AS partition_count FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions GROUP BY partitions.[object_id], partitions.index_id) IndexPartitions ON partitions.[object_id] = IndexPartitions.[object_id] AND partitions.[index_id] = IndexPartitions.[index_id]' + SET @CurrentCommand01 = @CurrentCommand01 + ', 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.[object_id] = tables.[object_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' + IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id LEFT OUTER JOIN (SELECT partitions.[object_id], partitions.index_id, COUNT(DISTINCT partitions.partition_number) AS partition_count FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions GROUP BY partitions.[object_id], partitions.index_id) IndexPartitions ON partitions.[object_id] = IndexPartitions.[object_id] AND partitions.[index_id] = IndexPartitions.[index_id]' IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_partition_stats dm_db_partition_stats ON indexes.[object_id] = dm_db_partition_stats.[object_id] AND indexes.[index_id] = dm_db_partition_stats.[index_id] AND partitions.partition_id = dm_db_partition_stats.partition_id' IF @PartitionLevel = 'N' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN (SELECT dm_db_partition_stats.[object_id], dm_db_partition_stats.[index_id], SUM(dm_db_partition_stats.in_row_data_page_count) AS in_row_data_page_count FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_partition_stats dm_db_partition_stats GROUP BY dm_db_partition_stats.[object_id], dm_db_partition_stats.[index_id]) dm_db_partition_stats ON indexes.[object_id] = dm_db_partition_stats.[object_id] AND indexes.[index_id] = dm_db_partition_stats.[index_id]' SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0' @@ -5177,15 +5386,11 @@ BEGIN IF (EXISTS(SELECT * FROM @ActionsPreferred) AND @UpdateStatistics = 'COLUMNS') OR @UpdateStatistics = 'ALL' SET @CurrentCommand01 = @CurrentCommand01 + ' UNION ' - IF @UpdateStatistics IN('ALL','COLUMNS') SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized, NULL AS IndexID, NULL AS IndexName, NULL AS IndexType, stats.stats_id AS StatisticsID, stats.name AS StatisticsName, NULL AS PartitionID, NULL AS PartitionNumber, NULL AS PartitionCount, 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.[object_id] = tables.[object_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND NOT EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id)' + IF @UpdateStatistics IN('ALL','COLUMNS') SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized, NULL AS IndexID, NULL AS IndexName, NULL AS IndexType, stats.stats_id AS StatisticsID, stats.name AS StatisticsName, NULL AS PartitionID, NULL AS PartitionNumber, NULL AS PartitionCount, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.[object_id] = tables.[object_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND NOT EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id)' - SET @CurrentCommand01 = @CurrentCommand01 + ') IndexesStatistics ORDER BY SchemaName ASC, ObjectName ASC' - IF (EXISTS(SELECT * FROM @ActionsPreferred) AND @UpdateStatistics = 'COLUMNS') OR @UpdateStatistics = 'ALL' SET @CurrentCommand01 = @CurrentCommand01 + ', CASE WHEN IndexType IS NULL THEN 1 ELSE 0 END ASC' - IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') SET @CurrentCommand01 = @CurrentCommand01 + ', IndexType ASC, IndexName ASC' - IF @UpdateStatistics IN('ALL','COLUMNS') SET @CurrentCommand01 = @CurrentCommand01 + ', StatisticsName ASC' - IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', PartitionNumber ASC' + SET @CurrentCommand01 = @CurrentCommand01 + ') IndexesStatistics' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, StatisticsID, StatisticsName, PartitionID, PartitionNumber, PartitionCount, Selected, Completed) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, StatisticsID, StatisticsName, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) EXECUTE sp_executesql @statement = @CurrentCommand01 SET @Error = @@ERROR IF @Error <> 0 @@ -5215,6 +5420,28 @@ BEGIN INNER JOIN @SelectedIndexes SelectedIndexes ON @CurrentDatabaseName LIKE REPLACE(SelectedIndexes.DatabaseName,'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(SelectedIndexes.SchemaName,'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(SelectedIndexes.ObjectName,'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(SelectedIndexes.IndexName,'_','[_]') WHERE SelectedIndexes.Selected = 0 + + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.StartPosition = SelectedIndexes2.StartPosition + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN (SELECT tmpIndexesStatistics.SchemaName, tmpIndexesStatistics.ObjectName, tmpIndexesStatistics.IndexName, tmpIndexesStatistics.StatisticsName, MIN(SelectedIndexes.StartPosition) AS StartPosition + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @SelectedIndexes SelectedIndexes + ON @CurrentDatabaseName LIKE REPLACE(SelectedIndexes.DatabaseName,'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(SelectedIndexes.SchemaName,'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(SelectedIndexes.ObjectName,'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(SelectedIndexes.IndexName,'_','[_]') + WHERE SelectedIndexes.Selected = 1 + GROUP BY tmpIndexesStatistics.SchemaName, tmpIndexesStatistics.ObjectName, tmpIndexesStatistics.IndexName, tmpIndexesStatistics.StatisticsName) SelectedIndexes2 + ON tmpIndexesStatistics.SchemaName = SelectedIndexes2.SchemaName + AND tmpIndexesStatistics.ObjectName = SelectedIndexes2.ObjectName + AND (tmpIndexesStatistics.IndexName = SelectedIndexes2.IndexName OR tmpIndexesStatistics.IndexName IS NULL) + AND (tmpIndexesStatistics.StatisticsName = SelectedIndexes2.StatisticsName OR tmpIndexesStatistics.StatisticsName IS NULL); + + WITH tmpIndexesStatistics AS ( + SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, SchemaName ASC, ObjectName ASC, CASE WHEN IndexType IS NULL THEN 1 ELSE 0 END ASC, IndexType ASC, IndexName ASC, StatisticsName ASC, PartitionNumber ASC) AS RowNumber + FROM @tmpIndexesStatistics tmpIndexesStatistics + WHERE Selected = 1 + ) + UPDATE tmpIndexesStatistics + SET [Order] = RowNumber END SET @ErrorMessage = '' @@ -5268,7 +5495,7 @@ BEGIN FROM @tmpIndexesStatistics WHERE Selected = 1 AND Completed = 0 - ORDER BY ID ASC + ORDER BY [Order] ASC IF @@ROWCOUNT = 0 BEGIN From d1d320d4eaac5297b7a69ba471ea805d372cb65c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 30 May 2018 23:06:32 +0200 Subject: [PATCH 028/188] Add files via upload --- DatabaseBackup.sql | 8 ++++---- MaintenanceSolution.sql | 10 +++++----- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index e5a689bd..0c67243c 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -1341,9 +1341,9 @@ BEGIN --// Check Availability Group cluster name //-- ---------------------------------------------------------------------------------------------------- - IF @Version >= 11 + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @Cluster = cluster_name + SELECT @Cluster = NULLIF(cluster_name,'') FROM sys.dm_hadr_cluster END @@ -1381,7 +1381,7 @@ BEGIN END END - IF @Version >= 11 AND @Cluster IS NOT NULL + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @CurrentAvailabilityGroup = availability_groups.name, @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, @@ -1393,7 +1393,7 @@ BEGIN WHERE databases.name = @CurrentDatabaseName END - IF @Version >= 11 AND @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) END diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index f16a4335..5689c073 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 28 May, 2018. +Last updated 30 May, 2018. Ola Hallengren https://ola.hallengren.com @@ -1630,9 +1630,9 @@ BEGIN --// Check Availability Group cluster name //-- ---------------------------------------------------------------------------------------------------- - IF @Version >= 11 + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @Cluster = cluster_name + SELECT @Cluster = NULLIF(cluster_name,'') FROM sys.dm_hadr_cluster END @@ -1670,7 +1670,7 @@ BEGIN END END - IF @Version >= 11 AND @Cluster IS NOT NULL + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @CurrentAvailabilityGroup = availability_groups.name, @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, @@ -1682,7 +1682,7 @@ BEGIN WHERE databases.name = @CurrentDatabaseName END - IF @Version >= 11 AND @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) END From 313096dbf10df0729bb827d3cc1d85bcea232518 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 1 Jun 2018 20:34:06 +0200 Subject: [PATCH 029/188] Add files via upload --- DatabaseBackup.sql | 20 ++++++---- DatabaseIntegrityCheck.sql | 14 +------ IndexOptimize.sql | 39 +++++++++---------- MaintenanceSolution.sql | 77 ++++++++++++++++---------------------- 4 files changed, 62 insertions(+), 88 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 0c67243c..779d8f5a 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -1223,32 +1223,32 @@ BEGIN SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1620,6 +1620,7 @@ BEGIN IF @Cluster IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}','') IF @CurrentAvailabilityGroup IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}','') IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}','') + IF @Description IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}','') WHILE (@Updated = 1 OR @Updated IS NULL) BEGIN @@ -1768,6 +1769,7 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupType}',@CurrentBackupType) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Partial}','PARTIAL') SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{CopyOnly}','COPY_ONLY') + IF @Description IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) @@ -1797,6 +1799,7 @@ BEGIN IF @Cluster IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}','') IF @CurrentAvailabilityGroup IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{AvailabilityGroupName}','') IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}','') + IF @Description IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}','') IF @NumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileNumber}','') WHILE (@Updated = 1 OR @Updated IS NULL) @@ -1900,6 +1903,7 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{BackupType}',@CurrentBackupType) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Partial}','PARTIAL') SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{CopyOnly}','COPY_ONLY') + IF @Description IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index c85e207b..1cdec89b 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -49,8 +49,6 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @AmazonRDS bit - DECLARE @Cluster nvarchar(max) - DECLARE @CurrentDBID int DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -815,16 +813,6 @@ BEGIN SET @Error = @@ERROR END - ---------------------------------------------------------------------------------------------------- - --// Check Availability Group cluster name //-- - ---------------------------------------------------------------------------------------------------- - - IF @Version >= 11 AND SERVERPROPERTY('EngineEdition') <> 5 - BEGIN - SELECT @Cluster = cluster_name - FROM sys.dm_hadr_cluster - END - ---------------------------------------------------------------------------------------------------- --// Execute commands //-- ---------------------------------------------------------------------------------------------------- @@ -858,7 +846,7 @@ BEGIN END END - IF @Version >= 11 AND @Cluster IS NOT NULL + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @CurrentAvailabilityGroup = availability_groups.name, @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 47a1adbb..50bdbcc7 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -15,7 +15,8 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @FragmentationHigh nvarchar(max) = 'INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', @FragmentationLevel1 int = 5, @FragmentationLevel2 int = 30, -@PageCountLevel int = 1000, +@MinNumberOfPages int = 1000, +@MaxNumberOfPages int = NULL, @SortInTempdb nvarchar(max) = 'N', @MaxDOP int = NULL, @FillFactor int = NULL, @@ -65,8 +66,6 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @AmazonRDS bit - DECLARE @Cluster nvarchar(max) - DECLARE @CurrentDBID int DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -242,7 +241,8 @@ BEGIN SET @Parameters = @Parameters + ', @FragmentationHigh = ' + ISNULL('''' + REPLACE(@FragmentationHigh,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @FragmentationLevel1 = ' + ISNULL(CAST(@FragmentationLevel1 AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @FragmentationLevel2 = ' + ISNULL(CAST(@FragmentationLevel2 AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @PageCountLevel = ' + ISNULL(CAST(@PageCountLevel AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @MinNumberOfPages = ' + ISNULL(CAST(@MinNumberOfPages AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @MaxNumberOfPages = ' + ISNULL(CAST(@MaxNumberOfPages AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @SortInTempdb = ' + ISNULL('''' + REPLACE(@SortInTempdb,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar),'NULL') @@ -728,9 +728,16 @@ BEGIN SET @Error = @@ERROR END - IF @PageCountLevel < 0 OR @PageCountLevel IS NULL + IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL + BEGIN + SET @ErrorMessage = 'The value for the parameter @MinNumberOfPages is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @MaxNumberOfPages < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @PageCountLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MaxNumberOfPages is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END @@ -929,16 +936,6 @@ BEGIN SET @Error = @@ERROR END - ---------------------------------------------------------------------------------------------------- - --// Check Availability Group cluster name //-- - ---------------------------------------------------------------------------------------------------- - - IF @Version >= 11 AND SERVERPROPERTY('EngineEdition') <> 5 - BEGIN - SELECT @Cluster = cluster_name - FROM sys.dm_hadr_cluster - END - ---------------------------------------------------------------------------------------------------- --// Execute commands //-- ---------------------------------------------------------------------------------------------------- @@ -972,7 +969,7 @@ BEGIN END END - IF @Version >= 11 AND @Cluster IS NOT NULL + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @CurrentAvailabilityGroup = availability_groups.name, @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc @@ -1055,10 +1052,7 @@ BEGIN IF @PartitionLevel = 'N' SET @CurrentCommand01 = @CurrentCommand01 + ', NULL AS PartitionID, NULL AS PartitionNumber, NULL AS PartitionCount' SET @CurrentCommand01 = @CurrentCommand01 + ', 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.[object_id] = tables.[object_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id LEFT OUTER JOIN (SELECT partitions.[object_id], partitions.index_id, COUNT(DISTINCT partitions.partition_number) AS partition_count FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions GROUP BY partitions.[object_id], partitions.index_id) IndexPartitions ON partitions.[object_id] = IndexPartitions.[object_id] AND partitions.[index_id] = IndexPartitions.[index_id]' - IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_partition_stats dm_db_partition_stats ON indexes.[object_id] = dm_db_partition_stats.[object_id] AND indexes.[index_id] = dm_db_partition_stats.[index_id] AND partitions.partition_id = dm_db_partition_stats.partition_id' - IF @PartitionLevel = 'N' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN (SELECT dm_db_partition_stats.[object_id], dm_db_partition_stats.[index_id], SUM(dm_db_partition_stats.in_row_data_page_count) AS in_row_data_page_count FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_partition_stats dm_db_partition_stats GROUP BY dm_db_partition_stats.[object_id], dm_db_partition_stats.[index_id]) dm_db_partition_stats ON indexes.[object_id] = dm_db_partition_stats.[object_id] AND indexes.[index_id] = dm_db_partition_stats.[index_id]' SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0' - IF NOT EXISTS(SELECT * FROM @ActionsPreferred) SET @CurrentCommand01 = @CurrentCommand01 + ' AND stats.stats_id IS NOT NULL' END IF (EXISTS(SELECT * FROM @ActionsPreferred) AND @UpdateStatistics = 'COLUMNS') OR @UpdateStatistics = 'ALL' SET @CurrentCommand01 = @CurrentCommand01 + ' UNION ' @@ -1431,7 +1425,7 @@ BEGIN IF @CurrentIndexID IS NOT NULL AND @CurrentOnReadOnlyFileGroup = 0 AND EXISTS(SELECT * FROM @ActionsPreferred) - AND (EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) OR @PageCountLevel > 0) + AND (EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) OR @MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) BEGIN SET @CurrentCommand12 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand12 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' @@ -1493,7 +1487,8 @@ BEGIN -- Decide action IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) - AND (@CurrentPageCount >= @PageCountLevel OR @PageCountLevel = 0) + AND (@CurrentPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) + AND (@CurrentPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL) BEGIN IF EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) BEGIN diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 5689c073..35edd689 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 30 May, 2018. +Last updated 1 June, 2018. Ola Hallengren https://ola.hallengren.com @@ -1512,32 +1512,32 @@ BEGIN SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1909,6 +1909,7 @@ BEGIN IF @Cluster IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}','') IF @CurrentAvailabilityGroup IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}','') IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}','') + IF @Description IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}','') WHILE (@Updated = 1 OR @Updated IS NULL) BEGIN @@ -2057,6 +2058,7 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupType}',@CurrentBackupType) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Partial}','PARTIAL') SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{CopyOnly}','COPY_ONLY') + IF @Description IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) @@ -2086,6 +2088,7 @@ BEGIN IF @Cluster IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}','') IF @CurrentAvailabilityGroup IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{AvailabilityGroupName}','') IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}','') + IF @Description IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}','') IF @NumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileNumber}','') WHILE (@Updated = 1 OR @Updated IS NULL) @@ -2189,6 +2192,7 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{BackupType}',@CurrentBackupType) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Partial}','PARTIAL') SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{CopyOnly}','COPY_ONLY') + IF @Description IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) @@ -3034,8 +3038,6 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @AmazonRDS bit - DECLARE @Cluster nvarchar(max) - DECLARE @CurrentDBID int DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -3800,16 +3802,6 @@ BEGIN SET @Error = @@ERROR END - ---------------------------------------------------------------------------------------------------- - --// Check Availability Group cluster name //-- - ---------------------------------------------------------------------------------------------------- - - IF @Version >= 11 AND SERVERPROPERTY('EngineEdition') <> 5 - BEGIN - SELECT @Cluster = cluster_name - FROM sys.dm_hadr_cluster - END - ---------------------------------------------------------------------------------------------------- --// Execute commands //-- ---------------------------------------------------------------------------------------------------- @@ -3843,7 +3835,7 @@ BEGIN END END - IF @Version >= 11 AND @Cluster IS NOT NULL + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @CurrentAvailabilityGroup = availability_groups.name, @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc @@ -4338,7 +4330,8 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @FragmentationHigh nvarchar(max) = 'INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', @FragmentationLevel1 int = 5, @FragmentationLevel2 int = 30, -@PageCountLevel int = 1000, +@MinNumberOfPages int = 1000, +@MaxNumberOfPages int = NULL, @SortInTempdb nvarchar(max) = 'N', @MaxDOP int = NULL, @FillFactor int = NULL, @@ -4388,8 +4381,6 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @AmazonRDS bit - DECLARE @Cluster nvarchar(max) - DECLARE @CurrentDBID int DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -4565,7 +4556,8 @@ BEGIN SET @Parameters = @Parameters + ', @FragmentationHigh = ' + ISNULL('''' + REPLACE(@FragmentationHigh,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @FragmentationLevel1 = ' + ISNULL(CAST(@FragmentationLevel1 AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @FragmentationLevel2 = ' + ISNULL(CAST(@FragmentationLevel2 AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @PageCountLevel = ' + ISNULL(CAST(@PageCountLevel AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @MinNumberOfPages = ' + ISNULL(CAST(@MinNumberOfPages AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @MaxNumberOfPages = ' + ISNULL(CAST(@MaxNumberOfPages AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @SortInTempdb = ' + ISNULL('''' + REPLACE(@SortInTempdb,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar),'NULL') @@ -5051,9 +5043,16 @@ BEGIN SET @Error = @@ERROR END - IF @PageCountLevel < 0 OR @PageCountLevel IS NULL + IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @PageCountLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MinNumberOfPages is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @MaxNumberOfPages < 0 + BEGIN + SET @ErrorMessage = 'The value for the parameter @MaxNumberOfPages is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END @@ -5252,16 +5251,6 @@ BEGIN SET @Error = @@ERROR END - ---------------------------------------------------------------------------------------------------- - --// Check Availability Group cluster name //-- - ---------------------------------------------------------------------------------------------------- - - IF @Version >= 11 AND SERVERPROPERTY('EngineEdition') <> 5 - BEGIN - SELECT @Cluster = cluster_name - FROM sys.dm_hadr_cluster - END - ---------------------------------------------------------------------------------------------------- --// Execute commands //-- ---------------------------------------------------------------------------------------------------- @@ -5295,7 +5284,7 @@ BEGIN END END - IF @Version >= 11 AND @Cluster IS NOT NULL + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @CurrentAvailabilityGroup = availability_groups.name, @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc @@ -5378,10 +5367,7 @@ BEGIN IF @PartitionLevel = 'N' SET @CurrentCommand01 = @CurrentCommand01 + ', NULL AS PartitionID, NULL AS PartitionNumber, NULL AS PartitionCount' SET @CurrentCommand01 = @CurrentCommand01 + ', 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.[object_id] = tables.[object_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id LEFT OUTER JOIN (SELECT partitions.[object_id], partitions.index_id, COUNT(DISTINCT partitions.partition_number) AS partition_count FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions GROUP BY partitions.[object_id], partitions.index_id) IndexPartitions ON partitions.[object_id] = IndexPartitions.[object_id] AND partitions.[index_id] = IndexPartitions.[index_id]' - IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_partition_stats dm_db_partition_stats ON indexes.[object_id] = dm_db_partition_stats.[object_id] AND indexes.[index_id] = dm_db_partition_stats.[index_id] AND partitions.partition_id = dm_db_partition_stats.partition_id' - IF @PartitionLevel = 'N' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN (SELECT dm_db_partition_stats.[object_id], dm_db_partition_stats.[index_id], SUM(dm_db_partition_stats.in_row_data_page_count) AS in_row_data_page_count FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_partition_stats dm_db_partition_stats GROUP BY dm_db_partition_stats.[object_id], dm_db_partition_stats.[index_id]) dm_db_partition_stats ON indexes.[object_id] = dm_db_partition_stats.[object_id] AND indexes.[index_id] = dm_db_partition_stats.[index_id]' SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0' - IF NOT EXISTS(SELECT * FROM @ActionsPreferred) SET @CurrentCommand01 = @CurrentCommand01 + ' AND stats.stats_id IS NOT NULL' END IF (EXISTS(SELECT * FROM @ActionsPreferred) AND @UpdateStatistics = 'COLUMNS') OR @UpdateStatistics = 'ALL' SET @CurrentCommand01 = @CurrentCommand01 + ' UNION ' @@ -5754,7 +5740,7 @@ BEGIN IF @CurrentIndexID IS NOT NULL AND @CurrentOnReadOnlyFileGroup = 0 AND EXISTS(SELECT * FROM @ActionsPreferred) - AND (EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) OR @PageCountLevel > 0) + AND (EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) OR @MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) BEGIN SET @CurrentCommand12 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand12 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' @@ -5816,7 +5802,8 @@ BEGIN -- Decide action IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) - AND (@CurrentPageCount >= @PageCountLevel OR @PageCountLevel = 0) + AND (@CurrentPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) + AND (@CurrentPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL) BEGIN IF EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) BEGIN @@ -6247,7 +6234,7 @@ BEGIN SELECT @LogDirectory = LEFT(CAST(SERVERPROPERTY('ErrorLogFileName') AS nvarchar(max)),LEN(CAST(SERVERPROPERTY('ErrorLogFileName') AS nvarchar(max))) - CHARINDEX('\',REVERSE(CAST(SERVERPROPERTY('ErrorLogFileName') AS nvarchar(max))))) END - IF @OutputFileDirectory IS NULL AND RIGHT(@OutputFileDirectory,1) = @DirectorySeparator + IF @OutputFileDirectory IS NOT NULL AND RIGHT(@OutputFileDirectory,1) = @DirectorySeparator BEGIN SET @OutputFileDirectory = LEFT(@OutputFileDirectory, LEN(@OutputFileDirectory) - 1) END From 77b058531421a58715349f8e09c25c065df9ad7f Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 2 Jun 2018 12:24:13 +0200 Subject: [PATCH 030/188] Add files via upload --- DatabaseBackup.sql | 26 ++++++++++++++------------ MaintenanceSolution.sql | 28 +++++++++++++++------------- 2 files changed, 29 insertions(+), 25 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 779d8f5a..ecdb70d3 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -1620,6 +1620,7 @@ BEGIN IF @Cluster IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}','') IF @CurrentAvailabilityGroup IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}','') IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}','') + IF @@SERVICENAME IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}','') IF @Description IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}','') WHILE (@Updated = 1 OR @Updated IS NULL) @@ -1760,16 +1761,16 @@ BEGIN -- Directory structure - replace tokens with real values SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}',@DirectorySeparator) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}',CAST(SERVERPROPERTY('MachineName') AS nvarchar(max))) - IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}',CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max))) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}',@@SERVICENAME) - IF @Cluster IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}',@Cluster) - IF @CurrentAvailabilityGroup IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}',@CurrentAvailabilityGroup) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}',CASE WHEN SERVERPROPERTY('EngineEdition') = 8 THEN LEFT(CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) - 1) ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)) END) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}',ISNULL(CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max)),'')) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}',ISNULL(@@SERVICENAME,'')) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}',ISNULL(@Cluster,'')) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}',ISNULL(@CurrentAvailabilityGroup,'')) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DatabaseName}',@CurrentDatabaseNameFS) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupType}',@CurrentBackupType) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Partial}','PARTIAL') SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{CopyOnly}','COPY_ONLY') - IF @Description IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ISNULL(@Description,''),'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) @@ -1799,6 +1800,7 @@ BEGIN IF @Cluster IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}','') IF @CurrentAvailabilityGroup IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{AvailabilityGroupName}','') IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}','') + IF @@SERVICENAME IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}','') IF @Description IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}','') IF @NumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileNumber}','') @@ -1895,15 +1897,15 @@ BEGIN END -- File name - replace tokens with real values - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServerName}',CAST(SERVERPROPERTY('MachineName') AS nvarchar(max))) - IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}',CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max))) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}',@@SERVICENAME) - IF @Cluster IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}',@Cluster) - IF @CurrentAvailabilityGroup IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{AvailabilityGroupName}',@CurrentAvailabilityGroup) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServerName}',CASE WHEN SERVERPROPERTY('EngineEdition') = 8 THEN LEFT(CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) - 1) ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)) END) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}',ISNULL(CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max)),'')) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}',ISNULL(@@SERVICENAME,'')) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}',ISNULL(@Cluster,'')) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{AvailabilityGroupName}',ISNULL(@CurrentAvailabilityGroup,'')) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{BackupType}',@CurrentBackupType) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Partial}','PARTIAL') SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{CopyOnly}','COPY_ONLY') - IF @Description IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ISNULL(@Description,''),'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 35edd689..57ce366f 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ The solution is free: https://ola.hallengren.com/license.html You can contact me by e-mail at ola@hallengren.com. -Last updated 1 June, 2018. +Last updated 2 June, 2018. Ola Hallengren https://ola.hallengren.com @@ -1909,6 +1909,7 @@ BEGIN IF @Cluster IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}','') IF @CurrentAvailabilityGroup IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}','') IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}','') + IF @@SERVICENAME IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}','') IF @Description IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}','') WHILE (@Updated = 1 OR @Updated IS NULL) @@ -2049,16 +2050,16 @@ BEGIN -- Directory structure - replace tokens with real values SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}',@DirectorySeparator) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}',CAST(SERVERPROPERTY('MachineName') AS nvarchar(max))) - IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}',CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max))) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}',@@SERVICENAME) - IF @Cluster IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}',@Cluster) - IF @CurrentAvailabilityGroup IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}',@CurrentAvailabilityGroup) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}',CASE WHEN SERVERPROPERTY('EngineEdition') = 8 THEN LEFT(CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) - 1) ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)) END) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}',ISNULL(CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max)),'')) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}',ISNULL(@@SERVICENAME,'')) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}',ISNULL(@Cluster,'')) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}',ISNULL(@CurrentAvailabilityGroup,'')) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DatabaseName}',@CurrentDatabaseNameFS) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupType}',@CurrentBackupType) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Partial}','PARTIAL') SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{CopyOnly}','COPY_ONLY') - IF @Description IS NOT NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ISNULL(@Description,''),'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) @@ -2088,6 +2089,7 @@ BEGIN IF @Cluster IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}','') IF @CurrentAvailabilityGroup IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{AvailabilityGroupName}','') IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}','') + IF @@SERVICENAME IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}','') IF @Description IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}','') IF @NumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileNumber}','') @@ -2184,15 +2186,15 @@ BEGIN END -- File name - replace tokens with real values - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServerName}',CAST(SERVERPROPERTY('MachineName') AS nvarchar(max))) - IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}',CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max))) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}',@@SERVICENAME) - IF @Cluster IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}',@Cluster) - IF @CurrentAvailabilityGroup IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{AvailabilityGroupName}',@CurrentAvailabilityGroup) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServerName}',CASE WHEN SERVERPROPERTY('EngineEdition') = 8 THEN LEFT(CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) - 1) ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)) END) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}',ISNULL(CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max)),'')) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}',ISNULL(@@SERVICENAME,'')) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}',ISNULL(@Cluster,'')) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{AvailabilityGroupName}',ISNULL(@CurrentAvailabilityGroup,'')) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{BackupType}',@CurrentBackupType) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Partial}','PARTIAL') SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{CopyOnly}','COPY_ONLY') - IF @Description IS NOT NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ISNULL(@Description,''),'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) From e544f3dac29d9ade718f31cf4ef8959333796366 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 3 Jun 2018 16:10:07 +0200 Subject: [PATCH 031/188] Add files via upload --- CommandExecute.sql | 4 +- DatabaseBackup.sql | 4 +- DatabaseIntegrityCheck.sql | 42 +-- IndexOptimize.sql | 519 +++++++++++++++++---------------- MaintenanceSolution.sql | 571 +++++++++++++++++++------------------ 5 files changed, 574 insertions(+), 566 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index de98f9ee..947e859b 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -30,7 +30,9 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- + --// License: https://ola.hallengren.com/license.html //-- + --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index ecdb70d3..c128664c 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -66,7 +66,9 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- + --// License: https://ola.hallengren.com/license.html //-- + --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 1cdec89b..05cc27f7 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -30,7 +30,9 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- + --// License: https://ola.hallengren.com/license.html //-- + --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -983,16 +985,16 @@ BEGIN ON @CurrentDatabaseName LIKE REPLACE(SelectedFileGroups.DatabaseName,'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(SelectedFileGroups.FileGroupName,'_','[_]') WHERE SelectedFileGroups.Selected = 1 GROUP BY tmpFileGroups.FileGroupName) SelectedFileGroups2 - ON tmpFileGroups.FileGroupName = SelectedFileGroups2.FileGroupName; + ON tmpFileGroups.FileGroupName = SelectedFileGroups2.FileGroupName + END; - WITH tmpFileGroups AS ( - SELECT FileGroupName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, FileGroupName ASC) AS RowNumber - FROM @tmpFileGroups tmpFileGroups - WHERE Selected = 1 - ) - UPDATE tmpFileGroups - SET [Order] = RowNumber - END + WITH tmpFileGroups AS ( + SELECT FileGroupName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, FileGroupName ASC) AS RowNumber + FROM @tmpFileGroups tmpFileGroups + WHERE Selected = 1 + ) + UPDATE tmpFileGroups + SET [Order] = RowNumber SET @ErrorMessage = '' SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + '.' + QUOTENAME(FileGroupName) + ', ' @@ -1138,16 +1140,16 @@ BEGIN ON @CurrentDatabaseName LIKE REPLACE(SelectedObjects.DatabaseName,'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(SelectedObjects.SchemaName,'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(SelectedObjects.ObjectName,'_','[_]') WHERE SelectedObjects.Selected = 1 GROUP BY tmpObjects.SchemaName, tmpObjects.ObjectName) SelectedObjects2 - ON tmpObjects.SchemaName = SelectedObjects2.SchemaName AND tmpObjects.ObjectName = SelectedObjects2.ObjectName; - - WITH tmpObjects AS ( - SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, SchemaName ASC, ObjectName ASC) AS RowNumber - FROM @tmpObjects tmpObjects - WHERE Selected = 1 - ) - UPDATE tmpObjects - SET [Order] = RowNumber - END + ON tmpObjects.SchemaName = SelectedObjects2.SchemaName AND tmpObjects.ObjectName = SelectedObjects2.ObjectName + END; + + WITH tmpObjects AS ( + SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, SchemaName ASC, ObjectName ASC) AS RowNumber + FROM @tmpObjects tmpObjects + WHERE Selected = 1 + ) + UPDATE tmpObjects + SET [Order] = RowNumber SET @ErrorMessage = '' SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + ', ' diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 50bdbcc7..36c860cd 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -43,7 +43,9 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- + --// License: https://ola.hallengren.com/license.html //-- + --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -82,19 +84,12 @@ BEGIN DECLARE @CurrentCommand05 nvarchar(max) DECLARE @CurrentCommand06 nvarchar(max) DECLARE @CurrentCommand07 nvarchar(max) - DECLARE @CurrentCommand08 nvarchar(max) - DECLARE @CurrentCommand09 nvarchar(max) - DECLARE @CurrentCommand10 nvarchar(max) - DECLARE @CurrentCommand11 nvarchar(max) - DECLARE @CurrentCommand12 nvarchar(max) - DECLARE @CurrentCommand13 nvarchar(max) - DECLARE @CurrentCommand14 nvarchar(max) - DECLARE @CurrentCommandOutput13 int - DECLARE @CurrentCommandOutput14 int + DECLARE @CurrentCommandOutput06 int + DECLARE @CurrentCommandOutput07 int - DECLARE @CurrentCommandType13 nvarchar(max) - DECLARE @CurrentCommandType14 nvarchar(max) + DECLARE @CurrentCommandType06 nvarchar(max) + DECLARE @CurrentCommandType07 nvarchar(max) DECLARE @CurrentIxID int DECLARE @CurrentSchemaID int @@ -120,7 +115,9 @@ BEGIN DECLARE @CurrentIsColumnStore bit DECLARE @CurrentAllowPageLocks bit DECLARE @CurrentNoRecompute bit - DECLARE @CurrentStatisticsModified bit + DECLARE @CurrentIsIncremental bit + DECLARE @CurrentRowCount int + DECLARE @CurrentModificationCounter int DECLARE @CurrentOnReadOnlyFileGroup bit DECLARE @CurrentFragmentationLevel float DECLARE @CurrentPageCount bigint @@ -162,8 +159,16 @@ BEGIN IndexID int, IndexName nvarchar(max), IndexType int, + AllowPageLocks bit, + IsImageText bit, + IsNewLOB bit, + IsFileStream bit, + IsColumnStore bit, + OnReadOnlyFileGroup bit, StatisticsID int, StatisticsName nvarchar(max), + [NoRecompute] bit, + IsIncremental bit, PartitionID bigint, PartitionNumber int, PartitionCount int, @@ -202,6 +207,12 @@ BEGIN DECLARE @CurrentActionsAllowed TABLE ([Action] nvarchar(max)) + + DECLARE @CurrentAlterIndexWithClauseArguments TABLE (ID int IDENTITY, + Argument nvarchar(max)) + + DECLARE @CurrentAlterIndexWithClause nvarchar(max) + DECLARE @CurrentUpdateStatisticsWithClauseArguments TABLE (ID int IDENTITY, Argument nvarchar(max)) @@ -1043,25 +1054,108 @@ BEGIN -- Select indexes in the current database IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, StatisticsID, StatisticsName, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed FROM (' + SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + 'USE ' + QUOTENAME(@CurrentDatabaseName) + ';' + + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, OnReadOnlyFileGroup, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + + ' FROM (' IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') BEGIN - SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized, indexes.index_id AS IndexID, indexes.[name] AS IndexName, indexes.[type] AS IndexType, stats.stats_id AS StatisticsID, stats.name AS StatisticsName' - IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', partitions.partition_id AS PartitionID, partitions.partition_number AS PartitionNumber, IndexPartitions.partition_count AS PartitionCount' - IF @PartitionLevel = 'N' SET @CurrentCommand01 = @CurrentCommand01 + ', NULL AS PartitionID, NULL AS PartitionNumber, NULL AS PartitionCount' - SET @CurrentCommand01 = @CurrentCommand01 + ', 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.[object_id] = tables.[object_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' - IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id LEFT OUTER JOIN (SELECT partitions.[object_id], partitions.index_id, COUNT(DISTINCT partitions.partition_number) AS partition_count FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions GROUP BY partitions.[object_id], partitions.index_id) IndexPartitions ON partitions.[object_id] = IndexPartitions.[object_id] AND partitions.[index_id] = IndexPartitions.[index_id]' - SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0' + SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID' + + ', schemas.[name] AS SchemaName' + + ', objects.[object_id] AS ObjectID' + + ', objects.[name] AS ObjectName' + + ', RTRIM(objects.[type]) AS ObjectType' + + ', ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized' + + ', indexes.index_id AS IndexID' + + ', indexes.[name] AS IndexName' + + ', indexes.[type] AS IndexType' + + ', indexes.allow_page_locks AS AllowPageLocks' + + + ', CASE WHEN indexes.[type] = 1 AND EXISTS(SELECT * FROM sys.columns columns INNER JOIN sys.types types ON columns.system_type_id = types.user_type_id WHERE columns.[object_id] = objects.object_id AND types.name IN(''image'',''text'',''ntext'')) THEN 1 ELSE 0 END AS IsImageText' + + + ', CASE WHEN indexes.[type] = 1 AND EXISTS(SELECT * FROM sys.columns columns INNER JOIN sys.types types ON columns.system_type_id = types.user_type_id OR (columns.user_type_id = types.user_type_id AND types.is_assembly_type = 1) WHERE columns.[object_id] = objects.object_id AND (types.name IN(''xml'') OR (types.name IN(''varchar'',''nvarchar'',''varbinary'') AND columns.max_length = -1) OR (types.is_assembly_type = 1 AND columns.max_length = -1))) THEN 1' + + ' WHEN indexes.[type] = 2 AND EXISTS(SELECT * FROM sys.index_columns index_columns INNER JOIN sys.columns columns ON index_columns.[object_id] = columns.[object_id] AND index_columns.column_id = columns.column_id INNER JOIN sys.types types ON columns.system_type_id = types.user_type_id OR (columns.user_type_id = types.user_type_id AND types.is_assembly_type = 1) WHERE index_columns.[object_id] = objects.object_id AND index_columns.index_id = indexes.index_id AND (types.[name] IN(''xml'') OR (types.[name] IN(''varchar'',''nvarchar'',''varbinary'') AND columns.max_length = -1) OR (types.is_assembly_type = 1 AND columns.max_length = -1))) THEN 1 ELSE 0 END AS IsNewLOB' + + + ', CASE WHEN indexes.[type] = 1 AND EXISTS(SELECT * FROM sys.columns columns WHERE columns.[object_id] = objects.object_id AND columns.is_filestream = 1) THEN 1 ELSE 0 END AS IsFileStream' + + + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] IN(5,6)) THEN 1 ELSE 0 END AS IsColumnStore' + + + ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON indexes.data_space_id = destination_data_spaces.partition_scheme_id INNER JOIN sys.filegroups filegroups ON destination_data_spaces.data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND indexes2.[object_id] = indexes.[object_id] AND indexes2.[index_id] = indexes.index_id' + CASE WHEN @PartitionLevel = 'Y' THEN ' AND destination_data_spaces.destination_id = partitions.partition_number' ELSE '' END + ') THEN 1' + + ' WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.filegroups filegroups ON indexes.data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND indexes.[object_id] = indexes2.[object_id] AND indexes.[index_id] = indexes2.index_id) THEN 1' + + ' WHEN indexes.[type] = 1 AND EXISTS (SELECT * FROM sys.tables tables INNER JOIN sys.filegroups filegroups ON tables.lob_data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND tables.[object_id] = objects.[object_id]) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' + + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE 'NULL' END + ' AS IsIncremental' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_id AS PartitionID' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionID' END + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber, NULL AS PartitionCount' END + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'IndexPartitions.partition_count AS PartitionCount' WHEN @PartitionLevel = 'N' THEN ', NULL AS PartitionCount' END + + ', 0 AS [Order]' + + ', 0 AS Selected' + + ', 0 AS Completed' + + ' FROM sys.indexes indexes' + + ' INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id]' + + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' + + ' LEFT OUTER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + + ' LEFT OUTER JOIN sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' + IF @PartitionLevel = 'Y' + BEGIN + SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' + + ' LEFT OUTER JOIN (SELECT partitions.[object_id], partitions.index_id, COUNT(DISTINCT partitions.partition_number) AS partition_count FROM sys.partitions partitions GROUP BY partitions.[object_id], partitions.index_id) IndexPartitions ON partitions.[object_id] = IndexPartitions.[object_id] AND partitions.[index_id] = IndexPartitions.[index_id]' + END + + SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + ' AND indexes.[type] IN(1,2,3,4,5,6,7)' + + ' AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0' END - IF (EXISTS(SELECT * FROM @ActionsPreferred) AND @UpdateStatistics = 'COLUMNS') OR @UpdateStatistics = 'ALL' SET @CurrentCommand01 = @CurrentCommand01 + ' UNION ' + IF (EXISTS(SELECT * FROM @ActionsPreferred) AND @UpdateStatistics = 'COLUMNS') OR @UpdateStatistics = 'ALL' + BEGIN + SET @CurrentCommand01 = @CurrentCommand01 + ' UNION ' + END - IF @UpdateStatistics IN('ALL','COLUMNS') SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized, NULL AS IndexID, NULL AS IndexName, NULL AS IndexType, stats.stats_id AS StatisticsID, stats.name AS StatisticsName, NULL AS PartitionID, NULL AS PartitionNumber, NULL AS PartitionCount, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.[object_id] = tables.[object_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND NOT EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id)' + IF @UpdateStatistics IN('ALL','COLUMNS') + BEGIN + SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID' + + ', schemas.[name] AS SchemaName' + + ', objects.[object_id] AS ObjectID' + + ', objects.[name] AS ObjectName' + + ', RTRIM(objects.[type]) AS ObjectType' + + ', ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized' + + ', NULL AS IndexID, NULL AS IndexName' + + ', NULL AS IndexType' + + ', NULL AS AllowPageLocks' + + ', NULL AS IsImageText' + + ', NULL AS IsNewLOB' + + ', NULL AS IsFileStream' + + ', NULL AS IsColumnStore' + + ', NULL AS OnReadOnlyFileGroup' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE 'NULL' END + ' AS IsIncremental' + + ', NULL AS PartitionID' + + ', NULL AS partition_number' + + ', NULL AS PartitionCount' + + ', 0 AS [Order]' + + ', 0 AS Selected' + + ', 0 AS Completed' + + ' FROM sys.stats stats' + + ' INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id]' + + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' + + ' LEFT OUTER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + + SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id)' + END SET @CurrentCommand01 = @CurrentCommand01 + ') IndexesStatistics' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, StatisticsID, StatisticsName, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, OnReadOnlyFileGroup, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) EXECUTE sp_executesql @statement = @CurrentCommand01 SET @Error = @@ERROR IF @Error <> 0 @@ -1104,16 +1198,16 @@ BEGIN ON tmpIndexesStatistics.SchemaName = SelectedIndexes2.SchemaName AND tmpIndexesStatistics.ObjectName = SelectedIndexes2.ObjectName AND (tmpIndexesStatistics.IndexName = SelectedIndexes2.IndexName OR tmpIndexesStatistics.IndexName IS NULL) - AND (tmpIndexesStatistics.StatisticsName = SelectedIndexes2.StatisticsName OR tmpIndexesStatistics.StatisticsName IS NULL); + AND (tmpIndexesStatistics.StatisticsName = SelectedIndexes2.StatisticsName OR tmpIndexesStatistics.StatisticsName IS NULL) + END; - WITH tmpIndexesStatistics AS ( - SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, SchemaName ASC, ObjectName ASC, CASE WHEN IndexType IS NULL THEN 1 ELSE 0 END ASC, IndexType ASC, IndexName ASC, StatisticsName ASC, PartitionNumber ASC) AS RowNumber - FROM @tmpIndexesStatistics tmpIndexesStatistics - WHERE Selected = 1 - ) - UPDATE tmpIndexesStatistics - SET [Order] = RowNumber - END + WITH tmpIndexesStatistics AS ( + SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, SchemaName ASC, ObjectName ASC, CASE WHEN IndexType IS NULL THEN 1 ELSE 0 END ASC, IndexType ASC, IndexName ASC, StatisticsName ASC, PartitionNumber ASC) AS RowNumber + FROM @tmpIndexesStatistics tmpIndexesStatistics + WHERE Selected = 1 + ) + UPDATE tmpIndexesStatistics + SET [Order] = RowNumber SET @ErrorMessage = '' SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + ', ' @@ -1147,7 +1241,6 @@ BEGIN WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SELECT TOP 1 @CurrentIxID = ID, @CurrentSchemaID = SchemaID, @CurrentSchemaName = SchemaName, @@ -1158,8 +1251,16 @@ BEGIN @CurrentIndexID = IndexID, @CurrentIndexName = IndexName, @CurrentIndexType = IndexType, + @CurrentAllowPageLocks = AllowPageLocks, + @CurrentIsImageText = IsImageText, + @CurrentIsNewLOB = IsNewLOB, + @CurrentIsFileStream = IsFileStream, + @CurrentIsColumnStore = IsColumnStore, + @CurrentOnReadOnlyFileGroup = OnReadOnlyFileGroup, @CurrentStatisticsID = StatisticsID, @CurrentStatisticsName = StatisticsName, + @CurrentNoRecompute = [NoRecompute], + @CurrentIsIncremental = IsIncremental, @CurrentPartitionID = PartitionID, @CurrentPartitionNumber = PartitionNumber, @CurrentPartitionCount = PartitionCount @@ -1180,9 +1281,12 @@ BEGIN IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) BEGIN SET @CurrentCommand02 = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand02 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - IF @CurrentIsPartition = 0 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' - IF @CurrentIsPartition = 1 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' + SET @CurrentCommand02 = @CurrentCommand02 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' + + IF @CurrentIsPartition = 0 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' + IF @CurrentIsPartition = 1 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' EXECUTE sp_executesql @statement = @CurrentCommand02, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT SET @Error = @@ERROR @@ -1205,8 +1309,11 @@ BEGIN IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL BEGIN SET @CurrentCommand03 = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' + SET @CurrentCommand03 = @CurrentCommand03 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' + + SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM sys.stats stats INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' EXECUTE sp_executesql @statement = @CurrentCommand03, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT SET @Error = @@ERROR @@ -1225,162 +1332,32 @@ BEGIN IF @CurrentStatisticsExists = 0 GOTO NoAction END - -- Is one of the columns in the index an image, text or ntext data type? - IF @CurrentIndexID IS NOT NULL AND @CurrentIndexType = 1 AND EXISTS(SELECT * FROM @ActionsPreferred) + -- Has the data in the statistics been modified since the statistics was last updated? + IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL AND @OnlyModifiedStatistics = 'Y' BEGIN SET @CurrentCommand04 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand04 = @CurrentCommand04 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.columns columns INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.types types ON columns.system_type_id = types.user_type_id WHERE columns.[object_id] = @ParamObjectID AND types.name IN(''image'',''text'',''ntext'')) BEGIN SET @ParamIsImageText = 1 END' - - EXECUTE sp_executesql @statement = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamIndexID int, @ParamIsImageText bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamIsImageText = @CurrentIsImageText OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentIsImageText IS NULL SET @CurrentIsImageText = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index contains any image, text, or ntext data types.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO NoAction - END - END - - -- Is one of the columns in the index an xml, varchar(max), nvarchar(max), varbinary(max) or large CLR data type? - IF @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN(1,2) AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentCommand05 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand05 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - IF @CurrentIndexType = 1 SET @CurrentCommand05 = @CurrentCommand05 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.columns columns INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.types types ON columns.system_type_id = types.user_type_id OR (columns.user_type_id = types.user_type_id AND types.is_assembly_type = 1) WHERE columns.[object_id] = @ParamObjectID AND (types.name IN(''xml'') OR (types.name IN(''varchar'',''nvarchar'',''varbinary'') AND columns.max_length = -1) OR (types.is_assembly_type = 1 AND columns.max_length = -1))) BEGIN SET @ParamIsNewLOB = 1 END' - IF @CurrentIndexType = 2 SET @CurrentCommand05 = @CurrentCommand05 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.index_columns index_columns INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.columns columns ON index_columns.[object_id] = columns.[object_id] AND index_columns.column_id = columns.column_id INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.types types ON columns.system_type_id = types.user_type_id OR (columns.user_type_id = types.user_type_id AND types.is_assembly_type = 1) WHERE index_columns.[object_id] = @ParamObjectID AND index_columns.index_id = @ParamIndexID AND (types.[name] IN(''xml'') OR (types.[name] IN(''varchar'',''nvarchar'',''varbinary'') AND columns.max_length = -1) OR (types.is_assembly_type = 1 AND columns.max_length = -1))) BEGIN SET @ParamIsNewLOB = 1 END' - - EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamObjectID int, @ParamIndexID int, @ParamIsNewLOB bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamIsNewLOB = @CurrentIsNewLOB OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentIsNewLOB IS NULL SET @CurrentIsNewLOB = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index contains any xml, varchar(max), nvarchar(max), varbinary(max), or large CLR data types.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO NoAction - END - END - - -- Is one of the columns in the index a file stream column? - IF @CurrentIndexID IS NOT NULL AND @CurrentIndexType = 1 AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentCommand06 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand06 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand06 = @CurrentCommand06 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.columns columns WHERE columns.[object_id] = @ParamObjectID AND columns.is_filestream = 1) BEGIN SET @ParamIsFileStream = 1 END' - - EXECUTE sp_executesql @statement = @CurrentCommand06, @params = N'@ParamObjectID int, @ParamIndexID int, @ParamIsFileStream bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamIsFileStream = @CurrentIsFileStream OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentIsFileStream IS NULL SET @CurrentIsFileStream = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index contains any file stream columns.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO NoAction - END - END - - -- Is there a columnstore index on the table? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) AND @Version >= 11 - BEGIN - SET @CurrentCommand07 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand07 = @CurrentCommand07 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.[object_id] = @ParamObjectID AND [type] IN(5,6)) BEGIN SET @ParamIsColumnStore = 1 END' - - EXECUTE sp_executesql @statement = @CurrentCommand07, @params = N'@ParamObjectID int, @ParamIsColumnStore bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamIsColumnStore = @CurrentIsColumnStore OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentIsColumnStore IS NULL SET @CurrentIsColumnStore = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if there is a columnstore index on the table.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO NoAction - END - END - -- Is Allow_Page_Locks set to On? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentCommand08 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand08 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand08 = @CurrentCommand08 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.[object_id] = @ParamObjectID AND indexes.[index_id] = @ParamIndexID AND indexes.[allow_page_locks] = 1) BEGIN SET @ParamAllowPageLocks = 1 END' - - EXECUTE sp_executesql @statement = @CurrentCommand08, @params = N'@ParamObjectID int, @ParamIndexID int, @ParamAllowPageLocks bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamAllowPageLocks = @CurrentAllowPageLocks OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentAllowPageLocks IS NULL SET @CurrentAllowPageLocks = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if page locking is enabled on the index.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO NoAction - END - END - - -- Is No_Recompute set to On? - IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL - BEGIN - SET @CurrentCommand09 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand09 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand09 = @CurrentCommand09 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats WHERE stats.[object_id] = @ParamObjectID AND stats.[stats_id] = @ParamStatisticsID AND stats.[no_recompute] = 1) BEGIN SET @ParamNoRecompute = 1 END' + IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand04 = @CurrentCommand04 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' - EXECUTE sp_executesql @statement = @CurrentCommand09, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamNoRecompute bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamNoRecompute = @CurrentNoRecompute OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentNoRecompute IS NULL SET @CurrentNoRecompute = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if automatic statistics update is enabled.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 + IF @CurrentIsIncremental = 1 AND ((@Version >= 12.05 AND @Version < 13) OR @Version >= 13.04422) AND 0 = 1 BEGIN - SET @ReturnCode = @Error - GOTO NoAction + SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' END - END - - -- Has the data in the statistics been modified since the statistics was last updated? - IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL AND @OnlyModifiedStatistics = 'Y' - BEGIN - SET @CurrentCommand10 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand10 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + ELSE IF (@Version >= 10.504000 AND @Version < 11) OR @Version >= 11.03000 BEGIN - SET @CurrentCommand10 = @CurrentCommand10 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; IF EXISTS(SELECT * FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE modification_counter > 0) BEGIN SET @ParamStatisticsModified = 1 END' + SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' END ELSE BEGIN - SET @CurrentCommand10 = @CurrentCommand10 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID AND sysindexes.[rowmodctr] <> 0) BEGIN SET @ParamStatisticsModified = 1 END' + SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = rowcnt, @ParamModificationCounter = rowmodctr FROM sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID' END - EXECUTE sp_executesql @statement = @CurrentCommand10, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamStatisticsModified bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsModified = @CurrentStatisticsModified OUTPUT + EXECUTE sp_executesql @statement = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount int OUTPUT, @ParamModificationCounter int OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT SET @Error = @@ERROR - IF @Error = 0 AND @CurrentStatisticsModified IS NULL SET @CurrentStatisticsModified = 0 + IF @Error = 0 AND @CurrentRowCount IS NULL SET @CurrentRowCount = 0 + IF @Error = 0 AND @CurrentModificationCounter IS NULL SET @CurrentModificationCounter = 0 IF @Error = 1222 BEGIN SET @ErrorMessage = 'The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if any rows has been modified since the most recent statistics update.' + CHAR(13) + CHAR(10) + ' ' @@ -1394,44 +1371,19 @@ BEGIN END END - -- Is the index on a read-only filegroup? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentCommand11 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand11 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand11 = @CurrentCommand11 + 'IF EXISTS(SELECT * FROM (SELECT filegroups.data_space_id FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.destination_data_spaces destination_data_spaces ON indexes.data_space_id = destination_data_spaces.partition_scheme_id INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups ON destination_data_spaces.data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND indexes.[object_id] = @ParamObjectID AND indexes.[index_id] = @ParamIndexID' - IF @CurrentIsPartition = 1 SET @CurrentCommand11 = @CurrentCommand11 + ' AND destination_data_spaces.destination_id = @ParamPartitionNumber' - SET @CurrentCommand11 = @CurrentCommand11 + ' UNION SELECT filegroups.data_space_id FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups ON indexes.data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND indexes.[object_id] = @ParamObjectID AND indexes.[index_id] = @ParamIndexID' - IF @CurrentIndexType = 1 SET @CurrentCommand11 = @CurrentCommand11 + ' UNION SELECT filegroups.data_space_id FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups ON tables.lob_data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND tables.[object_id] = @ParamObjectID' - SET @CurrentCommand11 = @CurrentCommand11 + ') ReadOnlyFileGroups) BEGIN SET @ParamOnReadOnlyFileGroup = 1 END' - - EXECUTE sp_executesql @statement = @CurrentCommand11, @params = N'@ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamOnReadOnlyFileGroup bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamOnReadOnlyFileGroup = @CurrentOnReadOnlyFileGroup OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentOnReadOnlyFileGroup IS NULL SET @CurrentOnReadOnlyFileGroup = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index is on a read-only filegroup.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO NoAction - END - END - -- Is the index fragmented? IF @CurrentIndexID IS NOT NULL AND @CurrentOnReadOnlyFileGroup = 0 AND EXISTS(SELECT * FROM @ActionsPreferred) AND (EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) OR @MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) BEGIN - SET @CurrentCommand12 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand12 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand12 = @CurrentCommand12 + 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(@ParamDatabaseID, @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + SET @CurrentCommand05 = '' + + IF @LockTimeout IS NOT NULL SET @CurrentCommand05 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - EXECUTE sp_executesql @statement = @CurrentCommand12, @params = N'@ParamDatabaseID int, @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseID = @CurrentDatabaseID, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT + SET @CurrentCommand05 = @CurrentCommand05 + 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(@ParamDatabaseID, @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + + EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamDatabaseID int, @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseID = @CurrentDatabaseID, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT SET @Error = @@ERROR IF @Error = 1222 BEGIN @@ -1514,6 +1466,7 @@ BEGIN IF @CurrentIndexID IS NOT NULL BEGIN SET @CurrentMaxDOP = @MaxDOP + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentAllowPageLocks = 0 BEGIN SET @CurrentMaxDOP = 1 @@ -1523,7 +1476,7 @@ BEGIN -- Update statistics? IF @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,3,4,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,3,4,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) - AND (@CurrentStatisticsModified = 1 OR @OnlyModifiedStatistics = 'N' OR @CurrentIsMemoryOptimized = 1) + AND (@CurrentModificationCounter > 0 OR @OnlyModifiedStatistics = 'N' OR (@CurrentIsMemoryOptimized = 1 AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') IN (5,8)))) AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND @CurrentPartitionNumber = @CurrentPartitionCount)) BEGIN SET @CurrentUpdateStatistics = 'Y' @@ -1537,7 +1490,7 @@ BEGIN SET @CurrentStatisticsResample = @StatisticsResample -- Memory-optimized tables only supports FULLSCAN and RESAMPLE in SQL Server 2014 - IF @CurrentIsMemoryOptimized = 1 AND @Version >= 12 AND @Version < 13 AND (@CurrentStatisticsSample <> 100 OR @CurrentStatisticsSample IS NULL) + IF @CurrentIsMemoryOptimized = 1 AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND (@CurrentStatisticsSample <> 100 OR @CurrentStatisticsSample IS NULL) BEGIN SET @CurrentStatisticsSample = NULL SET @CurrentStatisticsResample = 'Y' @@ -1567,44 +1520,91 @@ BEGIN IF @CurrentIndexID IS NOT NULL AND @CurrentAction IS NOT NULL AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommandType13 = 'ALTER_INDEX' + SET @CurrentCommandType06 = 'ALTER_INDEX' + + SET @CurrentCommand06 = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand06 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand06 = @CurrentCommand06 + 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') SET @CurrentCommand06 = @CurrentCommand06 + ' REBUILD' + IF @CurrentAction IN('INDEX_REORGANIZE') SET @CurrentCommand06 = @CurrentCommand06 + ' REORGANIZE' + IF @CurrentIsPartition = 1 SET @CurrentCommand06 = @CurrentCommand06 + ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) - SET @CurrentCommand13 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand13 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand13 = @CurrentCommand13 + 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'SORT_IN_TEMPDB = ON' + END + + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'N' AND @CurrentIndexType IN(1,2,3,4) + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'SORT_IN_TEMPDB = OFF' + END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentAction = 'INDEX_REBUILD_ONLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) BEGIN - SET @CurrentCommand13 = @CurrentCommand13 + ' REBUILD' - IF @CurrentIsPartition = 1 SET @CurrentCommand13 = @CurrentCommand13 + ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) - SET @CurrentCommand13 = @CurrentCommand13 + ' WITH (' - IF @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) SET @CurrentCommand13 = @CurrentCommand13 + 'SORT_IN_TEMPDB = ON' - IF @SortInTempdb = 'N' AND @CurrentIndexType IN(1,2,3,4) SET @CurrentCommand13 = @CurrentCommand13 + 'SORT_IN_TEMPDB = OFF' - IF @CurrentIndexType IN(1,2,3,4) AND (@CurrentIsPartition = 0 OR @Version >= 12) SET @CurrentCommand13 = @CurrentCommand13 + ', ' - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) SET @CurrentCommand13 = @CurrentCommand13 + 'ONLINE = ON' - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @WaitAtLowPriorityMaxDuration IS NOT NULL SET @CurrentCommand13 = @CurrentCommand13 + ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' - IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) SET @CurrentCommand13 = @CurrentCommand13 + 'ONLINE = OFF' - IF @CurrentMaxDOP IS NOT NULL SET @CurrentCommand13 = @CurrentCommand13 + ', MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) - IF @FillFactor IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) SET @CurrentCommand13 = @CurrentCommand13 + ', FILLFACTOR = ' + CAST(@FillFactor AS nvarchar) - IF @PadIndex = 'Y' AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) SET @CurrentCommand13 = @CurrentCommand13 + ', PAD_INDEX = ON' - IF @PadIndex = 'N' AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) SET @CurrentCommand13 = @CurrentCommand13 + ', PAD_INDEX = OFF' - SET @CurrentCommand13 = @CurrentCommand13 + ')' + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END END - IF @CurrentAction IN('INDEX_REORGANIZE') + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) BEGIN - SET @CurrentCommand13 = @CurrentCommand13 + ' REORGANIZE' - IF @CurrentIsPartition = 1 SET @CurrentCommand13 = @CurrentCommand13 + ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) - SET @CurrentCommand13 = @CurrentCommand13 + ' WITH (' - IF @LOBCompaction = 'Y' SET @CurrentCommand13 = @CurrentCommand13 + 'LOB_COMPACTION = ON' - IF @LOBCompaction = 'N' SET @CurrentCommand13 = @CurrentCommand13 + 'LOB_COMPACTION = OFF' - SET @CurrentCommand13 = @CurrentCommand13 + ')' + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'ONLINE = OFF' END - EXECUTE @CurrentCommandOutput13 = [dbo].[CommandExecute] @Command = @CurrentCommand13, @CommandType = @CurrentCommandType13, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo, @LogToTable = @LogToTable, @Execute = @Execute + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentMaxDOP IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) + END + + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @FillFactor IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'FILLFACTOR = ' + CAST(@FillFactor AS nvarchar) + END + + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex = 'Y' AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'PAD_INDEX = ON' + END + + IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'LOB_COMPACTION = ON' + END + + IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'N' + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'LOB_COMPACTION = OFF' + END + + IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) + BEGIN + SET @CurrentAlterIndexWithClause = ' WITH (' + END + + SELECT @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + Argument + ', ' + FROM @CurrentAlterIndexWithClauseArguments + ORDER BY ID ASC + + SET @CurrentAlterIndexWithClause = LEFT(@CurrentAlterIndexWithClause,LEN(@CurrentAlterIndexWithClause) - 1) + + IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) + BEGIN + SET @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + ')' + END + + IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand06 = @CurrentCommand06 + @CurrentAlterIndexWithClause + + EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput13 = @Error - IF @CurrentCommandOutput13 <> 0 SET @ReturnCode = @CurrentCommandOutput13 + IF @Error <> 0 SET @CurrentCommandOutput06 = @Error + IF @CurrentCommandOutput06 <> 0 SET @ReturnCode = @CurrentCommandOutput06 IF @Delay > 0 BEGIN @@ -1617,11 +1617,11 @@ BEGIN IF @CurrentStatisticsID IS NOT NULL AND @CurrentUpdateStatistics = 'Y' AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommandType14 = 'UPDATE_STATISTICS' + SET @CurrentCommandType07 = 'UPDATE_STATISTICS' - SET @CurrentCommand14 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand14 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand14 = @CurrentCommand14 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) + SET @CurrentCommand07 = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand07 = @CurrentCommand07 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) IF @CurrentStatisticsSample = 100 BEGIN @@ -1664,17 +1664,17 @@ BEGIN SET @CurrentUpdateStatisticsWithClause = LEFT(@CurrentUpdateStatisticsWithClause,LEN(@CurrentUpdateStatisticsWithClause) - 1) END - IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand14 = @CurrentCommand14 + @CurrentUpdateStatisticsWithClause + IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + @CurrentUpdateStatisticsWithClause - EXECUTE @CurrentCommandOutput14 = [dbo].[CommandExecute] @Command = @CurrentCommand14, @CommandType = @CurrentCommandType14, @Mode = 2, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput14 = @Error - IF @CurrentCommandOutput14 <> 0 SET @ReturnCode = @CurrentCommandOutput14 + IF @Error <> 0 SET @CurrentCommandOutput07 = @Error + IF @CurrentCommandOutput07 <> 0 SET @ReturnCode = @CurrentCommandOutput07 END NoAction: - -- Update that the index is completed + -- Update that the index or statistics is completed UPDATE @tmpIndexesStatistics SET Completed = 1 WHERE Selected = 1 @@ -1688,19 +1688,12 @@ BEGIN SET @CurrentCommand05 = NULL SET @CurrentCommand06 = NULL SET @CurrentCommand07 = NULL - SET @CurrentCommand08 = NULL - SET @CurrentCommand09 = NULL - SET @CurrentCommand10 = NULL - SET @CurrentCommand11 = NULL - SET @CurrentCommand12 = NULL - SET @CurrentCommand13 = NULL - SET @CurrentCommand14 = NULL - SET @CurrentCommandOutput13 = NULL - SET @CurrentCommandOutput14 = NULL + SET @CurrentCommandOutput06 = NULL + SET @CurrentCommandOutput07 = NULL - SET @CurrentCommandType13 = NULL - SET @CurrentCommandType14 = NULL + SET @CurrentCommandType06 = NULL + SET @CurrentCommandType07 = NULL SET @CurrentIxID = NULL SET @CurrentSchemaID = NULL @@ -1726,7 +1719,9 @@ BEGIN SET @CurrentIsColumnStore = NULL SET @CurrentAllowPageLocks = NULL SET @CurrentNoRecompute = NULL - SET @CurrentStatisticsModified = NULL + SET @CurrentIsIncremental = NULL + SET @CurrentRowCount = NULL + SET @CurrentModificationCounter = NULL SET @CurrentOnReadOnlyFileGroup = NULL SET @CurrentFragmentationLevel = NULL SET @CurrentPageCount = NULL @@ -1738,9 +1733,11 @@ BEGIN SET @CurrentStatisticsResample = NULL SET @CurrentComment = NULL SET @CurrentExtendedInfo = NULL + SET @CurrentAlterIndexWithClause = NULL SET @CurrentUpdateStatisticsWithClause = NULL DELETE FROM @CurrentActionsAllowed + DELETE FROM @CurrentAlterIndexWithClauseArguments DELETE FROM @CurrentUpdateStatisticsWithClauseArguments END diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 57ce366f..fbf47052 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -8,9 +8,11 @@ Index and Statistics Maintenance: https://ola.hallengren.com/sql-server-index-an The solution is free: https://ola.hallengren.com/license.html +GitHub: https://github.com/olahallengren/sql-server-maintenance-solution + You can contact me by e-mail at ola@hallengren.com. -Last updated 2 June, 2018. +Last updated 3 June, 2018. Ola Hallengren https://ola.hallengren.com @@ -112,7 +114,9 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- + --// License: https://ola.hallengren.com/license.html //-- + --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -355,7 +359,9 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- + --// License: https://ola.hallengren.com/license.html //-- + --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3021,7 +3027,9 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- + --// License: https://ola.hallengren.com/license.html //-- + --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3974,16 +3982,16 @@ BEGIN ON @CurrentDatabaseName LIKE REPLACE(SelectedFileGroups.DatabaseName,'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(SelectedFileGroups.FileGroupName,'_','[_]') WHERE SelectedFileGroups.Selected = 1 GROUP BY tmpFileGroups.FileGroupName) SelectedFileGroups2 - ON tmpFileGroups.FileGroupName = SelectedFileGroups2.FileGroupName; + ON tmpFileGroups.FileGroupName = SelectedFileGroups2.FileGroupName + END; - WITH tmpFileGroups AS ( - SELECT FileGroupName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, FileGroupName ASC) AS RowNumber - FROM @tmpFileGroups tmpFileGroups - WHERE Selected = 1 - ) - UPDATE tmpFileGroups - SET [Order] = RowNumber - END + WITH tmpFileGroups AS ( + SELECT FileGroupName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, FileGroupName ASC) AS RowNumber + FROM @tmpFileGroups tmpFileGroups + WHERE Selected = 1 + ) + UPDATE tmpFileGroups + SET [Order] = RowNumber SET @ErrorMessage = '' SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + '.' + QUOTENAME(FileGroupName) + ', ' @@ -4129,16 +4137,16 @@ BEGIN ON @CurrentDatabaseName LIKE REPLACE(SelectedObjects.DatabaseName,'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(SelectedObjects.SchemaName,'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(SelectedObjects.ObjectName,'_','[_]') WHERE SelectedObjects.Selected = 1 GROUP BY tmpObjects.SchemaName, tmpObjects.ObjectName) SelectedObjects2 - ON tmpObjects.SchemaName = SelectedObjects2.SchemaName AND tmpObjects.ObjectName = SelectedObjects2.ObjectName; + ON tmpObjects.SchemaName = SelectedObjects2.SchemaName AND tmpObjects.ObjectName = SelectedObjects2.ObjectName + END; - WITH tmpObjects AS ( - SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, SchemaName ASC, ObjectName ASC) AS RowNumber - FROM @tmpObjects tmpObjects - WHERE Selected = 1 - ) - UPDATE tmpObjects - SET [Order] = RowNumber - END + WITH tmpObjects AS ( + SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, SchemaName ASC, ObjectName ASC) AS RowNumber + FROM @tmpObjects tmpObjects + WHERE Selected = 1 + ) + UPDATE tmpObjects + SET [Order] = RowNumber SET @ErrorMessage = '' SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + ', ' @@ -4360,7 +4368,9 @@ AS BEGIN ---------------------------------------------------------------------------------------------------- - --// Source: https://ola.hallengren.com //-- + --// Source: https://ola.hallengren.com //-- + --// License: https://ola.hallengren.com/license.html //-- + --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4399,19 +4409,12 @@ BEGIN DECLARE @CurrentCommand05 nvarchar(max) DECLARE @CurrentCommand06 nvarchar(max) DECLARE @CurrentCommand07 nvarchar(max) - DECLARE @CurrentCommand08 nvarchar(max) - DECLARE @CurrentCommand09 nvarchar(max) - DECLARE @CurrentCommand10 nvarchar(max) - DECLARE @CurrentCommand11 nvarchar(max) - DECLARE @CurrentCommand12 nvarchar(max) - DECLARE @CurrentCommand13 nvarchar(max) - DECLARE @CurrentCommand14 nvarchar(max) - DECLARE @CurrentCommandOutput13 int - DECLARE @CurrentCommandOutput14 int + DECLARE @CurrentCommandOutput06 int + DECLARE @CurrentCommandOutput07 int - DECLARE @CurrentCommandType13 nvarchar(max) - DECLARE @CurrentCommandType14 nvarchar(max) + DECLARE @CurrentCommandType06 nvarchar(max) + DECLARE @CurrentCommandType07 nvarchar(max) DECLARE @CurrentIxID int DECLARE @CurrentSchemaID int @@ -4437,7 +4440,9 @@ BEGIN DECLARE @CurrentIsColumnStore bit DECLARE @CurrentAllowPageLocks bit DECLARE @CurrentNoRecompute bit - DECLARE @CurrentStatisticsModified bit + DECLARE @CurrentIsIncremental bit + DECLARE @CurrentRowCount int + DECLARE @CurrentModificationCounter int DECLARE @CurrentOnReadOnlyFileGroup bit DECLARE @CurrentFragmentationLevel float DECLARE @CurrentPageCount bigint @@ -4479,8 +4484,16 @@ BEGIN IndexID int, IndexName nvarchar(max), IndexType int, + AllowPageLocks bit, + IsImageText bit, + IsNewLOB bit, + IsFileStream bit, + IsColumnStore bit, + OnReadOnlyFileGroup bit, StatisticsID int, StatisticsName nvarchar(max), + [NoRecompute] bit, + IsIncremental bit, PartitionID bigint, PartitionNumber int, PartitionCount int, @@ -4519,6 +4532,12 @@ BEGIN DECLARE @CurrentActionsAllowed TABLE ([Action] nvarchar(max)) + + DECLARE @CurrentAlterIndexWithClauseArguments TABLE (ID int IDENTITY, + Argument nvarchar(max)) + + DECLARE @CurrentAlterIndexWithClause nvarchar(max) + DECLARE @CurrentUpdateStatisticsWithClauseArguments TABLE (ID int IDENTITY, Argument nvarchar(max)) @@ -5360,25 +5379,108 @@ BEGIN -- Select indexes in the current database IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, StatisticsID, StatisticsName, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed FROM (' + SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + 'USE ' + QUOTENAME(@CurrentDatabaseName) + ';' + + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, OnReadOnlyFileGroup, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + + ' FROM (' IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') BEGIN - SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized, indexes.index_id AS IndexID, indexes.[name] AS IndexName, indexes.[type] AS IndexType, stats.stats_id AS StatisticsID, stats.name AS StatisticsName' - IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', partitions.partition_id AS PartitionID, partitions.partition_number AS PartitionNumber, IndexPartitions.partition_count AS PartitionCount' - IF @PartitionLevel = 'N' SET @CurrentCommand01 = @CurrentCommand01 + ', NULL AS PartitionID, NULL AS PartitionNumber, NULL AS PartitionCount' - SET @CurrentCommand01 = @CurrentCommand01 + ', 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.[object_id] = tables.[object_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' - IF @PartitionLevel = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id LEFT OUTER JOIN (SELECT partitions.[object_id], partitions.index_id, COUNT(DISTINCT partitions.partition_number) AS partition_count FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions GROUP BY partitions.[object_id], partitions.index_id) IndexPartitions ON partitions.[object_id] = IndexPartitions.[object_id] AND partitions.[index_id] = IndexPartitions.[index_id]' - SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0' + SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID' + + ', schemas.[name] AS SchemaName' + + ', objects.[object_id] AS ObjectID' + + ', objects.[name] AS ObjectName' + + ', RTRIM(objects.[type]) AS ObjectType' + + ', ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized' + + ', indexes.index_id AS IndexID' + + ', indexes.[name] AS IndexName' + + ', indexes.[type] AS IndexType' + + ', indexes.allow_page_locks AS AllowPageLocks' + + + ', CASE WHEN indexes.[type] = 1 AND EXISTS(SELECT * FROM sys.columns columns INNER JOIN sys.types types ON columns.system_type_id = types.user_type_id WHERE columns.[object_id] = objects.object_id AND types.name IN(''image'',''text'',''ntext'')) THEN 1 ELSE 0 END AS IsImageText' + + + ', CASE WHEN indexes.[type] = 1 AND EXISTS(SELECT * FROM sys.columns columns INNER JOIN sys.types types ON columns.system_type_id = types.user_type_id OR (columns.user_type_id = types.user_type_id AND types.is_assembly_type = 1) WHERE columns.[object_id] = objects.object_id AND (types.name IN(''xml'') OR (types.name IN(''varchar'',''nvarchar'',''varbinary'') AND columns.max_length = -1) OR (types.is_assembly_type = 1 AND columns.max_length = -1))) THEN 1' + + ' WHEN indexes.[type] = 2 AND EXISTS(SELECT * FROM sys.index_columns index_columns INNER JOIN sys.columns columns ON index_columns.[object_id] = columns.[object_id] AND index_columns.column_id = columns.column_id INNER JOIN sys.types types ON columns.system_type_id = types.user_type_id OR (columns.user_type_id = types.user_type_id AND types.is_assembly_type = 1) WHERE index_columns.[object_id] = objects.object_id AND index_columns.index_id = indexes.index_id AND (types.[name] IN(''xml'') OR (types.[name] IN(''varchar'',''nvarchar'',''varbinary'') AND columns.max_length = -1) OR (types.is_assembly_type = 1 AND columns.max_length = -1))) THEN 1 ELSE 0 END AS IsNewLOB' + + + ', CASE WHEN indexes.[type] = 1 AND EXISTS(SELECT * FROM sys.columns columns WHERE columns.[object_id] = objects.object_id AND columns.is_filestream = 1) THEN 1 ELSE 0 END AS IsFileStream' + + + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] IN(5,6)) THEN 1 ELSE 0 END AS IsColumnStore' + + + ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON indexes.data_space_id = destination_data_spaces.partition_scheme_id INNER JOIN sys.filegroups filegroups ON destination_data_spaces.data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND indexes2.[object_id] = indexes.[object_id] AND indexes2.[index_id] = indexes.index_id' + CASE WHEN @PartitionLevel = 'Y' THEN ' AND destination_data_spaces.destination_id = partitions.partition_number' ELSE '' END + ') THEN 1' + + ' WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.filegroups filegroups ON indexes.data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND indexes.[object_id] = indexes2.[object_id] AND indexes.[index_id] = indexes2.index_id) THEN 1' + + ' WHEN indexes.[type] = 1 AND EXISTS (SELECT * FROM sys.tables tables INNER JOIN sys.filegroups filegroups ON tables.lob_data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND tables.[object_id] = objects.[object_id]) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' + + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE 'NULL' END + ' AS IsIncremental' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_id AS PartitionID' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionID' END + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber, NULL AS PartitionCount' END + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'IndexPartitions.partition_count AS PartitionCount' WHEN @PartitionLevel = 'N' THEN ', NULL AS PartitionCount' END + + ', 0 AS [Order]' + + ', 0 AS Selected' + + ', 0 AS Completed' + + ' FROM sys.indexes indexes' + + ' INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id]' + + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' + + ' LEFT OUTER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + + ' LEFT OUTER JOIN sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' + IF @PartitionLevel = 'Y' + BEGIN + SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' + + ' LEFT OUTER JOIN (SELECT partitions.[object_id], partitions.index_id, COUNT(DISTINCT partitions.partition_number) AS partition_count FROM sys.partitions partitions GROUP BY partitions.[object_id], partitions.index_id) IndexPartitions ON partitions.[object_id] = IndexPartitions.[object_id] AND partitions.[index_id] = IndexPartitions.[index_id]' + END + + SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + ' AND indexes.[type] IN(1,2,3,4,5,6,7)' + + ' AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0' END - IF (EXISTS(SELECT * FROM @ActionsPreferred) AND @UpdateStatistics = 'COLUMNS') OR @UpdateStatistics = 'ALL' SET @CurrentCommand01 = @CurrentCommand01 + ' UNION ' + IF (EXISTS(SELECT * FROM @ActionsPreferred) AND @UpdateStatistics = 'COLUMNS') OR @UpdateStatistics = 'ALL' + BEGIN + SET @CurrentCommand01 = @CurrentCommand01 + ' UNION ' + END - IF @UpdateStatistics IN('ALL','COLUMNS') SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized, NULL AS IndexID, NULL AS IndexName, NULL AS IndexType, stats.stats_id AS StatisticsID, stats.name AS StatisticsName, NULL AS PartitionID, NULL AS PartitionNumber, NULL AS PartitionCount, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.[object_id] = tables.[object_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND NOT EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id)' + IF @UpdateStatistics IN('ALL','COLUMNS') + BEGIN + SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID' + + ', schemas.[name] AS SchemaName' + + ', objects.[object_id] AS ObjectID' + + ', objects.[name] AS ObjectName' + + ', RTRIM(objects.[type]) AS ObjectType' + + ', ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized' + + ', NULL AS IndexID, NULL AS IndexName' + + ', NULL AS IndexType' + + ', NULL AS AllowPageLocks' + + ', NULL AS IsImageText' + + ', NULL AS IsNewLOB' + + ', NULL AS IsFileStream' + + ', NULL AS IsColumnStore' + + ', NULL AS OnReadOnlyFileGroup' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE 'NULL' END + ' AS IsIncremental' + + ', NULL AS PartitionID' + + ', NULL AS partition_number' + + ', NULL AS PartitionCount' + + ', 0 AS [Order]' + + ', 0 AS Selected' + + ', 0 AS Completed' + + ' FROM sys.stats stats' + + ' INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id]' + + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' + + ' LEFT OUTER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + + SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id)' + END SET @CurrentCommand01 = @CurrentCommand01 + ') IndexesStatistics' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, StatisticsID, StatisticsName, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, OnReadOnlyFileGroup, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) EXECUTE sp_executesql @statement = @CurrentCommand01 SET @Error = @@ERROR IF @Error <> 0 @@ -5421,16 +5523,16 @@ BEGIN ON tmpIndexesStatistics.SchemaName = SelectedIndexes2.SchemaName AND tmpIndexesStatistics.ObjectName = SelectedIndexes2.ObjectName AND (tmpIndexesStatistics.IndexName = SelectedIndexes2.IndexName OR tmpIndexesStatistics.IndexName IS NULL) - AND (tmpIndexesStatistics.StatisticsName = SelectedIndexes2.StatisticsName OR tmpIndexesStatistics.StatisticsName IS NULL); + AND (tmpIndexesStatistics.StatisticsName = SelectedIndexes2.StatisticsName OR tmpIndexesStatistics.StatisticsName IS NULL) + END; - WITH tmpIndexesStatistics AS ( - SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, SchemaName ASC, ObjectName ASC, CASE WHEN IndexType IS NULL THEN 1 ELSE 0 END ASC, IndexType ASC, IndexName ASC, StatisticsName ASC, PartitionNumber ASC) AS RowNumber - FROM @tmpIndexesStatistics tmpIndexesStatistics - WHERE Selected = 1 - ) - UPDATE tmpIndexesStatistics - SET [Order] = RowNumber - END + WITH tmpIndexesStatistics AS ( + SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, SchemaName ASC, ObjectName ASC, CASE WHEN IndexType IS NULL THEN 1 ELSE 0 END ASC, IndexType ASC, IndexName ASC, StatisticsName ASC, PartitionNumber ASC) AS RowNumber + FROM @tmpIndexesStatistics tmpIndexesStatistics + WHERE Selected = 1 + ) + UPDATE tmpIndexesStatistics + SET [Order] = RowNumber SET @ErrorMessage = '' SELECT @ErrorMessage = @ErrorMessage + QUOTENAME(DatabaseName) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + ', ' @@ -5464,7 +5566,6 @@ BEGIN WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SELECT TOP 1 @CurrentIxID = ID, @CurrentSchemaID = SchemaID, @CurrentSchemaName = SchemaName, @@ -5475,8 +5576,16 @@ BEGIN @CurrentIndexID = IndexID, @CurrentIndexName = IndexName, @CurrentIndexType = IndexType, + @CurrentAllowPageLocks = AllowPageLocks, + @CurrentIsImageText = IsImageText, + @CurrentIsNewLOB = IsNewLOB, + @CurrentIsFileStream = IsFileStream, + @CurrentIsColumnStore = IsColumnStore, + @CurrentOnReadOnlyFileGroup = OnReadOnlyFileGroup, @CurrentStatisticsID = StatisticsID, @CurrentStatisticsName = StatisticsName, + @CurrentNoRecompute = [NoRecompute], + @CurrentIsIncremental = IsIncremental, @CurrentPartitionID = PartitionID, @CurrentPartitionNumber = PartitionNumber, @CurrentPartitionCount = PartitionCount @@ -5497,9 +5606,12 @@ BEGIN IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) BEGIN SET @CurrentCommand02 = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand02 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - IF @CurrentIsPartition = 0 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' - IF @CurrentIsPartition = 1 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' + SET @CurrentCommand02 = @CurrentCommand02 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' + + IF @CurrentIsPartition = 0 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' + IF @CurrentIsPartition = 1 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' EXECUTE sp_executesql @statement = @CurrentCommand02, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT SET @Error = @@ERROR @@ -5522,8 +5634,11 @@ BEGIN IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL BEGIN SET @CurrentCommand03 = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' + SET @CurrentCommand03 = @CurrentCommand03 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' + + SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM sys.stats stats INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' EXECUTE sp_executesql @statement = @CurrentCommand03, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT SET @Error = @@ERROR @@ -5542,162 +5657,32 @@ BEGIN IF @CurrentStatisticsExists = 0 GOTO NoAction END - -- Is one of the columns in the index an image, text or ntext data type? - IF @CurrentIndexID IS NOT NULL AND @CurrentIndexType = 1 AND EXISTS(SELECT * FROM @ActionsPreferred) + -- Has the data in the statistics been modified since the statistics was last updated? + IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL AND @OnlyModifiedStatistics = 'Y' BEGIN SET @CurrentCommand04 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand04 = @CurrentCommand04 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.columns columns INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.types types ON columns.system_type_id = types.user_type_id WHERE columns.[object_id] = @ParamObjectID AND types.name IN(''image'',''text'',''ntext'')) BEGIN SET @ParamIsImageText = 1 END' - - EXECUTE sp_executesql @statement = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamIndexID int, @ParamIsImageText bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamIsImageText = @CurrentIsImageText OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentIsImageText IS NULL SET @CurrentIsImageText = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index contains any image, text, or ntext data types.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO NoAction - END - END - -- Is one of the columns in the index an xml, varchar(max), nvarchar(max), varbinary(max) or large CLR data type? - IF @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN(1,2) AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentCommand05 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand05 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - IF @CurrentIndexType = 1 SET @CurrentCommand05 = @CurrentCommand05 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.columns columns INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.types types ON columns.system_type_id = types.user_type_id OR (columns.user_type_id = types.user_type_id AND types.is_assembly_type = 1) WHERE columns.[object_id] = @ParamObjectID AND (types.name IN(''xml'') OR (types.name IN(''varchar'',''nvarchar'',''varbinary'') AND columns.max_length = -1) OR (types.is_assembly_type = 1 AND columns.max_length = -1))) BEGIN SET @ParamIsNewLOB = 1 END' - IF @CurrentIndexType = 2 SET @CurrentCommand05 = @CurrentCommand05 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.index_columns index_columns INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.columns columns ON index_columns.[object_id] = columns.[object_id] AND index_columns.column_id = columns.column_id INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.types types ON columns.system_type_id = types.user_type_id OR (columns.user_type_id = types.user_type_id AND types.is_assembly_type = 1) WHERE index_columns.[object_id] = @ParamObjectID AND index_columns.index_id = @ParamIndexID AND (types.[name] IN(''xml'') OR (types.[name] IN(''varchar'',''nvarchar'',''varbinary'') AND columns.max_length = -1) OR (types.is_assembly_type = 1 AND columns.max_length = -1))) BEGIN SET @ParamIsNewLOB = 1 END' - - EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamObjectID int, @ParamIndexID int, @ParamIsNewLOB bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamIsNewLOB = @CurrentIsNewLOB OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentIsNewLOB IS NULL SET @CurrentIsNewLOB = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index contains any xml, varchar(max), nvarchar(max), varbinary(max), or large CLR data types.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO NoAction - END - END - - -- Is one of the columns in the index a file stream column? - IF @CurrentIndexID IS NOT NULL AND @CurrentIndexType = 1 AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentCommand06 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand06 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand06 = @CurrentCommand06 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.columns columns WHERE columns.[object_id] = @ParamObjectID AND columns.is_filestream = 1) BEGIN SET @ParamIsFileStream = 1 END' - - EXECUTE sp_executesql @statement = @CurrentCommand06, @params = N'@ParamObjectID int, @ParamIndexID int, @ParamIsFileStream bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamIsFileStream = @CurrentIsFileStream OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentIsFileStream IS NULL SET @CurrentIsFileStream = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index contains any file stream columns.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO NoAction - END - END - - -- Is there a columnstore index on the table? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) AND @Version >= 11 - BEGIN - SET @CurrentCommand07 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand07 = @CurrentCommand07 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.[object_id] = @ParamObjectID AND [type] IN(5,6)) BEGIN SET @ParamIsColumnStore = 1 END' - - EXECUTE sp_executesql @statement = @CurrentCommand07, @params = N'@ParamObjectID int, @ParamIsColumnStore bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamIsColumnStore = @CurrentIsColumnStore OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentIsColumnStore IS NULL SET @CurrentIsColumnStore = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if there is a columnstore index on the table.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO NoAction - END - END - - -- Is Allow_Page_Locks set to On? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentCommand08 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand08 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand08 = @CurrentCommand08 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.[object_id] = @ParamObjectID AND indexes.[index_id] = @ParamIndexID AND indexes.[allow_page_locks] = 1) BEGIN SET @ParamAllowPageLocks = 1 END' - - EXECUTE sp_executesql @statement = @CurrentCommand08, @params = N'@ParamObjectID int, @ParamIndexID int, @ParamAllowPageLocks bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamAllowPageLocks = @CurrentAllowPageLocks OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentAllowPageLocks IS NULL SET @CurrentAllowPageLocks = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if page locking is enabled on the index.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO NoAction - END - END - - -- Is No_Recompute set to On? - IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL - BEGIN - SET @CurrentCommand09 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand09 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand09 = @CurrentCommand09 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.stats stats WHERE stats.[object_id] = @ParamObjectID AND stats.[stats_id] = @ParamStatisticsID AND stats.[no_recompute] = 1) BEGIN SET @ParamNoRecompute = 1 END' + IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand04 = @CurrentCommand04 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' - EXECUTE sp_executesql @statement = @CurrentCommand09, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamNoRecompute bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamNoRecompute = @CurrentNoRecompute OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentNoRecompute IS NULL SET @CurrentNoRecompute = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if automatic statistics update is enabled.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 + IF @CurrentIsIncremental = 1 AND ((@Version >= 12.05 AND @Version < 13) OR @Version >= 13.04422) AND 0 = 1 BEGIN - SET @ReturnCode = @Error - GOTO NoAction + SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' END - END - - -- Has the data in the statistics been modified since the statistics was last updated? - IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL AND @OnlyModifiedStatistics = 'Y' - BEGIN - SET @CurrentCommand10 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand10 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + ELSE IF (@Version >= 10.504000 AND @Version < 11) OR @Version >= 11.03000 BEGIN - SET @CurrentCommand10 = @CurrentCommand10 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; IF EXISTS(SELECT * FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE modification_counter > 0) BEGIN SET @ParamStatisticsModified = 1 END' + SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' END ELSE BEGIN - SET @CurrentCommand10 = @CurrentCommand10 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID AND sysindexes.[rowmodctr] <> 0) BEGIN SET @ParamStatisticsModified = 1 END' + SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = rowcnt, @ParamModificationCounter = rowmodctr FROM sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID' END - EXECUTE sp_executesql @statement = @CurrentCommand10, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamStatisticsModified bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsModified = @CurrentStatisticsModified OUTPUT + EXECUTE sp_executesql @statement = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount int OUTPUT, @ParamModificationCounter int OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT SET @Error = @@ERROR - IF @Error = 0 AND @CurrentStatisticsModified IS NULL SET @CurrentStatisticsModified = 0 + IF @Error = 0 AND @CurrentRowCount IS NULL SET @CurrentRowCount = 0 + IF @Error = 0 AND @CurrentModificationCounter IS NULL SET @CurrentModificationCounter = 0 IF @Error = 1222 BEGIN SET @ErrorMessage = 'The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if any rows has been modified since the most recent statistics update.' + CHAR(13) + CHAR(10) + ' ' @@ -5711,44 +5696,19 @@ BEGIN END END - -- Is the index on a read-only filegroup? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentCommand11 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand11 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand11 = @CurrentCommand11 + 'IF EXISTS(SELECT * FROM (SELECT filegroups.data_space_id FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.destination_data_spaces destination_data_spaces ON indexes.data_space_id = destination_data_spaces.partition_scheme_id INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups ON destination_data_spaces.data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND indexes.[object_id] = @ParamObjectID AND indexes.[index_id] = @ParamIndexID' - IF @CurrentIsPartition = 1 SET @CurrentCommand11 = @CurrentCommand11 + ' AND destination_data_spaces.destination_id = @ParamPartitionNumber' - SET @CurrentCommand11 = @CurrentCommand11 + ' UNION SELECT filegroups.data_space_id FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups ON indexes.data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND indexes.[object_id] = @ParamObjectID AND indexes.[index_id] = @ParamIndexID' - IF @CurrentIndexType = 1 SET @CurrentCommand11 = @CurrentCommand11 + ' UNION SELECT filegroups.data_space_id FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups ON tables.lob_data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND tables.[object_id] = @ParamObjectID' - SET @CurrentCommand11 = @CurrentCommand11 + ') ReadOnlyFileGroups) BEGIN SET @ParamOnReadOnlyFileGroup = 1 END' - - EXECUTE sp_executesql @statement = @CurrentCommand11, @params = N'@ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamOnReadOnlyFileGroup bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamOnReadOnlyFileGroup = @CurrentOnReadOnlyFileGroup OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentOnReadOnlyFileGroup IS NULL SET @CurrentOnReadOnlyFileGroup = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index is on a read-only filegroup.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO NoAction - END - END - -- Is the index fragmented? IF @CurrentIndexID IS NOT NULL AND @CurrentOnReadOnlyFileGroup = 0 AND EXISTS(SELECT * FROM @ActionsPreferred) AND (EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) OR @MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) BEGIN - SET @CurrentCommand12 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand12 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand12 = @CurrentCommand12 + 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(@ParamDatabaseID, @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + SET @CurrentCommand05 = '' + + IF @LockTimeout IS NOT NULL SET @CurrentCommand05 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + + SET @CurrentCommand05 = @CurrentCommand05 + 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(@ParamDatabaseID, @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' - EXECUTE sp_executesql @statement = @CurrentCommand12, @params = N'@ParamDatabaseID int, @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseID = @CurrentDatabaseID, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT + EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamDatabaseID int, @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseID = @CurrentDatabaseID, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT SET @Error = @@ERROR IF @Error = 1222 BEGIN @@ -5831,6 +5791,7 @@ BEGIN IF @CurrentIndexID IS NOT NULL BEGIN SET @CurrentMaxDOP = @MaxDOP + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentAllowPageLocks = 0 BEGIN SET @CurrentMaxDOP = 1 @@ -5840,7 +5801,7 @@ BEGIN -- Update statistics? IF @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,3,4,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,3,4,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) - AND (@CurrentStatisticsModified = 1 OR @OnlyModifiedStatistics = 'N' OR @CurrentIsMemoryOptimized = 1) + AND (@CurrentModificationCounter > 0 OR @OnlyModifiedStatistics = 'N' OR (@CurrentIsMemoryOptimized = 1 AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') IN (5,8)))) AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND @CurrentPartitionNumber = @CurrentPartitionCount)) BEGIN SET @CurrentUpdateStatistics = 'Y' @@ -5854,7 +5815,7 @@ BEGIN SET @CurrentStatisticsResample = @StatisticsResample -- Memory-optimized tables only supports FULLSCAN and RESAMPLE in SQL Server 2014 - IF @CurrentIsMemoryOptimized = 1 AND @Version >= 12 AND @Version < 13 AND (@CurrentStatisticsSample <> 100 OR @CurrentStatisticsSample IS NULL) + IF @CurrentIsMemoryOptimized = 1 AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND (@CurrentStatisticsSample <> 100 OR @CurrentStatisticsSample IS NULL) BEGIN SET @CurrentStatisticsSample = NULL SET @CurrentStatisticsResample = 'Y' @@ -5884,44 +5845,91 @@ BEGIN IF @CurrentIndexID IS NOT NULL AND @CurrentAction IS NOT NULL AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommandType13 = 'ALTER_INDEX' + SET @CurrentCommandType06 = 'ALTER_INDEX' + + SET @CurrentCommand06 = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand06 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand06 = @CurrentCommand06 + 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') SET @CurrentCommand06 = @CurrentCommand06 + ' REBUILD' + IF @CurrentAction IN('INDEX_REORGANIZE') SET @CurrentCommand06 = @CurrentCommand06 + ' REORGANIZE' + IF @CurrentIsPartition = 1 SET @CurrentCommand06 = @CurrentCommand06 + ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) + + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'SORT_IN_TEMPDB = ON' + END + + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'N' AND @CurrentIndexType IN(1,2,3,4) + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'SORT_IN_TEMPDB = OFF' + END + + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentAction = 'INDEX_REBUILD_ONLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END + END - SET @CurrentCommand13 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand13 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand13 = @CurrentCommand13 + 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'ONLINE = OFF' + END + + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentMaxDOP IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) + END + + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @FillFactor IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'FILLFACTOR = ' + CAST(@FillFactor AS nvarchar) + END + + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex = 'Y' AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'PAD_INDEX = ON' + END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') + IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' BEGIN - SET @CurrentCommand13 = @CurrentCommand13 + ' REBUILD' - IF @CurrentIsPartition = 1 SET @CurrentCommand13 = @CurrentCommand13 + ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) - SET @CurrentCommand13 = @CurrentCommand13 + ' WITH (' - IF @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) SET @CurrentCommand13 = @CurrentCommand13 + 'SORT_IN_TEMPDB = ON' - IF @SortInTempdb = 'N' AND @CurrentIndexType IN(1,2,3,4) SET @CurrentCommand13 = @CurrentCommand13 + 'SORT_IN_TEMPDB = OFF' - IF @CurrentIndexType IN(1,2,3,4) AND (@CurrentIsPartition = 0 OR @Version >= 12) SET @CurrentCommand13 = @CurrentCommand13 + ', ' - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) SET @CurrentCommand13 = @CurrentCommand13 + 'ONLINE = ON' - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @WaitAtLowPriorityMaxDuration IS NOT NULL SET @CurrentCommand13 = @CurrentCommand13 + ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' - IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) SET @CurrentCommand13 = @CurrentCommand13 + 'ONLINE = OFF' - IF @CurrentMaxDOP IS NOT NULL SET @CurrentCommand13 = @CurrentCommand13 + ', MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) - IF @FillFactor IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) SET @CurrentCommand13 = @CurrentCommand13 + ', FILLFACTOR = ' + CAST(@FillFactor AS nvarchar) - IF @PadIndex = 'Y' AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) SET @CurrentCommand13 = @CurrentCommand13 + ', PAD_INDEX = ON' - IF @PadIndex = 'N' AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) SET @CurrentCommand13 = @CurrentCommand13 + ', PAD_INDEX = OFF' - SET @CurrentCommand13 = @CurrentCommand13 + ')' + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'LOB_COMPACTION = ON' END - IF @CurrentAction IN('INDEX_REORGANIZE') + IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'N' BEGIN - SET @CurrentCommand13 = @CurrentCommand13 + ' REORGANIZE' - IF @CurrentIsPartition = 1 SET @CurrentCommand13 = @CurrentCommand13 + ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) - SET @CurrentCommand13 = @CurrentCommand13 + ' WITH (' - IF @LOBCompaction = 'Y' SET @CurrentCommand13 = @CurrentCommand13 + 'LOB_COMPACTION = ON' - IF @LOBCompaction = 'N' SET @CurrentCommand13 = @CurrentCommand13 + 'LOB_COMPACTION = OFF' - SET @CurrentCommand13 = @CurrentCommand13 + ')' + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'LOB_COMPACTION = OFF' END - EXECUTE @CurrentCommandOutput13 = [dbo].[CommandExecute] @Command = @CurrentCommand13, @CommandType = @CurrentCommandType13, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo, @LogToTable = @LogToTable, @Execute = @Execute + IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) + BEGIN + SET @CurrentAlterIndexWithClause = ' WITH (' + END + + SELECT @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + Argument + ', ' + FROM @CurrentAlterIndexWithClauseArguments + ORDER BY ID ASC + + SET @CurrentAlterIndexWithClause = LEFT(@CurrentAlterIndexWithClause,LEN(@CurrentAlterIndexWithClause) - 1) + + IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) + BEGIN + SET @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + ')' + END + + IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand06 = @CurrentCommand06 + @CurrentAlterIndexWithClause + + EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput13 = @Error - IF @CurrentCommandOutput13 <> 0 SET @ReturnCode = @CurrentCommandOutput13 + IF @Error <> 0 SET @CurrentCommandOutput06 = @Error + IF @CurrentCommandOutput06 <> 0 SET @ReturnCode = @CurrentCommandOutput06 IF @Delay > 0 BEGIN @@ -5934,11 +5942,11 @@ BEGIN IF @CurrentStatisticsID IS NOT NULL AND @CurrentUpdateStatistics = 'Y' AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommandType14 = 'UPDATE_STATISTICS' + SET @CurrentCommandType07 = 'UPDATE_STATISTICS' - SET @CurrentCommand14 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand14 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand14 = @CurrentCommand14 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) + SET @CurrentCommand07 = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand07 = @CurrentCommand07 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) IF @CurrentStatisticsSample = 100 BEGIN @@ -5981,17 +5989,17 @@ BEGIN SET @CurrentUpdateStatisticsWithClause = LEFT(@CurrentUpdateStatisticsWithClause,LEN(@CurrentUpdateStatisticsWithClause) - 1) END - IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand14 = @CurrentCommand14 + @CurrentUpdateStatisticsWithClause + IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + @CurrentUpdateStatisticsWithClause - EXECUTE @CurrentCommandOutput14 = [dbo].[CommandExecute] @Command = @CurrentCommand14, @CommandType = @CurrentCommandType14, @Mode = 2, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput14 = @Error - IF @CurrentCommandOutput14 <> 0 SET @ReturnCode = @CurrentCommandOutput14 + IF @Error <> 0 SET @CurrentCommandOutput07 = @Error + IF @CurrentCommandOutput07 <> 0 SET @ReturnCode = @CurrentCommandOutput07 END NoAction: - -- Update that the index is completed + -- Update that the index or statistics is completed UPDATE @tmpIndexesStatistics SET Completed = 1 WHERE Selected = 1 @@ -6005,19 +6013,12 @@ BEGIN SET @CurrentCommand05 = NULL SET @CurrentCommand06 = NULL SET @CurrentCommand07 = NULL - SET @CurrentCommand08 = NULL - SET @CurrentCommand09 = NULL - SET @CurrentCommand10 = NULL - SET @CurrentCommand11 = NULL - SET @CurrentCommand12 = NULL - SET @CurrentCommand13 = NULL - SET @CurrentCommand14 = NULL - SET @CurrentCommandOutput13 = NULL - SET @CurrentCommandOutput14 = NULL + SET @CurrentCommandOutput06 = NULL + SET @CurrentCommandOutput07 = NULL - SET @CurrentCommandType13 = NULL - SET @CurrentCommandType14 = NULL + SET @CurrentCommandType06 = NULL + SET @CurrentCommandType07 = NULL SET @CurrentIxID = NULL SET @CurrentSchemaID = NULL @@ -6043,7 +6044,9 @@ BEGIN SET @CurrentIsColumnStore = NULL SET @CurrentAllowPageLocks = NULL SET @CurrentNoRecompute = NULL - SET @CurrentStatisticsModified = NULL + SET @CurrentIsIncremental = NULL + SET @CurrentRowCount = NULL + SET @CurrentModificationCounter = NULL SET @CurrentOnReadOnlyFileGroup = NULL SET @CurrentFragmentationLevel = NULL SET @CurrentPageCount = NULL @@ -6055,9 +6058,11 @@ BEGIN SET @CurrentStatisticsResample = NULL SET @CurrentComment = NULL SET @CurrentExtendedInfo = NULL + SET @CurrentAlterIndexWithClause = NULL SET @CurrentUpdateStatisticsWithClause = NULL DELETE FROM @CurrentActionsAllowed + DELETE FROM @CurrentAlterIndexWithClauseArguments DELETE FROM @CurrentUpdateStatisticsWithClauseArguments END From 7d5bbed8b958381bbedae8b35e1cba556e03d2c6 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 3 Jun 2018 19:32:21 +0200 Subject: [PATCH 032/188] Add files via upload --- IndexOptimize.sql | 4 ++-- MaintenanceSolution.sql | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 36c860cd..f1b89107 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -1090,8 +1090,8 @@ BEGIN + ', stats.no_recompute AS NoRecompute' + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE 'NULL' END + ' AS IsIncremental' + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_id AS PartitionID' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionID' END - + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber, NULL AS PartitionCount' END - + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'IndexPartitions.partition_count AS PartitionCount' WHEN @PartitionLevel = 'N' THEN ', NULL AS PartitionCount' END + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'IndexPartitions.partition_count AS PartitionCount' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionCount' END + ', 0 AS [Order]' + ', 0 AS Selected' + ', 0 AS Completed' diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index fbf47052..f654f89e 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -5415,8 +5415,8 @@ BEGIN + ', stats.no_recompute AS NoRecompute' + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE 'NULL' END + ' AS IsIncremental' + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_id AS PartitionID' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionID' END - + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber, NULL AS PartitionCount' END - + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'IndexPartitions.partition_count AS PartitionCount' WHEN @PartitionLevel = 'N' THEN ', NULL AS PartitionCount' END + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'IndexPartitions.partition_count AS PartitionCount' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionCount' END + ', 0 AS [Order]' + ', 0 AS Selected' + ', 0 AS Completed' From 02061f1da38f850612370db6ab207a8b0e172873 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 3 Jun 2018 20:56:29 +0200 Subject: [PATCH 033/188] Add files via upload --- IndexOptimize.sql | 78 ++++++++++++++++++++++++++++------------- MaintenanceSolution.sql | 78 ++++++++++++++++++++++++++++------------- 2 files changed, 106 insertions(+), 50 deletions(-) diff --git a/IndexOptimize.sql b/IndexOptimize.sql index f1b89107..e4596857 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -91,6 +91,12 @@ BEGIN DECLARE @CurrentCommandType06 nvarchar(max) DECLARE @CurrentCommandType07 nvarchar(max) + DECLARE @CurrentComment06 nvarchar(max) + DECLARE @CurrentComment07 nvarchar(max) + + DECLARE @CurrentExtendedInfo06 xml + DECLARE @CurrentExtendedInfo07 xml + DECLARE @CurrentIxID int DECLARE @CurrentSchemaID int DECLARE @CurrentSchemaName nvarchar(max) @@ -127,8 +133,6 @@ BEGIN DECLARE @CurrentUpdateStatistics nvarchar(max) DECLARE @CurrentStatisticsSample int DECLARE @CurrentStatisticsResample nvarchar(max) - DECLARE @CurrentComment nvarchar(max) - DECLARE @CurrentExtendedInfo xml DECLARE @CurrentDelay datetime DECLARE @tmpDatabases TABLE (ID int IDENTITY, @@ -1066,7 +1070,7 @@ BEGIN + ', objects.[object_id] AS ObjectID' + ', objects.[name] AS ObjectName' + ', RTRIM(objects.[type]) AS ObjectType' - + ', ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized' + + ', ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE '0' END + ' AS IsMemoryOptimized' + ', indexes.index_id AS IndexID' + ', indexes.[name] AS IndexName' + ', indexes.[type] AS IndexType' @@ -1088,7 +1092,7 @@ BEGIN + ', stats.stats_id AS StatisticsID' + ', stats.name AS StatisticsName' + ', stats.no_recompute AS NoRecompute' - + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE 'NULL' END + ' AS IsIncremental' + + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE '0' END + ' AS IsIncremental' + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_id AS PartitionID' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionID' END + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'IndexPartitions.partition_count AS PartitionCount' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionCount' END @@ -1124,7 +1128,7 @@ BEGIN + ', objects.[object_id] AS ObjectID' + ', objects.[name] AS ObjectName' + ', RTRIM(objects.[type]) AS ObjectType' - + ', ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized' + + ', ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE '0' END + ' AS IsMemoryOptimized' + ', NULL AS IndexID, NULL AS IndexName' + ', NULL AS IndexType' + ', NULL AS AllowPageLocks' @@ -1136,7 +1140,7 @@ BEGIN + ', stats.stats_id AS StatisticsID' + ', stats.name AS StatisticsName' + ', stats.no_recompute AS NoRecompute' - + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE 'NULL' END + ' AS IsIncremental' + + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE '0' END + ' AS IsIncremental' + ', NULL AS PartitionID' + ', NULL AS partition_number' + ', NULL AS PartitionCount' @@ -1333,7 +1337,7 @@ BEGIN END -- Has the data in the statistics been modified since the statistics was last updated? - IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL AND @OnlyModifiedStatistics = 'Y' + IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL BEGIN SET @CurrentCommand04 = '' @@ -1496,26 +1500,46 @@ BEGIN SET @CurrentStatisticsResample = 'Y' END - -- Create comment + + -- Create index comment IF @CurrentIndexID IS NOT NULL BEGIN - SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment = @CurrentComment + 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' - SET @CurrentComment = @CurrentComment + 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment = @CurrentComment + 'NewLOB: ' + CASE WHEN @CurrentIsNewLOB = 1 THEN 'Yes' WHEN @CurrentIsNewLOB = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment = @CurrentComment + 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 11 SET @CurrentComment = @CurrentComment + 'ColumnStore: ' + CASE WHEN @CurrentIsColumnStore = 1 THEN 'Yes' WHEN @CurrentIsColumnStore = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment = @CurrentComment + 'AllowPageLocks: ' + CASE WHEN @CurrentAllowPageLocks = 1 THEN 'Yes' WHEN @CurrentAllowPageLocks = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment = @CurrentComment + 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar),'N/A') + ', ' - SET @CurrentComment = @CurrentComment + 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar),'N/A') + SET @CurrentComment06 = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' + SET @CurrentComment06 = @CurrentComment06 + 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' + SET @CurrentComment06 = @CurrentComment06 + 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 = @CurrentComment06 + 'NewLOB: ' + CASE WHEN @CurrentIsNewLOB = 1 THEN 'Yes' WHEN @CurrentIsNewLOB = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 = @CurrentComment06 + 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 11 SET @CurrentComment06 = @CurrentComment06 + 'ColumnStore: ' + CASE WHEN @CurrentIsColumnStore = 1 THEN 'Yes' WHEN @CurrentIsColumnStore = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 = @CurrentComment06 + 'AllowPageLocks: ' + CASE WHEN @CurrentAllowPageLocks = 1 THEN 'Yes' WHEN @CurrentAllowPageLocks = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 = @CurrentComment06 + 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar),'N/A') + ', ' + SET @CurrentComment06 = @CurrentComment06 + 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar),'N/A') END IF @CurrentIndexID IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) BEGIN - SET @CurrentExtendedInfo = (SELECT * - FROM (SELECT CAST(@CurrentPageCount AS nvarchar) AS [PageCount], - CAST(@CurrentFragmentationLevel AS nvarchar) AS Fragmentation - ) ExtendedInfo FOR XML AUTO, ELEMENTS) + SET @CurrentExtendedInfo06 = (SELECT * + FROM (SELECT CAST(@CurrentPageCount AS nvarchar) AS [PageCount], + CAST(@CurrentFragmentationLevel AS nvarchar) AS Fragmentation + ) ExtendedInfo FOR XML AUTO, ELEMENTS) + END + + -- Create statistics comment + IF @CurrentStatisticsID IS NOT NULL + BEGIN + SET @CurrentComment07 = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' + SET @CurrentComment07 = @CurrentComment07 + 'IndexType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' + IF @CurrentIndexID IS NOT NULL SET @CurrentComment07 = @CurrentComment07 + 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' + SET @CurrentComment07 = @CurrentComment07 + 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Y' WHEN @CurrentIsIncremental = 0 THEN 'N' ELSE 'N/A' END + ', ' + SET @CurrentComment07 = @CurrentComment07 + 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' + SET @CurrentComment07 = @CurrentComment07 + 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') + END + + IF @CurrentStatisticsID IS NOT NULL AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) + BEGIN + SET @CurrentExtendedInfo07 = (SELECT * + FROM (SELECT CAST(@CurrentRowCount AS nvarchar) AS [RowCount], + CAST(@CurrentModificationCounter AS nvarchar) AS ModificationCounter + ) ExtendedInfo FOR XML AUTO, ELEMENTS) END IF @CurrentIndexID IS NOT NULL AND @CurrentAction IS NOT NULL AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) @@ -1601,7 +1625,7 @@ BEGIN IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand06 = @CurrentCommand06 + @CurrentAlterIndexWithClause - EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment06, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo06, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput06 = @Error IF @CurrentCommandOutput06 <> 0 SET @ReturnCode = @CurrentCommandOutput06 @@ -1666,7 +1690,7 @@ BEGIN IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + @CurrentUpdateStatisticsWithClause - EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput07 = @Error IF @CurrentCommandOutput07 <> 0 SET @ReturnCode = @CurrentCommandOutput07 @@ -1695,6 +1719,12 @@ BEGIN SET @CurrentCommandType06 = NULL SET @CurrentCommandType07 = NULL + SET @CurrentComment06 = NULL + SET @CurrentComment07 = NULL + + SET @CurrentExtendedInfo06 = NULL + SET @CurrentExtendedInfo07 = NULL + SET @CurrentIxID = NULL SET @CurrentSchemaID = NULL SET @CurrentSchemaName = NULL @@ -1731,8 +1761,6 @@ BEGIN SET @CurrentUpdateStatistics = NULL SET @CurrentStatisticsSample = NULL SET @CurrentStatisticsResample = NULL - SET @CurrentComment = NULL - SET @CurrentExtendedInfo = NULL SET @CurrentAlterIndexWithClause = NULL SET @CurrentUpdateStatisticsWithClause = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index f654f89e..3953d8b7 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -4416,6 +4416,12 @@ BEGIN DECLARE @CurrentCommandType06 nvarchar(max) DECLARE @CurrentCommandType07 nvarchar(max) + DECLARE @CurrentComment06 nvarchar(max) + DECLARE @CurrentComment07 nvarchar(max) + + DECLARE @CurrentExtendedInfo06 xml + DECLARE @CurrentExtendedInfo07 xml + DECLARE @CurrentIxID int DECLARE @CurrentSchemaID int DECLARE @CurrentSchemaName nvarchar(max) @@ -4452,8 +4458,6 @@ BEGIN DECLARE @CurrentUpdateStatistics nvarchar(max) DECLARE @CurrentStatisticsSample int DECLARE @CurrentStatisticsResample nvarchar(max) - DECLARE @CurrentComment nvarchar(max) - DECLARE @CurrentExtendedInfo xml DECLARE @CurrentDelay datetime DECLARE @tmpDatabases TABLE (ID int IDENTITY, @@ -5391,7 +5395,7 @@ BEGIN + ', objects.[object_id] AS ObjectID' + ', objects.[name] AS ObjectName' + ', RTRIM(objects.[type]) AS ObjectType' - + ', ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized' + + ', ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE '0' END + ' AS IsMemoryOptimized' + ', indexes.index_id AS IndexID' + ', indexes.[name] AS IndexName' + ', indexes.[type] AS IndexType' @@ -5413,7 +5417,7 @@ BEGIN + ', stats.stats_id AS StatisticsID' + ', stats.name AS StatisticsName' + ', stats.no_recompute AS NoRecompute' - + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE 'NULL' END + ' AS IsIncremental' + + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE '0' END + ' AS IsIncremental' + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_id AS PartitionID' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionID' END + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'IndexPartitions.partition_count AS PartitionCount' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionCount' END @@ -5449,7 +5453,7 @@ BEGIN + ', objects.[object_id] AS ObjectID' + ', objects.[name] AS ObjectName' + ', RTRIM(objects.[type]) AS ObjectType' - + ', ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE 'NULL' END + ' AS IsMemoryOptimized' + + ', ' + CASE WHEN @Version >= 12 THEN 'tables.is_memory_optimized' ELSE '0' END + ' AS IsMemoryOptimized' + ', NULL AS IndexID, NULL AS IndexName' + ', NULL AS IndexType' + ', NULL AS AllowPageLocks' @@ -5461,7 +5465,7 @@ BEGIN + ', stats.stats_id AS StatisticsID' + ', stats.name AS StatisticsName' + ', stats.no_recompute AS NoRecompute' - + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE 'NULL' END + ' AS IsIncremental' + + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE '0' END + ' AS IsIncremental' + ', NULL AS PartitionID' + ', NULL AS partition_number' + ', NULL AS PartitionCount' @@ -5658,7 +5662,7 @@ BEGIN END -- Has the data in the statistics been modified since the statistics was last updated? - IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL AND @OnlyModifiedStatistics = 'Y' + IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL BEGIN SET @CurrentCommand04 = '' @@ -5821,26 +5825,46 @@ BEGIN SET @CurrentStatisticsResample = 'Y' END - -- Create comment + + -- Create index comment IF @CurrentIndexID IS NOT NULL BEGIN - SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment = @CurrentComment + 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' - SET @CurrentComment = @CurrentComment + 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment = @CurrentComment + 'NewLOB: ' + CASE WHEN @CurrentIsNewLOB = 1 THEN 'Yes' WHEN @CurrentIsNewLOB = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment = @CurrentComment + 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 11 SET @CurrentComment = @CurrentComment + 'ColumnStore: ' + CASE WHEN @CurrentIsColumnStore = 1 THEN 'Yes' WHEN @CurrentIsColumnStore = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment = @CurrentComment + 'AllowPageLocks: ' + CASE WHEN @CurrentAllowPageLocks = 1 THEN 'Yes' WHEN @CurrentAllowPageLocks = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment = @CurrentComment + 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar),'N/A') + ', ' - SET @CurrentComment = @CurrentComment + 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar),'N/A') + SET @CurrentComment06 = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' + SET @CurrentComment06 = @CurrentComment06 + 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' + SET @CurrentComment06 = @CurrentComment06 + 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 = @CurrentComment06 + 'NewLOB: ' + CASE WHEN @CurrentIsNewLOB = 1 THEN 'Yes' WHEN @CurrentIsNewLOB = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 = @CurrentComment06 + 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 11 SET @CurrentComment06 = @CurrentComment06 + 'ColumnStore: ' + CASE WHEN @CurrentIsColumnStore = 1 THEN 'Yes' WHEN @CurrentIsColumnStore = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 = @CurrentComment06 + 'AllowPageLocks: ' + CASE WHEN @CurrentAllowPageLocks = 1 THEN 'Yes' WHEN @CurrentAllowPageLocks = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 = @CurrentComment06 + 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar),'N/A') + ', ' + SET @CurrentComment06 = @CurrentComment06 + 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar),'N/A') END IF @CurrentIndexID IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) BEGIN - SET @CurrentExtendedInfo = (SELECT * - FROM (SELECT CAST(@CurrentPageCount AS nvarchar) AS [PageCount], - CAST(@CurrentFragmentationLevel AS nvarchar) AS Fragmentation - ) ExtendedInfo FOR XML AUTO, ELEMENTS) + SET @CurrentExtendedInfo06 = (SELECT * + FROM (SELECT CAST(@CurrentPageCount AS nvarchar) AS [PageCount], + CAST(@CurrentFragmentationLevel AS nvarchar) AS Fragmentation + ) ExtendedInfo FOR XML AUTO, ELEMENTS) + END + + -- Create statistics comment + IF @CurrentStatisticsID IS NOT NULL + BEGIN + SET @CurrentComment07 = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' + SET @CurrentComment07 = @CurrentComment07 + 'IndexType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' + IF @CurrentIndexID IS NOT NULL SET @CurrentComment07 = @CurrentComment07 + 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' + SET @CurrentComment07 = @CurrentComment07 + 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Y' WHEN @CurrentIsIncremental = 0 THEN 'N' ELSE 'N/A' END + ', ' + SET @CurrentComment07 = @CurrentComment07 + 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' + SET @CurrentComment07 = @CurrentComment07 + 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') + END + + IF @CurrentStatisticsID IS NOT NULL AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) + BEGIN + SET @CurrentExtendedInfo07 = (SELECT * + FROM (SELECT CAST(@CurrentRowCount AS nvarchar) AS [RowCount], + CAST(@CurrentModificationCounter AS nvarchar) AS ModificationCounter + ) ExtendedInfo FOR XML AUTO, ELEMENTS) END IF @CurrentIndexID IS NOT NULL AND @CurrentAction IS NOT NULL AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) @@ -5926,7 +5950,7 @@ BEGIN IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand06 = @CurrentCommand06 + @CurrentAlterIndexWithClause - EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment06, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo06, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput06 = @Error IF @CurrentCommandOutput06 <> 0 SET @ReturnCode = @CurrentCommandOutput06 @@ -5991,7 +6015,7 @@ BEGIN IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + @CurrentUpdateStatisticsWithClause - EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput07 = @Error IF @CurrentCommandOutput07 <> 0 SET @ReturnCode = @CurrentCommandOutput07 @@ -6020,6 +6044,12 @@ BEGIN SET @CurrentCommandType06 = NULL SET @CurrentCommandType07 = NULL + SET @CurrentComment06 = NULL + SET @CurrentComment07 = NULL + + SET @CurrentExtendedInfo06 = NULL + SET @CurrentExtendedInfo07 = NULL + SET @CurrentIxID = NULL SET @CurrentSchemaID = NULL SET @CurrentSchemaName = NULL @@ -6056,8 +6086,6 @@ BEGIN SET @CurrentUpdateStatistics = NULL SET @CurrentStatisticsSample = NULL SET @CurrentStatisticsResample = NULL - SET @CurrentComment = NULL - SET @CurrentExtendedInfo = NULL SET @CurrentAlterIndexWithClause = NULL SET @CurrentUpdateStatisticsWithClause = NULL From fdf1d5986111731a30f7398ca7fc4ab2d3c61f28 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 4 Jun 2018 11:10:12 +0200 Subject: [PATCH 034/188] Add files via upload --- IndexOptimize.sql | 5 ----- MaintenanceSolution.sql | 7 +------ 2 files changed, 1 insertion(+), 11 deletions(-) diff --git a/IndexOptimize.sql b/IndexOptimize.sql index e4596857..8f20d3a3 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -1344,11 +1344,6 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand04 = @CurrentCommand04 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' - IF @CurrentIsIncremental = 1 AND ((@Version >= 12.05 AND @Version < 13) OR @Version >= 13.04422) AND 0 = 1 - BEGIN - SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' - END - ELSE IF (@Version >= 10.504000 AND @Version < 11) OR @Version >= 11.03000 BEGIN SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 3953d8b7..0a913568 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -12,7 +12,7 @@ GitHub: https://github.com/olahallengren/sql-server-maintenance-solution You can contact me by e-mail at ola@hallengren.com. -Last updated 3 June, 2018. +Last updated 4 June, 2018. Ola Hallengren https://ola.hallengren.com @@ -5669,11 +5669,6 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand04 = @CurrentCommand04 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' - IF @CurrentIsIncremental = 1 AND ((@Version >= 12.05 AND @Version < 13) OR @Version >= 13.04422) AND 0 = 1 - BEGIN - SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' - END - ELSE IF (@Version >= 10.504000 AND @Version < 11) OR @Version >= 11.03000 BEGIN SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' From 336c848ab7e911982a8209076a2611b63038f4b9 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 4 Jun 2018 21:24:32 +0200 Subject: [PATCH 035/188] Update README.md --- README.md | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 927bd55d..14d3f3d4 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,40 @@ -# sql-server-maintenance-solution +# SQL Server Maintenance Solution +[![licence badge]][licence] +[![stars badge]][stars] +[![forks badge]][forks] +[![issues badge]][issues] + +## Getting Started + +Download [MaintenanceSolution.sql](/MaintenanceSolution.sql). +This script creates all the objects and jobs that you need. + +You can also download the objects as separate scripts: + - [DatabaseBackup](/DatabaseBackup.sql): SQL Server Backup + - [DatabaseIntegrityCheck](/DatabaseIntegrityCheck.sql): SQL Server Integrity Check + - [IndexOptimize](/IndexOptimize.sql): SQL Server Index and Statistics Maintenance + - [CommandExecute](/CommandExecute.sql): Stored procedure to execute and log commands + - [CommandLog](/CommandLog.sql): Table to log commands + +Note that you always need CommandExecute, DatabaseBackup, DatabaseIntegrityCheck, and IndexOptimize are using it. +You need CommandLog if you are going to use the option to log commands to a table. Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, and SQL Server 2017 +## Documentation +
    • Backup: https://ola.hallengren.com/sql-server-backup.html
    • Integrity Check: https://ola.hallengren.com/sql-server-integrity-check.html
    • Index and Statistics Maintenance: https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html
    + +[licence badge]:https://img.shields.io/badge/license-MIT-blue.svg +[stars badge]:https://img.shields.io/github/stars/olahallengren/sql-server-maintenance-solution.svg +[forks badge]:https://img.shields.io/github/forks/olahallengren/sql-server-maintenance-solution.svg +[issues badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution.svg + +[licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE +[stars]:https://github.com/olahallengren/sql-server-maintenance-solution/stargazers +[forks]:https://github.com/olahallengren/sql-server-maintenance-solution/network +[issues]:https://github.com/olahallengren/sql-server-maintenance-solution/issues From f254dd3ca34247b03691a5d8035ffde5235e7588 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 5 Jun 2018 10:10:44 +0200 Subject: [PATCH 036/188] Add files via upload --- IndexOptimize.sql | 4 ++-- MaintenanceSolution.sql | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 8f20d3a3..e97dacf2 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -122,8 +122,8 @@ BEGIN DECLARE @CurrentAllowPageLocks bit DECLARE @CurrentNoRecompute bit DECLARE @CurrentIsIncremental bit - DECLARE @CurrentRowCount int - DECLARE @CurrentModificationCounter int + DECLARE @CurrentRowCount bigint + DECLARE @CurrentModificationCounter bigint DECLARE @CurrentOnReadOnlyFileGroup bit DECLARE @CurrentFragmentationLevel float DECLARE @CurrentPageCount bigint diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 0a913568..93e287e8 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -12,7 +12,7 @@ GitHub: https://github.com/olahallengren/sql-server-maintenance-solution You can contact me by e-mail at ola@hallengren.com. -Last updated 4 June, 2018. +Last updated 5 June, 2018. Ola Hallengren https://ola.hallengren.com @@ -4447,8 +4447,8 @@ BEGIN DECLARE @CurrentAllowPageLocks bit DECLARE @CurrentNoRecompute bit DECLARE @CurrentIsIncremental bit - DECLARE @CurrentRowCount int - DECLARE @CurrentModificationCounter int + DECLARE @CurrentRowCount bigint + DECLARE @CurrentModificationCounter bigint DECLARE @CurrentOnReadOnlyFileGroup bit DECLARE @CurrentFragmentationLevel float DECLARE @CurrentPageCount bigint From a2a8f3e7db1b6d6d36a661a2bd1245f35ca2b41b Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 5 Jun 2018 10:20:06 +0200 Subject: [PATCH 037/188] Add files via upload --- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/IndexOptimize.sql b/IndexOptimize.sql index e97dacf2..dc470397 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -1353,7 +1353,7 @@ BEGIN SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = rowcnt, @ParamModificationCounter = rowmodctr FROM sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID' END - EXECUTE sp_executesql @statement = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount int OUTPUT, @ParamModificationCounter int OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT + EXECUTE sp_executesql @statement = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT SET @Error = @@ERROR IF @Error = 0 AND @CurrentRowCount IS NULL SET @CurrentRowCount = 0 IF @Error = 0 AND @CurrentModificationCounter IS NULL SET @CurrentModificationCounter = 0 diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 93e287e8..111680ac 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -5678,7 +5678,7 @@ BEGIN SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = rowcnt, @ParamModificationCounter = rowmodctr FROM sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID' END - EXECUTE sp_executesql @statement = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount int OUTPUT, @ParamModificationCounter int OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT + EXECUTE sp_executesql @statement = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT SET @Error = @@ERROR IF @Error = 0 AND @CurrentRowCount IS NULL SET @CurrentRowCount = 0 IF @Error = 0 AND @CurrentModificationCounter IS NULL SET @CurrentModificationCounter = 0 From 26c0d990b1895549540658343dc5cb610d511500 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 5 Jun 2018 18:25:01 +0200 Subject: [PATCH 038/188] Add files via upload --- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/IndexOptimize.sql b/IndexOptimize.sql index dc470397..35bc8cc2 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -1142,7 +1142,7 @@ BEGIN + ', stats.no_recompute AS NoRecompute' + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE '0' END + ' AS IsIncremental' + ', NULL AS PartitionID' - + ', NULL AS partition_number' + + ', NULL AS PartitionNumber' + ', NULL AS PartitionCount' + ', 0 AS [Order]' + ', 0 AS Selected' diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 111680ac..1dfb86c2 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -5467,7 +5467,7 @@ BEGIN + ', stats.no_recompute AS NoRecompute' + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE '0' END + ' AS IsIncremental' + ', NULL AS PartitionID' - + ', NULL AS partition_number' + + ', NULL AS PartitionNumber' + ', NULL AS PartitionCount' + ', 0 AS [Order]' + ', 0 AS Selected' From 0d1b36b920ec40bc00b30f8b5c3c2f2c5c17d9f1 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 6 Jun 2018 19:02:55 +0200 Subject: [PATCH 039/188] Add files via upload --- IndexOptimize.sql | 43 +++++++++++++++++++++++++++++++-------- MaintenanceSolution.sql | 45 ++++++++++++++++++++++++++++++++--------- 2 files changed, 71 insertions(+), 17 deletions(-) diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 35bc8cc2..aa1bcfa9 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -68,6 +68,8 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @AmazonRDS bit + DECLARE @PartitionLevelStatistics bit + DECLARE @CurrentDBID int DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -951,6 +953,12 @@ BEGIN SET @Error = @@ERROR END + ---------------------------------------------------------------------------------------------------- + --// Should statistics be updated on the partition level? //-- + ---------------------------------------------------------------------------------------------------- + + SET @PartitionLevelStatistics = CASE WHEN @PartitionLevel = 'Y' AND ((@Version >= 12.05 AND @Version < 13) OR @Version >= 13.04422 OR SERVERPROPERTY('EngineEdition') IN (5,8)) THEN 1 ELSE 0 END + ---------------------------------------------------------------------------------------------------- --// Execute commands //-- ---------------------------------------------------------------------------------------------------- @@ -1142,7 +1150,7 @@ BEGIN + ', stats.no_recompute AS NoRecompute' + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE '0' END + ' AS IsIncremental' + ', NULL AS PartitionID' - + ', NULL AS PartitionNumber' + + ', ' + CASE WHEN @PartitionLevelStatistics = 1 THEN 'dm_db_incremental_stats_properties.partition_number' ELSE 'NULL' END + ' AS PartitionNumber' + ', NULL AS PartitionCount' + ', 0 AS [Order]' + ', 0 AS Selected' @@ -1152,6 +1160,11 @@ BEGIN + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' + ' LEFT OUTER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + IF @PartitionLevelStatistics = 1 + BEGIN + SET @CurrentCommand01 = @CurrentCommand01 + ' OUTER APPLY sys.dm_db_incremental_stats_properties(stats.object_id, stats.stats_id) dm_db_incremental_stats_properties' + END + SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id)' @@ -1344,6 +1357,11 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand04 = @CurrentCommand04 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' + IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 + BEGIN + SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' + END + ELSE IF (@Version >= 10.504000 AND @Version < 11) OR @Version >= 11.03000 BEGIN SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' @@ -1476,7 +1494,8 @@ BEGIN IF @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,3,4,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,3,4,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) AND (@CurrentModificationCounter > 0 OR @OnlyModifiedStatistics = 'N' OR (@CurrentIsMemoryOptimized = 1 AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') IN (5,8)))) - AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND @CurrentPartitionNumber = @CurrentPartitionCount)) + AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1)))) + BEGIN SET @CurrentUpdateStatistics = 'Y' END @@ -1495,6 +1514,12 @@ BEGIN SET @CurrentStatisticsResample = 'Y' END + -- Incremental statistics only supports RESAMPLE + IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 + BEGIN + SET @CurrentStatisticsSample = NULL + SET @CurrentStatisticsResample = 'Y' + END -- Create index comment IF @CurrentIndexID IS NOT NULL @@ -1642,6 +1667,12 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand07 = @CurrentCommand07 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) + IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) + END + IF @CurrentStatisticsSample = 100 BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) @@ -1666,12 +1697,6 @@ BEGIN SELECT 'NORECOMPUTE' END - IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) - BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) - END - IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) BEGIN SET @CurrentUpdateStatisticsWithClause = ' WITH' @@ -1685,6 +1710,8 @@ BEGIN IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + @CurrentUpdateStatisticsWithClause + IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput07 = @Error diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 1dfb86c2..32d4c951 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -12,7 +12,7 @@ GitHub: https://github.com/olahallengren/sql-server-maintenance-solution You can contact me by e-mail at ola@hallengren.com. -Last updated 5 June, 2018. +Last updated 6 June, 2018. Ola Hallengren https://ola.hallengren.com @@ -4393,6 +4393,8 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @AmazonRDS bit + DECLARE @PartitionLevelStatistics bit + DECLARE @CurrentDBID int DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -5276,6 +5278,12 @@ BEGIN SET @Error = @@ERROR END + ---------------------------------------------------------------------------------------------------- + --// Should statistics be updated on the partition level? //-- + ---------------------------------------------------------------------------------------------------- + + SET @PartitionLevelStatistics = CASE WHEN @PartitionLevel = 'Y' AND ((@Version >= 12.05 AND @Version < 13) OR @Version >= 13.04422 OR SERVERPROPERTY('EngineEdition') IN (5,8)) THEN 1 ELSE 0 END + ---------------------------------------------------------------------------------------------------- --// Execute commands //-- ---------------------------------------------------------------------------------------------------- @@ -5467,7 +5475,7 @@ BEGIN + ', stats.no_recompute AS NoRecompute' + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE '0' END + ' AS IsIncremental' + ', NULL AS PartitionID' - + ', NULL AS PartitionNumber' + + ', ' + CASE WHEN @PartitionLevelStatistics = 1 THEN 'dm_db_incremental_stats_properties.partition_number' ELSE 'NULL' END + ' AS PartitionNumber' + ', NULL AS PartitionCount' + ', 0 AS [Order]' + ', 0 AS Selected' @@ -5477,6 +5485,11 @@ BEGIN + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' + ' LEFT OUTER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + IF @PartitionLevelStatistics = 1 + BEGIN + SET @CurrentCommand01 = @CurrentCommand01 + ' OUTER APPLY sys.dm_db_incremental_stats_properties(stats.object_id, stats.stats_id) dm_db_incremental_stats_properties' + END + SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id)' @@ -5669,6 +5682,11 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand04 = @CurrentCommand04 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' + IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 + BEGIN + SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' + END + ELSE IF (@Version >= 10.504000 AND @Version < 11) OR @Version >= 11.03000 BEGIN SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' @@ -5801,7 +5819,8 @@ BEGIN IF @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,3,4,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,3,4,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) AND (@CurrentModificationCounter > 0 OR @OnlyModifiedStatistics = 'N' OR (@CurrentIsMemoryOptimized = 1 AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') IN (5,8)))) - AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND @CurrentPartitionNumber = @CurrentPartitionCount)) + AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1)))) + BEGIN SET @CurrentUpdateStatistics = 'Y' END @@ -5820,6 +5839,12 @@ BEGIN SET @CurrentStatisticsResample = 'Y' END + -- Incremental statistics only supports RESAMPLE + IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 + BEGIN + SET @CurrentStatisticsSample = NULL + SET @CurrentStatisticsResample = 'Y' + END -- Create index comment IF @CurrentIndexID IS NOT NULL @@ -5967,6 +5992,12 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand07 = @CurrentCommand07 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) + IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) + END + IF @CurrentStatisticsSample = 100 BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) @@ -5991,12 +6022,6 @@ BEGIN SELECT 'NORECOMPUTE' END - IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) - BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) - END - IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) BEGIN SET @CurrentUpdateStatisticsWithClause = ' WITH' @@ -6010,6 +6035,8 @@ BEGIN IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + @CurrentUpdateStatisticsWithClause + IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput07 = @Error From 8ae595096f73ff3352f4bc54ee37d57e8b087ee8 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 9 Jun 2018 23:21:56 +0200 Subject: [PATCH 040/188] Add files via upload --- DatabaseBackup.sql | 13 ++++++ IndexOptimize.sql | 82 +++++++++++++++++++++++++++++----- MaintenanceSolution.sql | 97 +++++++++++++++++++++++++++++++++++------ 3 files changed, 167 insertions(+), 25 deletions(-) diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index c128664c..1bac3e20 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -58,6 +58,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @FileExtensionFull nvarchar(max) = NULL, @FileExtensionDiff nvarchar(max) = NULL, @FileExtensionLog nvarchar(max) = NULL, +@Init nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -292,6 +293,7 @@ BEGIN SET @Parameters = @Parameters + ', @FileExtensionFull = ' + ISNULL('''' + REPLACE(@FileExtensionFull,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @FileExtensionDiff = ' + ISNULL('''' + REPLACE(@FileExtensionDiff,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -1278,6 +1280,13 @@ BEGIN SET @Error = @@ERROR END + IF @Init NOT IN('Y','N') OR @Init IS NULL OR (@Init = 'Y' AND @BackupType = 'LOG') OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + BEGIN + SET @ErrorMessage = 'The value for the parameter @Init is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -2214,6 +2223,7 @@ BEGIN IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', COPY_ONLY' IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 = @CurrentCommand03 + ', NORECOVERY' + IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', INIT' IF @BlockSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar) IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@MaxTransferSize AS nvarchar) @@ -2264,6 +2274,7 @@ BEGIN IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @buffercount = ' + CAST(@BufferCount AS nvarchar) IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @maxtransfersize = ' + CAST(@MaxTransferSize AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @threads = ' + CAST(@Threads AS nvarchar) + IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @init = 1' IF @Throttle IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @throttle = ' + CAST(@Throttle AS nvarchar) IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' @@ -2313,6 +2324,7 @@ BEGIN IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 = @CurrentCommand03 + ', DIFFERENTIAL' IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', COPY_ONLY' IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 = @CurrentCommand03 + ', NORECOVERY' + IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', INIT' IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', COMPRESSION = ' + CAST(@CompressionLevel AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', THREADCOUNT = ' + CAST(@Threads AS nvarchar) IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@MaxTransferSize AS nvarchar) @@ -2349,6 +2361,7 @@ BEGIN SET @CurrentCommand03 = @CurrentCommand03 + ', @copyonly = ' + CASE WHEN @CopyOnly = 'Y' THEN '1' WHEN @CopyOnly = 'N' THEN '0' END IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @threads = ' + CAST(@Threads AS nvarchar) + IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @overwrite = 1' IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @encryptiontype = N''' + CASE diff --git a/IndexOptimize.sql b/IndexOptimize.sql index aa1bcfa9..25ad8824 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -33,6 +33,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @Delay int = NULL, @WaitAtLowPriorityMaxDuration int = NULL, @WaitAtLowPriorityAbortAfterWait nvarchar(max) = NULL, +@Resumable nvarchar(max) = 'N', @AvailabilityGroups nvarchar(max) = NULL, @LockTimeout int = NULL, @LogToTable nvarchar(max) = 'N', @@ -121,12 +122,15 @@ BEGIN DECLARE @CurrentIsNewLOB bit DECLARE @CurrentIsFileStream bit DECLARE @CurrentIsColumnStore bit + DECLARE @CurrentIsComputed bit + DECLARE @CurrentIsTimestamp bit DECLARE @CurrentAllowPageLocks bit DECLARE @CurrentNoRecompute bit DECLARE @CurrentIsIncremental bit DECLARE @CurrentRowCount bigint DECLARE @CurrentModificationCounter bigint DECLARE @CurrentOnReadOnlyFileGroup bit + DECLARE @CurrentResumableIndexOperation bit DECLARE @CurrentFragmentationLevel float DECLARE @CurrentPageCount bigint DECLARE @CurrentFragmentationGroup nvarchar(max) @@ -170,7 +174,10 @@ BEGIN IsNewLOB bit, IsFileStream bit, IsColumnStore bit, + IsComputed bit, + IsTimestamp bit, OnReadOnlyFileGroup bit, + ResumableIndexOperation bit, StatisticsID int, StatisticsName nvarchar(max), [NoRecompute] bit, @@ -276,6 +283,7 @@ BEGIN SET @Parameters = @Parameters + ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @WaitAtLowPriorityAbortAfterWait = ' + ISNULL('''' + REPLACE(@WaitAtLowPriorityAbortAfterWait,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Resumable = ' + ISNULL('''' + REPLACE(@Resumable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -871,6 +879,20 @@ BEGIN SET @Error = @@ERROR END + IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL OR (@Resumable = 'Y' AND NOT (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8))) + BEGIN + SET @ErrorMessage = 'The value for the parameter @Resumable is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @Resumable = 'Y' AND @SortInTempdb = 'Y' + BEGIN + SET @ErrorMessage = 'You can only specify one of the parameters @Resumable and @SortInTempdb.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LockTimeout < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1068,7 +1090,7 @@ BEGIN BEGIN SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + 'USE ' + QUOTENAME(@CurrentDatabaseName) + ';' - + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, OnReadOnlyFileGroup, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, IsComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + ' FROM (' IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') @@ -1093,10 +1115,16 @@ BEGIN + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] IN(5,6)) THEN 1 ELSE 0 END AS IsColumnStore' + + ', CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns INNER JOIN sys.columns columns ON index_columns.object_id = columns.object_id AND index_columns.column_id = columns.column_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND index_columns.object_id = indexes.object_id AND index_columns.index_id = indexes.index_id) THEN 1 ELSE 0 END AS IsComputed' + + + ', CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns INNER JOIN sys.columns columns ON index_columns.[object_id] = columns.[object_id] AND index_columns.column_id = columns.column_id INNER JOIN sys.types types ON columns.system_type_id = types.system_type_id WHERE index_columns.[object_id] = objects.object_id AND index_columns.index_id = indexes.index_id AND types.[name] = ''timestamp'') THEN 1 ELSE 0 END AS IsTimestamp' + + ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON indexes.data_space_id = destination_data_spaces.partition_scheme_id INNER JOIN sys.filegroups filegroups ON destination_data_spaces.data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND indexes2.[object_id] = indexes.[object_id] AND indexes2.[index_id] = indexes.index_id' + CASE WHEN @PartitionLevel = 'Y' THEN ' AND destination_data_spaces.destination_id = partitions.partition_number' ELSE '' END + ') THEN 1' + ' WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.filegroups filegroups ON indexes.data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND indexes.[object_id] = indexes2.[object_id] AND indexes.[index_id] = indexes2.index_id) THEN 1' + ' WHEN indexes.[type] = 1 AND EXISTS (SELECT * FROM sys.tables tables INNER JOIN sys.filegroups filegroups ON tables.lob_data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND tables.[object_id] = objects.[object_id]) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' + + ', ' + CASE WHEN @Version >= 14 THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_resumable_operations index_resumable_operations WHERE state_desc = ''PAUSED'' AND index_resumable_operations.object_id = indexes.object_id AND index_resumable_operations.index_id = indexes.index_id AND (index_resumable_operations.partition_number = partitions.partition_number OR index_resumable_operations.partition_number IS NULL)) THEN 1 ELSE 0 END' ELSE '0' END + ' AS ResumableIndexOperation' + + ', stats.stats_id AS StatisticsID' + ', stats.name AS StatisticsName' + ', stats.no_recompute AS NoRecompute' @@ -1144,7 +1172,10 @@ BEGIN + ', NULL AS IsNewLOB' + ', NULL AS IsFileStream' + ', NULL AS IsColumnStore' + + ', NULL AS IsComputed' + + ', NULL AS IsTimestamp' + ', NULL AS OnReadOnlyFileGroup' + + ', NULL AS ResumableIndexOperation' + ', stats.stats_id AS StatisticsID' + ', stats.name AS StatisticsName' + ', stats.no_recompute AS NoRecompute' @@ -1172,7 +1203,7 @@ BEGIN SET @CurrentCommand01 = @CurrentCommand01 + ') IndexesStatistics' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, OnReadOnlyFileGroup, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, IsComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) EXECUTE sp_executesql @statement = @CurrentCommand01 SET @Error = @@ERROR IF @Error <> 0 @@ -1219,7 +1250,7 @@ BEGIN END; WITH tmpIndexesStatistics AS ( - SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, SchemaName ASC, ObjectName ASC, CASE WHEN IndexType IS NULL THEN 1 ELSE 0 END ASC, IndexType ASC, IndexName ASC, StatisticsName ASC, PartitionNumber ASC) AS RowNumber + SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY ISNULL(ResumableIndexOperation,0) DESC, StartPosition ASC, SchemaName ASC, ObjectName ASC, CASE WHEN IndexType IS NULL THEN 1 ELSE 0 END ASC, IndexType ASC, IndexName ASC, StatisticsName ASC, PartitionNumber ASC) AS RowNumber FROM @tmpIndexesStatistics tmpIndexesStatistics WHERE Selected = 1 ) @@ -1273,7 +1304,10 @@ BEGIN @CurrentIsNewLOB = IsNewLOB, @CurrentIsFileStream = IsFileStream, @CurrentIsColumnStore = IsColumnStore, + @CurrentIsComputed = IsComputed, + @CurrentIsTimestamp = IsTimestamp, @CurrentOnReadOnlyFileGroup = OnReadOnlyFileGroup, + @CurrentResumableIndexOperation = ResumableIndexOperation, @CurrentStatisticsID = StatisticsID, @CurrentStatisticsName = StatisticsName, @CurrentNoRecompute = [NoRecompute], @@ -1458,6 +1492,7 @@ BEGIN AND EXISTS(SELECT * FROM @ActionsPreferred) AND (@CurrentPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (@CurrentPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL) + AND @CurrentResumableIndexOperation = 0 BEGIN IF EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) BEGIN @@ -1479,6 +1514,11 @@ BEGIN END END + IF @CurrentResumableIndexOperation = 1 + BEGIN + SET @CurrentAction = 'INDEX_REBUILD_ONLINE' + END + -- Workaround for limitation in SQL Server, http://support.microsoft.com/kb/2292737 IF @CurrentIndexID IS NOT NULL BEGIN @@ -1530,6 +1570,8 @@ BEGIN SET @CurrentComment06 = @CurrentComment06 + 'NewLOB: ' + CASE WHEN @CurrentIsNewLOB = 1 THEN 'Yes' WHEN @CurrentIsNewLOB = 0 THEN 'No' ELSE 'N/A' END + ', ' SET @CurrentComment06 = @CurrentComment06 + 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Version >= 11 SET @CurrentComment06 = @CurrentComment06 + 'ColumnStore: ' + CASE WHEN @CurrentIsColumnStore = 1 THEN 'Yes' WHEN @CurrentIsColumnStore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 = @CurrentComment06 + 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 = @CurrentComment06 + 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' SET @CurrentComment06 = @CurrentComment06 + 'AllowPageLocks: ' + CASE WHEN @CurrentAllowPageLocks = 1 THEN 'Yes' WHEN @CurrentAllowPageLocks = 0 THEN 'No' ELSE 'N/A' END + ', ' SET @CurrentComment06 = @CurrentComment06 + 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar),'N/A') + ', ' SET @CurrentComment06 = @CurrentComment06 + 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar),'N/A') @@ -1569,29 +1611,30 @@ BEGIN SET @CurrentCommand06 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand06 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand06 = @CurrentCommand06 + 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') SET @CurrentCommand06 = @CurrentCommand06 + ' REBUILD' - IF @CurrentAction IN('INDEX_REORGANIZE') SET @CurrentCommand06 = @CurrentCommand06 + ' REORGANIZE' - IF @CurrentIsPartition = 1 SET @CurrentCommand06 = @CurrentCommand06 + ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) + IF @CurrentResumableIndexOperation = 1 SET @CurrentCommand06 = @CurrentCommand06 + ' RESUME' + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' REBUILD' + IF @CurrentAction IN('INDEX_REORGANIZE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' REORGANIZE' + IF @CurrentIsPartition = 1 AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'SORT_IN_TEMPDB = ON' END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'N' AND @CurrentIndexType IN(1,2,3,4) + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'N' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'SORT_IN_TEMPDB = OFF' END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentAction = 'INDEX_REBUILD_ONLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) + IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'ONLINE = OFF' @@ -1603,18 +1646,30 @@ BEGIN SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @FillFactor IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @FillFactor IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'FILLFACTOR = ' + CAST(@FillFactor AS nvarchar) END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex = 'Y' AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex = 'Y' AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'PAD_INDEX = ON' END + IF (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT CASE WHEN @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsTimestamp = 0 THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END + END + + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsTimestamp = 0 AND @TimeLimit IS NOT NULL AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'MAX_DURATION = ' + CAST(DATEDIFF(MINUTE,GETDATE(),DATEADD(ss,@TimeLimit,@StartTime)) AS nvarchar(max)) + END + IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) @@ -1769,12 +1824,15 @@ BEGIN SET @CurrentIsNewLOB = NULL SET @CurrentIsFileStream = NULL SET @CurrentIsColumnStore = NULL + SET @CurrentIsComputed = NULL + SET @CurrentIsTimestamp = NULL SET @CurrentAllowPageLocks = NULL SET @CurrentNoRecompute = NULL SET @CurrentIsIncremental = NULL SET @CurrentRowCount = NULL SET @CurrentModificationCounter = NULL SET @CurrentOnReadOnlyFileGroup = NULL + SET @CurrentResumableIndexOperation = NULL SET @CurrentFragmentationLevel = NULL SET @CurrentPageCount = NULL SET @CurrentFragmentationGroup = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 32d4c951..68c31b23 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -12,7 +12,7 @@ GitHub: https://github.com/olahallengren/sql-server-maintenance-solution You can contact me by e-mail at ola@hallengren.com. -Last updated 6 June, 2018. +Last updated 9 June, 2018. Ola Hallengren https://ola.hallengren.com @@ -351,6 +351,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @FileExtensionFull nvarchar(max) = NULL, @FileExtensionDiff nvarchar(max) = NULL, @FileExtensionLog nvarchar(max) = NULL, +@Init nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -585,6 +586,7 @@ BEGIN SET @Parameters = @Parameters + ', @FileExtensionFull = ' + ISNULL('''' + REPLACE(@FileExtensionFull,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @FileExtensionDiff = ' + ISNULL('''' + REPLACE(@FileExtensionDiff,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -1571,6 +1573,13 @@ BEGIN SET @Error = @@ERROR END + IF @Init NOT IN('Y','N') OR @Init IS NULL OR (@Init = 'Y' AND @BackupType = 'LOG') OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + BEGIN + SET @ErrorMessage = 'The value for the parameter @Init is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -2507,6 +2516,7 @@ BEGIN IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', COPY_ONLY' IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 = @CurrentCommand03 + ', NORECOVERY' + IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', INIT' IF @BlockSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar) IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@MaxTransferSize AS nvarchar) @@ -2557,6 +2567,7 @@ BEGIN IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @buffercount = ' + CAST(@BufferCount AS nvarchar) IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @maxtransfersize = ' + CAST(@MaxTransferSize AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @threads = ' + CAST(@Threads AS nvarchar) + IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @init = 1' IF @Throttle IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @throttle = ' + CAST(@Throttle AS nvarchar) IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' @@ -2606,6 +2617,7 @@ BEGIN IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 = @CurrentCommand03 + ', DIFFERENTIAL' IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', COPY_ONLY' IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 = @CurrentCommand03 + ', NORECOVERY' + IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', INIT' IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', COMPRESSION = ' + CAST(@CompressionLevel AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', THREADCOUNT = ' + CAST(@Threads AS nvarchar) IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@MaxTransferSize AS nvarchar) @@ -2642,6 +2654,7 @@ BEGIN SET @CurrentCommand03 = @CurrentCommand03 + ', @copyonly = ' + CASE WHEN @CopyOnly = 'Y' THEN '1' WHEN @CopyOnly = 'N' THEN '0' END IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @threads = ' + CAST(@Threads AS nvarchar) + IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @overwrite = 1' IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @encryptiontype = N''' + CASE @@ -4358,6 +4371,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @Delay int = NULL, @WaitAtLowPriorityMaxDuration int = NULL, @WaitAtLowPriorityAbortAfterWait nvarchar(max) = NULL, +@Resumable nvarchar(max) = 'N', @AvailabilityGroups nvarchar(max) = NULL, @LockTimeout int = NULL, @LogToTable nvarchar(max) = 'N', @@ -4446,12 +4460,15 @@ BEGIN DECLARE @CurrentIsNewLOB bit DECLARE @CurrentIsFileStream bit DECLARE @CurrentIsColumnStore bit + DECLARE @CurrentIsComputed bit + DECLARE @CurrentIsTimestamp bit DECLARE @CurrentAllowPageLocks bit DECLARE @CurrentNoRecompute bit DECLARE @CurrentIsIncremental bit DECLARE @CurrentRowCount bigint DECLARE @CurrentModificationCounter bigint DECLARE @CurrentOnReadOnlyFileGroup bit + DECLARE @CurrentResumableIndexOperation bit DECLARE @CurrentFragmentationLevel float DECLARE @CurrentPageCount bigint DECLARE @CurrentFragmentationGroup nvarchar(max) @@ -4495,7 +4512,10 @@ BEGIN IsNewLOB bit, IsFileStream bit, IsColumnStore bit, + IsComputed bit, + IsTimestamp bit, OnReadOnlyFileGroup bit, + ResumableIndexOperation bit, StatisticsID int, StatisticsName nvarchar(max), [NoRecompute] bit, @@ -4601,6 +4621,7 @@ BEGIN SET @Parameters = @Parameters + ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @WaitAtLowPriorityAbortAfterWait = ' + ISNULL('''' + REPLACE(@WaitAtLowPriorityAbortAfterWait,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Resumable = ' + ISNULL('''' + REPLACE(@Resumable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -5196,6 +5217,20 @@ BEGIN SET @Error = @@ERROR END + IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL OR (@Resumable = 'Y' AND NOT (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8))) + BEGIN + SET @ErrorMessage = 'The value for the parameter @Resumable is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @Resumable = 'Y' AND @SortInTempdb = 'Y' + BEGIN + SET @ErrorMessage = 'You can only specify one of the parameters @Resumable and @SortInTempdb.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LockTimeout < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -5393,7 +5428,7 @@ BEGIN BEGIN SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + 'USE ' + QUOTENAME(@CurrentDatabaseName) + ';' - + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, OnReadOnlyFileGroup, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, IsComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + ' FROM (' IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') @@ -5418,10 +5453,16 @@ BEGIN + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] IN(5,6)) THEN 1 ELSE 0 END AS IsColumnStore' + + ', CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns INNER JOIN sys.columns columns ON index_columns.object_id = columns.object_id AND index_columns.column_id = columns.column_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND index_columns.object_id = indexes.object_id AND index_columns.index_id = indexes.index_id) THEN 1 ELSE 0 END AS IsComputed' + + + ', CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns INNER JOIN sys.columns columns ON index_columns.[object_id] = columns.[object_id] AND index_columns.column_id = columns.column_id INNER JOIN sys.types types ON columns.system_type_id = types.system_type_id WHERE index_columns.[object_id] = objects.object_id AND index_columns.index_id = indexes.index_id AND types.[name] = ''timestamp'') THEN 1 ELSE 0 END AS IsTimestamp' + + ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON indexes.data_space_id = destination_data_spaces.partition_scheme_id INNER JOIN sys.filegroups filegroups ON destination_data_spaces.data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND indexes2.[object_id] = indexes.[object_id] AND indexes2.[index_id] = indexes.index_id' + CASE WHEN @PartitionLevel = 'Y' THEN ' AND destination_data_spaces.destination_id = partitions.partition_number' ELSE '' END + ') THEN 1' + ' WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.filegroups filegroups ON indexes.data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND indexes.[object_id] = indexes2.[object_id] AND indexes.[index_id] = indexes2.index_id) THEN 1' + ' WHEN indexes.[type] = 1 AND EXISTS (SELECT * FROM sys.tables tables INNER JOIN sys.filegroups filegroups ON tables.lob_data_space_id = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND tables.[object_id] = objects.[object_id]) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' + + ', ' + CASE WHEN @Version >= 14 THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_resumable_operations index_resumable_operations WHERE state_desc = ''PAUSED'' AND index_resumable_operations.object_id = indexes.object_id AND index_resumable_operations.index_id = indexes.index_id AND (index_resumable_operations.partition_number = partitions.partition_number OR index_resumable_operations.partition_number IS NULL)) THEN 1 ELSE 0 END' ELSE '0' END + ' AS ResumableIndexOperation' + + ', stats.stats_id AS StatisticsID' + ', stats.name AS StatisticsName' + ', stats.no_recompute AS NoRecompute' @@ -5469,7 +5510,10 @@ BEGIN + ', NULL AS IsNewLOB' + ', NULL AS IsFileStream' + ', NULL AS IsColumnStore' + + ', NULL AS IsComputed' + + ', NULL AS IsTimestamp' + ', NULL AS OnReadOnlyFileGroup' + + ', NULL AS ResumableIndexOperation' + ', stats.stats_id AS StatisticsID' + ', stats.name AS StatisticsName' + ', stats.no_recompute AS NoRecompute' @@ -5497,7 +5541,7 @@ BEGIN SET @CurrentCommand01 = @CurrentCommand01 + ') IndexesStatistics' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, OnReadOnlyFileGroup, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, IsComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) EXECUTE sp_executesql @statement = @CurrentCommand01 SET @Error = @@ERROR IF @Error <> 0 @@ -5544,7 +5588,7 @@ BEGIN END; WITH tmpIndexesStatistics AS ( - SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, SchemaName ASC, ObjectName ASC, CASE WHEN IndexType IS NULL THEN 1 ELSE 0 END ASC, IndexType ASC, IndexName ASC, StatisticsName ASC, PartitionNumber ASC) AS RowNumber + SELECT SchemaName, ObjectName, [Order], ROW_NUMBER() OVER (ORDER BY ISNULL(ResumableIndexOperation,0) DESC, StartPosition ASC, SchemaName ASC, ObjectName ASC, CASE WHEN IndexType IS NULL THEN 1 ELSE 0 END ASC, IndexType ASC, IndexName ASC, StatisticsName ASC, PartitionNumber ASC) AS RowNumber FROM @tmpIndexesStatistics tmpIndexesStatistics WHERE Selected = 1 ) @@ -5598,7 +5642,10 @@ BEGIN @CurrentIsNewLOB = IsNewLOB, @CurrentIsFileStream = IsFileStream, @CurrentIsColumnStore = IsColumnStore, + @CurrentIsComputed = IsComputed, + @CurrentIsTimestamp = IsTimestamp, @CurrentOnReadOnlyFileGroup = OnReadOnlyFileGroup, + @CurrentResumableIndexOperation = ResumableIndexOperation, @CurrentStatisticsID = StatisticsID, @CurrentStatisticsName = StatisticsName, @CurrentNoRecompute = [NoRecompute], @@ -5783,6 +5830,7 @@ BEGIN AND EXISTS(SELECT * FROM @ActionsPreferred) AND (@CurrentPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (@CurrentPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL) + AND @CurrentResumableIndexOperation = 0 BEGIN IF EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) BEGIN @@ -5804,6 +5852,11 @@ BEGIN END END + IF @CurrentResumableIndexOperation = 1 + BEGIN + SET @CurrentAction = 'INDEX_REBUILD_ONLINE' + END + -- Workaround for limitation in SQL Server, http://support.microsoft.com/kb/2292737 IF @CurrentIndexID IS NOT NULL BEGIN @@ -5855,6 +5908,8 @@ BEGIN SET @CurrentComment06 = @CurrentComment06 + 'NewLOB: ' + CASE WHEN @CurrentIsNewLOB = 1 THEN 'Yes' WHEN @CurrentIsNewLOB = 0 THEN 'No' ELSE 'N/A' END + ', ' SET @CurrentComment06 = @CurrentComment06 + 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Version >= 11 SET @CurrentComment06 = @CurrentComment06 + 'ColumnStore: ' + CASE WHEN @CurrentIsColumnStore = 1 THEN 'Yes' WHEN @CurrentIsColumnStore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 = @CurrentComment06 + 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 = @CurrentComment06 + 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' SET @CurrentComment06 = @CurrentComment06 + 'AllowPageLocks: ' + CASE WHEN @CurrentAllowPageLocks = 1 THEN 'Yes' WHEN @CurrentAllowPageLocks = 0 THEN 'No' ELSE 'N/A' END + ', ' SET @CurrentComment06 = @CurrentComment06 + 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar),'N/A') + ', ' SET @CurrentComment06 = @CurrentComment06 + 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar),'N/A') @@ -5894,29 +5949,30 @@ BEGIN SET @CurrentCommand06 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand06 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand06 = @CurrentCommand06 + 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') SET @CurrentCommand06 = @CurrentCommand06 + ' REBUILD' - IF @CurrentAction IN('INDEX_REORGANIZE') SET @CurrentCommand06 = @CurrentCommand06 + ' REORGANIZE' - IF @CurrentIsPartition = 1 SET @CurrentCommand06 = @CurrentCommand06 + ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) + IF @CurrentResumableIndexOperation = 1 SET @CurrentCommand06 = @CurrentCommand06 + ' RESUME' + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' REBUILD' + IF @CurrentAction IN('INDEX_REORGANIZE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' REORGANIZE' + IF @CurrentIsPartition = 1 AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'SORT_IN_TEMPDB = ON' END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'N' AND @CurrentIndexType IN(1,2,3,4) + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'N' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'SORT_IN_TEMPDB = OFF' END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentAction = 'INDEX_REBUILD_ONLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) + IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'ONLINE = OFF' @@ -5928,18 +5984,30 @@ BEGIN SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @FillFactor IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @FillFactor IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'FILLFACTOR = ' + CAST(@FillFactor AS nvarchar) END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex = 'Y' AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex = 'Y' AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'PAD_INDEX = ON' END + IF (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT CASE WHEN @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsTimestamp = 0 THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END + END + + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsTimestamp = 0 AND @TimeLimit IS NOT NULL AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'MAX_DURATION = ' + CAST(DATEDIFF(MINUTE,GETDATE(),DATEADD(ss,@TimeLimit,@StartTime)) AS nvarchar(max)) + END + IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) @@ -6094,12 +6162,15 @@ BEGIN SET @CurrentIsNewLOB = NULL SET @CurrentIsFileStream = NULL SET @CurrentIsColumnStore = NULL + SET @CurrentIsComputed = NULL + SET @CurrentIsTimestamp = NULL SET @CurrentAllowPageLocks = NULL SET @CurrentNoRecompute = NULL SET @CurrentIsIncremental = NULL SET @CurrentRowCount = NULL SET @CurrentModificationCounter = NULL SET @CurrentOnReadOnlyFileGroup = NULL + SET @CurrentResumableIndexOperation = NULL SET @CurrentFragmentationLevel = NULL SET @CurrentPageCount = NULL SET @CurrentFragmentationGroup = NULL From a37f114eed3f3f7e926362f03677653f748facbc Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 10 Jun 2018 14:30:38 +0200 Subject: [PATCH 041/188] Add files via upload --- CommandExecute.sql | 1 + DatabaseBackup.sql | 1 + DatabaseIntegrityCheck.sql | 1 + IndexOptimize.sql | 1 + MaintenanceSolution.sql | 10 +++++++--- 5 files changed, 11 insertions(+), 3 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 947e859b..ea2fa5ad 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -33,6 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- + --// Version: 2018-06-10 14:25:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 1bac3e20..b58ed518 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -70,6 +70,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- + --// Version: 2018-06-10 14:25:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 05cc27f7..f3a25720 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -33,6 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- + --// Version: 2018-06-10 14:25:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 25ad8824..a8811db5 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -47,6 +47,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- + --// Version: 2018-06-10 14:25:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 68c31b23..741b957c 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -6,13 +6,13 @@ Backup: https://ola.hallengren.com/sql-server-backup.html Integrity Check: https://ola.hallengren.com/sql-server-integrity-check.html Index and Statistics Maintenance: https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html -The solution is free: https://ola.hallengren.com/license.html +License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -You can contact me by e-mail at ola@hallengren.com. +Version: 2018-06-10 14:25:42 -Last updated 9 June, 2018. +You can contact me by e-mail at ola@hallengren.com. Ola Hallengren https://ola.hallengren.com @@ -117,6 +117,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- + --// Version: 2018-06-10 14:25:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -363,6 +364,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- + --// Version: 2018-06-10 14:25:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3043,6 +3045,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- + --// Version: 2018-06-10 14:25:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4385,6 +4388,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- + --// Version: 2018-06-10 14:25:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From d4cb0fa42e894ef2138ff08bcd2ad95148635cc5 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 10 Jun 2018 16:12:48 +0200 Subject: [PATCH 042/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 7 ++++++- DatabaseIntegrityCheck.sql | 7 ++++++- IndexOptimize.sql | 7 ++++++- MaintenanceSolution.sql | 25 ++++++++++++++++++++----- 5 files changed, 39 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index ea2fa5ad..227cd6b2 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -33,7 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 14:25:42 //-- + --// Version: 2018-06-10 16:09:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index b58ed518..b81b7af1 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -70,7 +70,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 14:25:42 //-- + --// Version: 2018-06-10 16:09:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -83,6 +83,7 @@ BEGIN DECLARE @StartTime datetime DECLARE @SchemaName nvarchar(max) DECLARE @ObjectName nvarchar(max) + DECLARE @VersionTimestamp nvarchar(max) DECLARE @Parameters nvarchar(max) DECLARE @Version numeric(18,10) @@ -244,6 +245,7 @@ BEGIN SET @StartTime = GETDATE() SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) SET @ObjectName = OBJECT_NAME(@@PROCID) + SET @VersionTimestamp = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL') @@ -320,6 +322,9 @@ BEGIN SET @StartMessage = REPLACE(@StartMessage,'%','%%') RAISERROR(@StartMessage,10,1) WITH NOWAIT + SET @StartMessage = 'Version: ' + @VersionTimestamp + RAISERROR(@StartMessage,10,1) WITH NOWAIT + SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@StartMessage,10,1) WITH NOWAIT diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index f3a25720..36f9c923 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -33,7 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 14:25:42 //-- + --// Version: 2018-06-10 16:09:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -46,6 +46,7 @@ BEGIN DECLARE @StartTime datetime DECLARE @SchemaName nvarchar(max) DECLARE @ObjectName nvarchar(max) + DECLARE @VersionTimestamp nvarchar(max) DECLARE @Parameters nvarchar(max) DECLARE @Version numeric(18,10) @@ -186,6 +187,7 @@ BEGIN SET @StartTime = GETDATE() SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) SET @ObjectName = OBJECT_NAME(@@PROCID) + SET @VersionTimestamp = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @CheckCommands = ' + ISNULL('''' + REPLACE(@CheckCommands,'''','''''') + '''','NULL') @@ -225,6 +227,9 @@ BEGIN SET @StartMessage = REPLACE(@StartMessage,'%','%%') RAISERROR(@StartMessage,10,1) WITH NOWAIT + SET @StartMessage = 'Version: ' + @VersionTimestamp + RAISERROR(@StartMessage,10,1) WITH NOWAIT + SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@StartMessage,10,1) WITH NOWAIT diff --git a/IndexOptimize.sql b/IndexOptimize.sql index a8811db5..f85e5873 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -47,7 +47,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 14:25:42 //-- + --// Version: 2018-06-10 16:09:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -64,6 +64,7 @@ BEGIN DECLARE @StartTime datetime DECLARE @SchemaName nvarchar(max) DECLARE @ObjectName nvarchar(max) + DECLARE @VersionTimestamp nvarchar(max) DECLARE @Parameters nvarchar(max) DECLARE @Version numeric(18,10) @@ -259,6 +260,7 @@ BEGIN SET @StartTime = GETDATE() SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) SET @ObjectName = OBJECT_NAME(@@PROCID) + SET @VersionTimestamp = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @FragmentationLow = ' + ISNULL('''' + REPLACE(@FragmentationLow,'''','''''') + '''','NULL') @@ -312,6 +314,9 @@ BEGIN SET @StartMessage = REPLACE(@StartMessage,'%','%%') RAISERROR(@StartMessage,10,1) WITH NOWAIT + SET @StartMessage = 'Version: ' + @VersionTimestamp + RAISERROR(@StartMessage,10,1) WITH NOWAIT + SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@StartMessage,10,1) WITH NOWAIT diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 741b957c..476fd47e 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-06-10 14:25:42 +Version: 2018-06-10 16:09:01 You can contact me by e-mail at ola@hallengren.com. @@ -117,7 +117,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 14:25:42 //-- + --// Version: 2018-06-10 16:09:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -364,7 +364,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 14:25:42 //-- + --// Version: 2018-06-10 16:09:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -377,6 +377,7 @@ BEGIN DECLARE @StartTime datetime DECLARE @SchemaName nvarchar(max) DECLARE @ObjectName nvarchar(max) + DECLARE @VersionTimestamp nvarchar(max) DECLARE @Parameters nvarchar(max) DECLARE @Version numeric(18,10) @@ -538,6 +539,7 @@ BEGIN SET @StartTime = GETDATE() SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) SET @ObjectName = OBJECT_NAME(@@PROCID) + SET @VersionTimestamp = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL') @@ -614,6 +616,9 @@ BEGIN SET @StartMessage = REPLACE(@StartMessage,'%','%%') RAISERROR(@StartMessage,10,1) WITH NOWAIT + SET @StartMessage = 'Version: ' + @VersionTimestamp + RAISERROR(@StartMessage,10,1) WITH NOWAIT + SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@StartMessage,10,1) WITH NOWAIT @@ -3045,7 +3050,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 14:25:42 //-- + --// Version: 2018-06-10 16:09:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3058,6 +3063,7 @@ BEGIN DECLARE @StartTime datetime DECLARE @SchemaName nvarchar(max) DECLARE @ObjectName nvarchar(max) + DECLARE @VersionTimestamp nvarchar(max) DECLARE @Parameters nvarchar(max) DECLARE @Version numeric(18,10) @@ -3198,6 +3204,7 @@ BEGIN SET @StartTime = GETDATE() SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) SET @ObjectName = OBJECT_NAME(@@PROCID) + SET @VersionTimestamp = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @CheckCommands = ' + ISNULL('''' + REPLACE(@CheckCommands,'''','''''') + '''','NULL') @@ -3237,6 +3244,9 @@ BEGIN SET @StartMessage = REPLACE(@StartMessage,'%','%%') RAISERROR(@StartMessage,10,1) WITH NOWAIT + SET @StartMessage = 'Version: ' + @VersionTimestamp + RAISERROR(@StartMessage,10,1) WITH NOWAIT + SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@StartMessage,10,1) WITH NOWAIT @@ -4388,7 +4398,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 14:25:42 //-- + --// Version: 2018-06-10 16:09:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4405,6 +4415,7 @@ BEGIN DECLARE @StartTime datetime DECLARE @SchemaName nvarchar(max) DECLARE @ObjectName nvarchar(max) + DECLARE @VersionTimestamp nvarchar(max) DECLARE @Parameters nvarchar(max) DECLARE @Version numeric(18,10) @@ -4600,6 +4611,7 @@ BEGIN SET @StartTime = GETDATE() SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) SET @ObjectName = OBJECT_NAME(@@PROCID) + SET @VersionTimestamp = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @FragmentationLow = ' + ISNULL('''' + REPLACE(@FragmentationLow,'''','''''') + '''','NULL') @@ -4653,6 +4665,9 @@ BEGIN SET @StartMessage = REPLACE(@StartMessage,'%','%%') RAISERROR(@StartMessage,10,1) WITH NOWAIT + SET @StartMessage = 'Version: ' + @VersionTimestamp + RAISERROR(@StartMessage,10,1) WITH NOWAIT + SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@StartMessage,10,1) WITH NOWAIT From 14cc7d5b60a16edf6dcc6889f53dff47117f7648 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 11 Jun 2018 10:57:11 +0200 Subject: [PATCH 043/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 8 ++++---- MaintenanceSolution.sql | 16 ++++++++-------- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 227cd6b2..a4710463 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -33,7 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 16:09:01 //-- + --// Version: 2018-06-11 10:53:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index b81b7af1..ec005c7c 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -70,7 +70,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 16:09:01 //-- + --// Version: 2018-06-11 10:53:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 36f9c923..1bfd1acd 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -33,7 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 16:09:01 //-- + --// Version: 2018-06-11 10:53:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index f85e5873..07a9c23d 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -47,7 +47,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 16:09:01 //-- + --// Version: 2018-06-11 10:53:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1664,13 +1664,13 @@ BEGIN SELECT 'PAD_INDEX = ON' END - IF (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND @CurrentResumableIndexOperation = 0 + IF (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT CASE WHEN @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsTimestamp = 0 THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END + SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsTimestamp = 0 THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END END - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsTimestamp = 0 AND @TimeLimit IS NOT NULL AND @CurrentResumableIndexOperation = 0 + IF (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsTimestamp = 0 AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'MAX_DURATION = ' + CAST(DATEDIFF(MINUTE,GETDATE(),DATEADD(ss,@TimeLimit,@StartTime)) AS nvarchar(max)) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 476fd47e..345ddd51 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-06-10 16:09:01 +Version: 2018-06-11 10:53:52 You can contact me by e-mail at ola@hallengren.com. @@ -117,7 +117,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 16:09:01 //-- + --// Version: 2018-06-11 10:53:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -364,7 +364,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 16:09:01 //-- + --// Version: 2018-06-11 10:53:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3050,7 +3050,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 16:09:01 //-- + --// Version: 2018-06-11 10:53:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4398,7 +4398,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-10 16:09:01 //-- + --// Version: 2018-06-11 10:53:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6015,13 +6015,13 @@ BEGIN SELECT 'PAD_INDEX = ON' END - IF (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND @CurrentResumableIndexOperation = 0 + IF (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT CASE WHEN @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsTimestamp = 0 THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END + SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsTimestamp = 0 THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END END - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsTimestamp = 0 AND @TimeLimit IS NOT NULL AND @CurrentResumableIndexOperation = 0 + IF (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsTimestamp = 0 AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'MAX_DURATION = ' + CAST(DATEDIFF(MINUTE,GETDATE(),DATEADD(ss,@TimeLimit,@StartTime)) AS nvarchar(max)) From dadbe69c8c32b46df900b4e17507a09d2c8147a2 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 11 Jun 2018 19:29:39 +0200 Subject: [PATCH 044/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 10 +++++++++- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 20 ++++++++++++++------ 5 files changed, 26 insertions(+), 10 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index a4710463..09f9641d 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -33,7 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 10:53:52 //-- + --// Version: 2018-06-11 19:25:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index ec005c7c..11aecd18 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -70,7 +70,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 10:53:52 //-- + --// Version: 2018-06-11 19:25:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1640,6 +1640,14 @@ BEGIN IF @@SERVICENAME IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}','') IF @Description IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}','') + IF @Directory IS NULL AND @MirrorDirectory IS NULL AND @URL IS NULL AND @DefaultDirectory LIKE '%' + '.' + @@SERVICENAME + @DirectorySeparator + 'MSSQL' + @DirectorySeparator + 'Backup' + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}','') + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}','') + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}','') + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}','') + END + WHILE (@Updated = 1 OR @Updated IS NULL) BEGIN SET @Updated = 0 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 1bfd1acd..735a25bc 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -33,7 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 10:53:52 //-- + --// Version: 2018-06-11 19:25:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 07a9c23d..0576246d 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -47,7 +47,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 10:53:52 //-- + --// Version: 2018-06-11 19:25:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 345ddd51..afc03525 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-06-11 10:53:52 +Version: 2018-06-11 19:25:33 You can contact me by e-mail at ola@hallengren.com. @@ -30,7 +30,7 @@ DECLARE @OutputFileDirectory nvarchar(max) DECLARE @LogToTable nvarchar(max) SET @CreateJobs = 'Y' -- Specify whether jobs should be created. -SET @BackupDirectory = N'C:\Backup' -- Specify the backup root directory. +SET @BackupDirectory = NULL -- Specify the backup root directory. If no directory is specified, the default backup directory is used. SET @CleanupTime = NULL -- Time in hours, after which backup files are deleted. If no time is specified, then no backup files are deleted. SET @OutputFileDirectory = NULL -- Specify the output file directory. If no directory is specified, then the SQL Server error log directory is used. SET @LogToTable = 'Y' -- Log commands to a table. @@ -117,7 +117,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 10:53:52 //-- + --// Version: 2018-06-11 19:25:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -364,7 +364,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 10:53:52 //-- + --// Version: 2018-06-11 19:25:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1934,6 +1934,14 @@ BEGIN IF @@SERVICENAME IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}','') IF @Description IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}','') + IF @Directory IS NULL AND @MirrorDirectory IS NULL AND @URL IS NULL AND @DefaultDirectory LIKE '%' + '.' + @@SERVICENAME + @DirectorySeparator + 'MSSQL' + @DirectorySeparator + 'Backup' + BEGIN + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}','') + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}','') + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}','') + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}','') + END + WHILE (@Updated = 1 OR @Updated IS NULL) BEGIN SET @Updated = 0 @@ -3050,7 +3058,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 10:53:52 //-- + --// Version: 2018-06-11 19:25:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4398,7 +4406,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 10:53:52 //-- + --// Version: 2018-06-11 19:25:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 52f3e9192a62c58efbdfc1ea05212be43346a3d0 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 15 Jun 2018 10:42:48 +0200 Subject: [PATCH 045/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 4 ++-- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 ++++++------ 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 09f9641d..e60055bf 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -33,7 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 19:25:33 //-- + --// Version: 2018-06-15 10:37:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 11aecd18..4de4c2e3 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -70,7 +70,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 19:25:33 //-- + --// Version: 2018-06-15 10:37:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1943,7 +1943,7 @@ BEGIN WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) WHEN @URL IS NOT NULL THEN LEN(@URL + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END + @DirectorySeparator) END - + LEN(REPLACE(REPLACE(@CurrentFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '1' WHEN @NumberOfFiles >= 10 THEN '01' ELSE '' END)) + + LEN(REPLACE(REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '1' WHEN @NumberOfFiles >= 10 THEN '01' ELSE '' END)) -- The maximum length of a backup device is 259 characters IF @CurrentMaxFilePathLength > 259 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 735a25bc..4edffa79 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -33,7 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 19:25:33 //-- + --// Version: 2018-06-15 10:37:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 0576246d..39beb53a 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -47,7 +47,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 19:25:33 //-- + --// Version: 2018-06-15 10:37:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index afc03525..ff894afa 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-06-11 19:25:33 +Version: 2018-06-15 10:37:58 You can contact me by e-mail at ola@hallengren.com. @@ -117,7 +117,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 19:25:33 //-- + --// Version: 2018-06-15 10:37:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -364,7 +364,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 19:25:33 //-- + --// Version: 2018-06-15 10:37:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2237,7 +2237,7 @@ BEGIN WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) WHEN @URL IS NOT NULL THEN LEN(@URL + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END + @DirectorySeparator) END - + LEN(REPLACE(REPLACE(@CurrentFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '1' WHEN @NumberOfFiles >= 10 THEN '01' ELSE '' END)) + + LEN(REPLACE(REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '1' WHEN @NumberOfFiles >= 10 THEN '01' ELSE '' END)) -- The maximum length of a backup device is 259 characters IF @CurrentMaxFilePathLength > 259 @@ -3058,7 +3058,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 19:25:33 //-- + --// Version: 2018-06-15 10:37:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4406,7 +4406,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-11 19:25:33 //-- + --// Version: 2018-06-15 10:37:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From f8d8e36daec9f1d115ec59c56fb0483ab559cc67 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 16 Jun 2018 14:44:25 +0200 Subject: [PATCH 046/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 90 ++++++-- DatabaseIntegrityCheck.sql | 207 ++++++++++++++++--- IndexOptimize.sql | 107 ++++++++-- MaintenanceSolution.sql | 408 +++++++++++++++++++++++++++++++------ 5 files changed, 695 insertions(+), 119 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index e60055bf..2a6c2b1b 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -33,7 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-15 10:37:58 //-- + --// Version: 2018-06-16 14:27:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 4de4c2e3..3b7ed8ba 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -59,6 +59,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @FileExtensionDiff nvarchar(max) = NULL, @FileExtensionLog nvarchar(max) = NULL, @Init nvarchar(max) = 'N', +@DatabaseOrder nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -70,7 +71,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-15 10:37:58 //-- + --// Version: 2018-06-16 14:27:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -171,6 +172,7 @@ BEGIN DatabaseType nvarchar(max), AvailabilityGroup bit, StartPosition int, + DatabaseSize bigint, [Order] int, Selected bit, Completed bit, @@ -297,6 +299,7 @@ BEGIN SET @Parameters = @Parameters + ', @FileExtensionDiff = ' + ISNULL('''' + REPLACE(@FileExtensionDiff,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -438,11 +441,12 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, DatabaseSize, [Order], Selected, Completed) SELECT [name] AS DatabaseName, LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, + (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) AS DatabaseSize, 0 AS [Order], 0 AS Selected, 0 AS Completed @@ -601,19 +605,7 @@ BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR - END; - - ---------------------------------------------------------------------------------------------------- - --// Update database order //-- - ---------------------------------------------------------------------------------------------------- - - WITH tmpDatabases AS ( - SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber - FROM @tmpDatabases tmpDatabases - WHERE Selected = 1 - ) - UPDATE tmpDatabases - SET [Order] = RowNumber + END ---------------------------------------------------------------------------------------------------- --// Check database names //-- @@ -1293,6 +1285,13 @@ BEGIN SET @Error = @@ERROR END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + BEGIN + SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1364,6 +1363,65 @@ BEGIN FROM sys.dm_hadr_cluster END + ---------------------------------------------------------------------------------------------------- + --// Update database order //-- + ---------------------------------------------------------------------------------------------------- + + IF @DatabaseOrder IS NULL + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_NAME_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_NAME_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseName DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_SIZE_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseSize ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_SIZE_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseSize DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ---------------------------------------------------------------------------------------------------- --// Execute backup commands //-- ---------------------------------------------------------------------------------------------------- @@ -1937,7 +1995,7 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension); + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) SELECT @CurrentMaxFilePathLength = CASE WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 4edffa79..e3203943 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -21,7 +21,9 @@ ALTER PROCEDURE [dbo].[DatabaseIntegrityCheck] @AvailabilityGroups nvarchar(max) = NULL, @AvailabilityGroupReplicas nvarchar(max) = 'ALL', @Updateability nvarchar(max) = 'ALL', +@TimeLimit int = NULL, @LockTimeout int = NULL, +@DatabaseOrder nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -33,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-15 10:37:58 //-- + --// Version: 2018-06-16 14:27:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -59,6 +61,8 @@ BEGIN DECLARE @CurrentIsDatabaseAccessible bit DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) + DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) + DECLARE @CurrentIsPreferredBackupReplica bit DECLARE @CurrentDatabaseMirroringRole nvarchar(max) DECLARE @CurrentIsReadOnly bit @@ -103,6 +107,9 @@ BEGIN AvailabilityGroup bit, [Snapshot] bit, StartPosition int, + LastCommandTime datetime, + DatabaseSize bigint, + LastGoodCheckDbTime datetime, [Order] int, Selected bit, Completed bit, @@ -201,7 +208,9 @@ BEGIN SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @AvailabilityGroupReplicas = ' + ISNULL('''' + REPLACE(@AvailabilityGroupReplicas,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -336,11 +345,13 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], [Order], Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], DatabaseSize, LastGoodCheckDbTime, [Order], Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], + (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) AS DatabaseSize, + NULLIF(CAST(DATABASEPROPERTYEX (name,'LastGoodCheckDbTime') AS datetime),'1900-01-01 00:00:00.000') AS LastGoodCheckDbTime, 0 AS [Order], 0 AS Selected, 0 AS Completed @@ -499,19 +510,7 @@ BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR - END; - - ---------------------------------------------------------------------------------------------------- - --// Update database order //-- - ---------------------------------------------------------------------------------------------------- - - WITH tmpDatabases AS ( - SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber - FROM @tmpDatabases tmpDatabases - WHERE Selected = 1 - ) - UPDATE tmpDatabases - SET [Order] = RowNumber + END ---------------------------------------------------------------------------------------------------- --// Select filegroups //-- @@ -700,7 +699,7 @@ BEGIN SET @Error = @@ERROR END - IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY') OR @AvailabilityGroupReplicas IS NULL + IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupReplicas is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -714,6 +713,13 @@ BEGIN SET @Error = @@ERROR END + IF @TimeLimit < 0 + BEGIN + SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LockTimeout < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -721,6 +727,13 @@ BEGIN SET @Error = @@ERROR END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 13.05026 AND @Version < 14)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') + BEGIN + SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -821,6 +834,133 @@ BEGIN SET @Error = @@ERROR END + ---------------------------------------------------------------------------------------------------- + --// Check @@SERVERNAME //-- + ---------------------------------------------------------------------------------------------------- + + IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 + BEGIN + SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + ---------------------------------------------------------------------------------------------------- + --// Update database order //-- + ---------------------------------------------------------------------------------------------------- + + IF @DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') + BEGIN + UPDATE tmpDatabases + SET LastCommandTime = MaxStartTime + FROM @tmpDatabases tmpDatabases + INNER JOIN (SELECT DatabaseName, MAX(StartTime) AS MaxStartTime + FROM dbo.CommandLog + WHERE CommandType = 'DBCC_CHECKDB' + AND ErrorNumber = 0 + GROUP BY DatabaseName) CommandLog + ON tmpDatabases.DatabaseName = CommandLog.DatabaseName + END + + IF @DatabaseOrder IS NULL + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_NAME_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_NAME_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseName DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_SIZE_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseSize ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_SIZE_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseSize DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_LAST_GOOD_CHECK_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY LastGoodCheckDbTime ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_LAST_GOOD_CHECK_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY LastGoodCheckDbTime DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'REPLICA_LAST_GOOD_CHECK_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY LastCommandTime ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'REPLICA_LAST_GOOD_CHECK_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY LastCommandTime DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ---------------------------------------------------------------------------------------------------- --// Execute commands //-- ---------------------------------------------------------------------------------------------------- @@ -857,7 +997,8 @@ BEGIN IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @CurrentAvailabilityGroup = availability_groups.name, - @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc + @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) FROM sys.databases databases INNER JOIN sys.availability_databases_cluster availability_databases_cluster ON databases.group_database_id = availability_databases_cluster.group_database_id INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id @@ -865,6 +1006,11 @@ BEGIN WHERE databases.name = @CurrentDatabaseName END + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL AND @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' + BEGIN + SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) @@ -910,6 +1056,15 @@ BEGIN SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + IF @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' + BEGIN + SET @DatabaseMessage = 'Availability group backup preference: ' + @CurrentAvailabilityGroupBackupPreference + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Is preferred backup replica: ' + CASE WHEN @CurrentIsPreferredBackupReplica = 1 THEN 'Yes' WHEN @CurrentIsPreferredBackupReplica = 0 THEN 'No' ELSE 'N/A' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END END IF @CurrentDatabaseMirroringRole IS NOT NULL @@ -923,13 +1078,13 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR SERVERPROPERTY('EngineEdition') = 3) - AND (@CurrentAvailabilityGroupRole = @AvailabilityGroupReplicas OR @AvailabilityGroupReplicas = 'ALL' OR @CurrentAvailabilityGroupRole IS NULL) + AND ((@AvailabilityGroupReplicas = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY') OR (@AvailabilityGroupReplicas = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY') OR (@AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' AND @CurrentIsPreferredBackupReplica = 1) OR @AvailabilityGroupReplicas = 'ALL' OR @CurrentAvailabilityGroupRole IS NULL) AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') BEGIN -- Check database - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKDB') + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKDB') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType01 = 'DBCC_CHECKDB' @@ -951,7 +1106,7 @@ BEGIN END -- Check filegroups - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand02 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' @@ -1015,7 +1170,7 @@ BEGIN SET @Error = @@ERROR END - WHILE (1 = 1) + WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SELECT TOP 1 @CurrentFGID = ID, @CurrentFileGroupID = FileGroupID, @@ -1089,7 +1244,7 @@ BEGIN END -- Check disk space allocation structures - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKALLOC') + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKALLOC') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType05 = 'DBCC_CHECKALLOC' @@ -1106,7 +1261,7 @@ BEGIN END -- Check objects - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand06 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' @@ -1171,7 +1326,7 @@ BEGIN SET @Error = @@ERROR END - WHILE (1 = 1) + WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SELECT TOP 1 @CurrentOID = ID, @CurrentSchemaID = SchemaID, @@ -1253,7 +1408,7 @@ BEGIN END -- Check catalog - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType09 = 'DBCC_CHECKCATALOG' @@ -1291,6 +1446,8 @@ BEGIN SET @CurrentIsDatabaseAccessible = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL + SET @CurrentAvailabilityGroupBackupPreference = NULL + SET @CurrentIsPreferredBackupReplica = NULL SET @CurrentDatabaseMirroringRole = NULL SET @CurrentIsReadOnly = NULL diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 39beb53a..f02f36b9 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -24,6 +24,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @LOBCompaction nvarchar(max) = 'Y', @UpdateStatistics nvarchar(max) = NULL, @OnlyModifiedStatistics nvarchar(max) = 'N', +@StatisticsModificationLevel int = NULL, @StatisticsSample int = NULL, @StatisticsResample nvarchar(max) = 'N', @PartitionLevel nvarchar(max) = 'Y', @@ -36,6 +37,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @Resumable nvarchar(max) = 'N', @AvailabilityGroups nvarchar(max) = NULL, @LockTimeout int = NULL, +@DatabaseOrder nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -47,7 +49,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-15 10:37:58 //-- + --// Version: 2018-06-16 14:27:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -148,6 +150,7 @@ BEGIN DatabaseType nvarchar(max), AvailabilityGroup bit, StartPosition int, + DatabaseSize bigint, [Order] int, Selected bit, Completed bit, @@ -277,6 +280,7 @@ BEGIN SET @Parameters = @Parameters + ', @LOBCompaction = ' + ISNULL('''' + REPLACE(@LOBCompaction,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @UpdateStatistics = ' + ISNULL('''' + REPLACE(@UpdateStatistics,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @StatisticsModificationLevel = ' + ISNULL(CAST(@StatisticsModificationLevel AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @StatisticsResample = ' + ISNULL('''' + REPLACE(@StatisticsResample,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @PartitionLevel = ' + ISNULL('''' + REPLACE(@PartitionLevel,'''','''''') + '''','NULL') @@ -289,6 +293,7 @@ BEGIN SET @Parameters = @Parameters + ', @Resumable = ' + ISNULL('''' + REPLACE(@Resumable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -423,10 +428,11 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, DatabaseSize, [Order], Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, + (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) AS DatabaseSize, 0 AS [Order], 0 AS Selected, 0 AS Completed @@ -585,19 +591,7 @@ BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR - END; - - ---------------------------------------------------------------------------------------------------- - --// Update database order //-- - ---------------------------------------------------------------------------------------------------- - - WITH tmpDatabases AS ( - SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber - FROM @tmpDatabases tmpDatabases - WHERE Selected = 1 - ) - UPDATE tmpDatabases - SET [Order] = RowNumber + END ---------------------------------------------------------------------------------------------------- --// Select indexes //-- @@ -822,6 +816,20 @@ BEGIN SET @Error = @@ERROR END + IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 + BEGIN + SET @ErrorMessage = 'The value for the parameter @StatisticsModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL + BEGIN + SET @ErrorMessage = 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN SET @ErrorMessage = 'The value for the parameter @StatisticsSample is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -906,6 +914,13 @@ BEGIN SET @Error = @@ERROR END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + BEGIN + SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -987,6 +1002,65 @@ BEGIN SET @PartitionLevelStatistics = CASE WHEN @PartitionLevel = 'Y' AND ((@Version >= 12.05 AND @Version < 13) OR @Version >= 13.04422 OR SERVERPROPERTY('EngineEdition') IN (5,8)) THEN 1 ELSE 0 END + ---------------------------------------------------------------------------------------------------- + --// Update database order //-- + ---------------------------------------------------------------------------------------------------- + + IF @DatabaseOrder IS NULL + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_NAME_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_NAME_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseName DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_SIZE_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseSize ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_SIZE_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseSize DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ---------------------------------------------------------------------------------------------------- --// Execute commands //-- ---------------------------------------------------------------------------------------------------- @@ -1539,9 +1613,8 @@ BEGIN -- Update statistics? IF @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,3,4,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,3,4,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) - AND (@CurrentModificationCounter > 0 OR @OnlyModifiedStatistics = 'N' OR (@CurrentIsMemoryOptimized = 1 AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') IN (5,8)))) + AND ((@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) OR (@OnlyModifiedStatistics = 'Y' AND @CurrentModificationCounter > 0) OR ((@CurrentModificationCounter * 1. / NULLIF(@CurrentRowCount,0)) * 100 >= @StatisticsModificationLevel) OR (@StatisticsModificationLevel IS NOT NULL AND @CurrentModificationCounter > 0 AND (@CurrentModificationCounter >= SQRT(@CurrentRowCount * 1000))) OR (@CurrentIsMemoryOptimized = 1 AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') IN (5,8)))) AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1)))) - BEGIN SET @CurrentUpdateStatistics = 'Y' END diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index ff894afa..91294e35 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-06-15 10:37:58 +Version: 2018-06-16 14:27:00 You can contact me by e-mail at ola@hallengren.com. @@ -117,7 +117,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-15 10:37:58 //-- + --// Version: 2018-06-16 14:27:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -353,6 +353,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @FileExtensionDiff nvarchar(max) = NULL, @FileExtensionLog nvarchar(max) = NULL, @Init nvarchar(max) = 'N', +@DatabaseOrder nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -364,7 +365,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-15 10:37:58 //-- + --// Version: 2018-06-16 14:27:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -465,6 +466,7 @@ BEGIN DatabaseType nvarchar(max), AvailabilityGroup bit, StartPosition int, + DatabaseSize bigint, [Order] int, Selected bit, Completed bit, @@ -591,6 +593,7 @@ BEGIN SET @Parameters = @Parameters + ', @FileExtensionDiff = ' + ISNULL('''' + REPLACE(@FileExtensionDiff,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -732,11 +735,12 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, DatabaseSize, [Order], Selected, Completed) SELECT [name] AS DatabaseName, LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, + (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) AS DatabaseSize, 0 AS [Order], 0 AS Selected, 0 AS Completed @@ -895,19 +899,7 @@ BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR - END; - - ---------------------------------------------------------------------------------------------------- - --// Update database order //-- - ---------------------------------------------------------------------------------------------------- - - WITH tmpDatabases AS ( - SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber - FROM @tmpDatabases tmpDatabases - WHERE Selected = 1 - ) - UPDATE tmpDatabases - SET [Order] = RowNumber + END ---------------------------------------------------------------------------------------------------- --// Check database names //-- @@ -1587,6 +1579,13 @@ BEGIN SET @Error = @@ERROR END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + BEGIN + SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1658,6 +1657,65 @@ BEGIN FROM sys.dm_hadr_cluster END + ---------------------------------------------------------------------------------------------------- + --// Update database order //-- + ---------------------------------------------------------------------------------------------------- + + IF @DatabaseOrder IS NULL + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_NAME_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_NAME_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseName DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_SIZE_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseSize ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_SIZE_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseSize DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ---------------------------------------------------------------------------------------------------- --// Execute backup commands //-- ---------------------------------------------------------------------------------------------------- @@ -2231,7 +2289,7 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension); + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) SELECT @CurrentMaxFilePathLength = CASE WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) @@ -3046,7 +3104,9 @@ ALTER PROCEDURE [dbo].[DatabaseIntegrityCheck] @AvailabilityGroups nvarchar(max) = NULL, @AvailabilityGroupReplicas nvarchar(max) = 'ALL', @Updateability nvarchar(max) = 'ALL', +@TimeLimit int = NULL, @LockTimeout int = NULL, +@DatabaseOrder nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -3058,7 +3118,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-15 10:37:58 //-- + --// Version: 2018-06-16 14:27:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3084,6 +3144,8 @@ BEGIN DECLARE @CurrentIsDatabaseAccessible bit DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) + DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) + DECLARE @CurrentIsPreferredBackupReplica bit DECLARE @CurrentDatabaseMirroringRole nvarchar(max) DECLARE @CurrentIsReadOnly bit @@ -3128,6 +3190,9 @@ BEGIN AvailabilityGroup bit, [Snapshot] bit, StartPosition int, + LastCommandTime datetime, + DatabaseSize bigint, + LastGoodCheckDbTime datetime, [Order] int, Selected bit, Completed bit, @@ -3226,7 +3291,9 @@ BEGIN SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @AvailabilityGroupReplicas = ' + ISNULL('''' + REPLACE(@AvailabilityGroupReplicas,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -3361,11 +3428,13 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], [Order], Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], DatabaseSize, LastGoodCheckDbTime, [Order], Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], + (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) AS DatabaseSize, + NULLIF(CAST(DATABASEPROPERTYEX (name,'LastGoodCheckDbTime') AS datetime),'1900-01-01 00:00:00.000') AS LastGoodCheckDbTime, 0 AS [Order], 0 AS Selected, 0 AS Completed @@ -3524,19 +3593,7 @@ BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR - END; - - ---------------------------------------------------------------------------------------------------- - --// Update database order //-- - ---------------------------------------------------------------------------------------------------- - - WITH tmpDatabases AS ( - SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber - FROM @tmpDatabases tmpDatabases - WHERE Selected = 1 - ) - UPDATE tmpDatabases - SET [Order] = RowNumber + END ---------------------------------------------------------------------------------------------------- --// Select filegroups //-- @@ -3725,7 +3782,7 @@ BEGIN SET @Error = @@ERROR END - IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY') OR @AvailabilityGroupReplicas IS NULL + IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupReplicas is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -3739,6 +3796,13 @@ BEGIN SET @Error = @@ERROR END + IF @TimeLimit < 0 + BEGIN + SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LockTimeout < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -3746,6 +3810,13 @@ BEGIN SET @Error = @@ERROR END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 13.05026 AND @Version < 14)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') + BEGIN + SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -3846,6 +3917,133 @@ BEGIN SET @Error = @@ERROR END + ---------------------------------------------------------------------------------------------------- + --// Check @@SERVERNAME //-- + ---------------------------------------------------------------------------------------------------- + + IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 + BEGIN + SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + ---------------------------------------------------------------------------------------------------- + --// Update database order //-- + ---------------------------------------------------------------------------------------------------- + + IF @DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') + BEGIN + UPDATE tmpDatabases + SET LastCommandTime = MaxStartTime + FROM @tmpDatabases tmpDatabases + INNER JOIN (SELECT DatabaseName, MAX(StartTime) AS MaxStartTime + FROM dbo.CommandLog + WHERE CommandType = 'DBCC_CHECKDB' + AND ErrorNumber = 0 + GROUP BY DatabaseName) CommandLog + ON tmpDatabases.DatabaseName = CommandLog.DatabaseName + END + + IF @DatabaseOrder IS NULL + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_NAME_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_NAME_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseName DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_SIZE_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseSize ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_SIZE_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseSize DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_LAST_GOOD_CHECK_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY LastGoodCheckDbTime ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_LAST_GOOD_CHECK_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY LastGoodCheckDbTime DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'REPLICA_LAST_GOOD_CHECK_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY LastCommandTime ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'REPLICA_LAST_GOOD_CHECK_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY LastCommandTime DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ---------------------------------------------------------------------------------------------------- --// Execute commands //-- ---------------------------------------------------------------------------------------------------- @@ -3882,7 +4080,8 @@ BEGIN IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @CurrentAvailabilityGroup = availability_groups.name, - @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc + @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) FROM sys.databases databases INNER JOIN sys.availability_databases_cluster availability_databases_cluster ON databases.group_database_id = availability_databases_cluster.group_database_id INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id @@ -3890,6 +4089,11 @@ BEGIN WHERE databases.name = @CurrentDatabaseName END + IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL AND @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' + BEGIN + SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) @@ -3935,6 +4139,15 @@ BEGIN SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + IF @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' + BEGIN + SET @DatabaseMessage = 'Availability group backup preference: ' + @CurrentAvailabilityGroupBackupPreference + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + + SET @DatabaseMessage = 'Is preferred backup replica: ' + CASE WHEN @CurrentIsPreferredBackupReplica = 1 THEN 'Yes' WHEN @CurrentIsPreferredBackupReplica = 0 THEN 'No' ELSE 'N/A' END + RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + END END IF @CurrentDatabaseMirroringRole IS NOT NULL @@ -3948,13 +4161,13 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR SERVERPROPERTY('EngineEdition') = 3) - AND (@CurrentAvailabilityGroupRole = @AvailabilityGroupReplicas OR @AvailabilityGroupReplicas = 'ALL' OR @CurrentAvailabilityGroupRole IS NULL) + AND ((@AvailabilityGroupReplicas = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY') OR (@AvailabilityGroupReplicas = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY') OR (@AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' AND @CurrentIsPreferredBackupReplica = 1) OR @AvailabilityGroupReplicas = 'ALL' OR @CurrentAvailabilityGroupRole IS NULL) AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') BEGIN -- Check database - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKDB') + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKDB') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType01 = 'DBCC_CHECKDB' @@ -3976,7 +4189,7 @@ BEGIN END -- Check filegroups - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand02 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' @@ -4040,7 +4253,7 @@ BEGIN SET @Error = @@ERROR END - WHILE (1 = 1) + WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SELECT TOP 1 @CurrentFGID = ID, @CurrentFileGroupID = FileGroupID, @@ -4114,7 +4327,7 @@ BEGIN END -- Check disk space allocation structures - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKALLOC') + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKALLOC') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType05 = 'DBCC_CHECKALLOC' @@ -4131,7 +4344,7 @@ BEGIN END -- Check objects - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand06 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' @@ -4196,7 +4409,7 @@ BEGIN SET @Error = @@ERROR END - WHILE (1 = 1) + WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SELECT TOP 1 @CurrentOID = ID, @CurrentSchemaID = SchemaID, @@ -4278,7 +4491,7 @@ BEGIN END -- Check catalog - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType09 = 'DBCC_CHECKCATALOG' @@ -4316,6 +4529,8 @@ BEGIN SET @CurrentIsDatabaseAccessible = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL + SET @CurrentAvailabilityGroupBackupPreference = NULL + SET @CurrentIsPreferredBackupReplica = NULL SET @CurrentDatabaseMirroringRole = NULL SET @CurrentIsReadOnly = NULL @@ -4383,6 +4598,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @LOBCompaction nvarchar(max) = 'Y', @UpdateStatistics nvarchar(max) = NULL, @OnlyModifiedStatistics nvarchar(max) = 'N', +@StatisticsModificationLevel int = NULL, @StatisticsSample int = NULL, @StatisticsResample nvarchar(max) = 'N', @PartitionLevel nvarchar(max) = 'Y', @@ -4395,6 +4611,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @Resumable nvarchar(max) = 'N', @AvailabilityGroups nvarchar(max) = NULL, @LockTimeout int = NULL, +@DatabaseOrder nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -4406,7 +4623,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-15 10:37:58 //-- + --// Version: 2018-06-16 14:27:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4507,6 +4724,7 @@ BEGIN DatabaseType nvarchar(max), AvailabilityGroup bit, StartPosition int, + DatabaseSize bigint, [Order] int, Selected bit, Completed bit, @@ -4636,6 +4854,7 @@ BEGIN SET @Parameters = @Parameters + ', @LOBCompaction = ' + ISNULL('''' + REPLACE(@LOBCompaction,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @UpdateStatistics = ' + ISNULL('''' + REPLACE(@UpdateStatistics,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @StatisticsModificationLevel = ' + ISNULL(CAST(@StatisticsModificationLevel AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @StatisticsResample = ' + ISNULL('''' + REPLACE(@StatisticsResample,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @PartitionLevel = ' + ISNULL('''' + REPLACE(@PartitionLevel,'''','''''') + '''','NULL') @@ -4648,6 +4867,7 @@ BEGIN SET @Parameters = @Parameters + ', @Resumable = ' + ISNULL('''' + REPLACE(@Resumable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -4782,10 +5002,11 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, DatabaseSize, [Order], Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, + (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) AS DatabaseSize, 0 AS [Order], 0 AS Selected, 0 AS Completed @@ -4944,19 +5165,7 @@ BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR - END; - - ---------------------------------------------------------------------------------------------------- - --// Update database order //-- - ---------------------------------------------------------------------------------------------------- - - WITH tmpDatabases AS ( - SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber - FROM @tmpDatabases tmpDatabases - WHERE Selected = 1 - ) - UPDATE tmpDatabases - SET [Order] = RowNumber + END ---------------------------------------------------------------------------------------------------- --// Select indexes //-- @@ -5181,6 +5390,20 @@ BEGIN SET @Error = @@ERROR END + IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 + BEGIN + SET @ErrorMessage = 'The value for the parameter @StatisticsModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL + BEGIN + SET @ErrorMessage = 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN SET @ErrorMessage = 'The value for the parameter @StatisticsSample is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -5265,6 +5488,13 @@ BEGIN SET @Error = @@ERROR END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + BEGIN + SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -5346,6 +5576,65 @@ BEGIN SET @PartitionLevelStatistics = CASE WHEN @PartitionLevel = 'Y' AND ((@Version >= 12.05 AND @Version < 13) OR @Version >= 13.04422 OR SERVERPROPERTY('EngineEdition') IN (5,8)) THEN 1 ELSE 0 END + ---------------------------------------------------------------------------------------------------- + --// Update database order //-- + ---------------------------------------------------------------------------------------------------- + + IF @DatabaseOrder IS NULL + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY StartPosition ASC, DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_NAME_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseName ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_NAME_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseName DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_SIZE_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseSize ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'DATABASE_SIZE_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY DatabaseSize DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ---------------------------------------------------------------------------------------------------- --// Execute commands //-- ---------------------------------------------------------------------------------------------------- @@ -5898,9 +6187,8 @@ BEGIN -- Update statistics? IF @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,3,4,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,3,4,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) - AND (@CurrentModificationCounter > 0 OR @OnlyModifiedStatistics = 'N' OR (@CurrentIsMemoryOptimized = 1 AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') IN (5,8)))) + AND ((@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) OR (@OnlyModifiedStatistics = 'Y' AND @CurrentModificationCounter > 0) OR ((@CurrentModificationCounter * 1. / NULLIF(@CurrentRowCount,0)) * 100 >= @StatisticsModificationLevel) OR (@StatisticsModificationLevel IS NOT NULL AND @CurrentModificationCounter > 0 AND (@CurrentModificationCounter >= SQRT(@CurrentRowCount * 1000))) OR (@CurrentIsMemoryOptimized = 1 AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') IN (5,8)))) AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1)))) - BEGIN SET @CurrentUpdateStatistics = 'Y' END From 626d5661b74ba43221fe6fabf750bdca29df3688 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 18 Jun 2018 19:26:56 +0200 Subject: [PATCH 047/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 14 +++++++--- DatabaseIntegrityCheck.sql | 22 ++++++++++++---- IndexOptimize.sql | 14 +++++++--- MaintenanceSolution.sql | 54 +++++++++++++++++++++++++++----------- 5 files changed, 77 insertions(+), 29 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 2a6c2b1b..e31d7159 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -33,7 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-16 14:27:00 //-- + --// Version: 2018-06-18 19:09:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 3b7ed8ba..e8ee6a09 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -71,7 +71,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-16 14:27:00 //-- + --// Version: 2018-06-18 19:09:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -441,12 +441,11 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, DatabaseSize, [Order], Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, - (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) AS DatabaseSize, 0 AS [Order], 0 AS Selected, 0 AS Completed @@ -1285,7 +1284,7 @@ BEGIN SET @Error = @@ERROR END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1367,6 +1366,13 @@ BEGIN --// Update database order //-- ---------------------------------------------------------------------------------------------------- + IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + BEGIN + UPDATE tmpDatabases + SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) + FROM @tmpDatabases tmpDatabases + END + IF @DatabaseOrder IS NULL BEGIN WITH tmpDatabases AS ( diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index e3203943..3b4c87b8 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-16 14:27:00 //-- + --// Version: 2018-06-18 19:09:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -345,13 +345,11 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], DatabaseSize, LastGoodCheckDbTime, [Order], Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], [Order], Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], - (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) AS DatabaseSize, - NULLIF(CAST(DATABASEPROPERTYEX (name,'LastGoodCheckDbTime') AS datetime),'1900-01-01 00:00:00.000') AS LastGoodCheckDbTime, 0 AS [Order], 0 AS Selected, 0 AS Completed @@ -727,7 +725,7 @@ BEGIN SET @Error = @@ERROR END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 13.05026 AND @Version < 14)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 13.05026 AND @Version < 14)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -849,6 +847,20 @@ BEGIN --// Update database order //-- ---------------------------------------------------------------------------------------------------- + IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + BEGIN + UPDATE tmpDatabases + SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) + FROM @tmpDatabases tmpDatabases + END + + IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') + BEGIN + UPDATE tmpDatabases + SET LastGoodCheckDbTime = NULLIF(CAST(DATABASEPROPERTYEX (DatabaseName,'LastGoodCheckDbTime') AS datetime),'1900-01-01 00:00:00.000') + FROM @tmpDatabases tmpDatabases + END + IF @DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') BEGIN UPDATE tmpDatabases diff --git a/IndexOptimize.sql b/IndexOptimize.sql index f02f36b9..ed34eb99 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -49,7 +49,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-16 14:27:00 //-- + --// Version: 2018-06-18 19:09:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -428,11 +428,10 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, DatabaseSize, [Order], Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, - (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) AS DatabaseSize, 0 AS [Order], 0 AS Selected, 0 AS Completed @@ -914,7 +913,7 @@ BEGIN SET @Error = @@ERROR END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1006,6 +1005,13 @@ BEGIN --// Update database order //-- ---------------------------------------------------------------------------------------------------- + IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + BEGIN + UPDATE tmpDatabases + SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) + FROM @tmpDatabases tmpDatabases + END + IF @DatabaseOrder IS NULL BEGIN WITH tmpDatabases AS ( diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 91294e35..9827ddc1 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-06-16 14:27:00 +Version: 2018-06-18 19:09:39 You can contact me by e-mail at ola@hallengren.com. @@ -117,7 +117,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-16 14:27:00 //-- + --// Version: 2018-06-18 19:09:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -365,7 +365,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-16 14:27:00 //-- + --// Version: 2018-06-18 19:09:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -735,12 +735,11 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, DatabaseSize, [Order], Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, - (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) AS DatabaseSize, 0 AS [Order], 0 AS Selected, 0 AS Completed @@ -1579,7 +1578,7 @@ BEGIN SET @Error = @@ERROR END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1661,6 +1660,13 @@ BEGIN --// Update database order //-- ---------------------------------------------------------------------------------------------------- + IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + BEGIN + UPDATE tmpDatabases + SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) + FROM @tmpDatabases tmpDatabases + END + IF @DatabaseOrder IS NULL BEGIN WITH tmpDatabases AS ( @@ -3118,7 +3124,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-16 14:27:00 //-- + --// Version: 2018-06-18 19:09:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3428,13 +3434,11 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], DatabaseSize, LastGoodCheckDbTime, [Order], Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], [Order], Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], - (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) AS DatabaseSize, - NULLIF(CAST(DATABASEPROPERTYEX (name,'LastGoodCheckDbTime') AS datetime),'1900-01-01 00:00:00.000') AS LastGoodCheckDbTime, 0 AS [Order], 0 AS Selected, 0 AS Completed @@ -3810,7 +3814,7 @@ BEGIN SET @Error = @@ERROR END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 13.05026 AND @Version < 14)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 13.05026 AND @Version < 14)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -3932,6 +3936,20 @@ BEGIN --// Update database order //-- ---------------------------------------------------------------------------------------------------- + IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + BEGIN + UPDATE tmpDatabases + SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) + FROM @tmpDatabases tmpDatabases + END + + IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') + BEGIN + UPDATE tmpDatabases + SET LastGoodCheckDbTime = NULLIF(CAST(DATABASEPROPERTYEX (DatabaseName,'LastGoodCheckDbTime') AS datetime),'1900-01-01 00:00:00.000') + FROM @tmpDatabases tmpDatabases + END + IF @DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') BEGIN UPDATE tmpDatabases @@ -4623,7 +4641,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-16 14:27:00 //-- + --// Version: 2018-06-18 19:09:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5002,11 +5020,10 @@ BEGIN INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id END - INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, DatabaseSize, [Order], Selected, Completed) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, - (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) AS DatabaseSize, 0 AS [Order], 0 AS Selected, 0 AS Completed @@ -5488,7 +5505,7 @@ BEGIN SET @Error = @@ERROR END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -5580,6 +5597,13 @@ BEGIN --// Update database order //-- ---------------------------------------------------------------------------------------------------- + IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + BEGIN + UPDATE tmpDatabases + SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) + FROM @tmpDatabases tmpDatabases + END + IF @DatabaseOrder IS NULL BEGIN WITH tmpDatabases AS ( From 65137b31ff83c306f2eb5b074ba77afdc197480b Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 18 Jun 2018 23:31:58 +0200 Subject: [PATCH 048/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 14d3f3d4..af3fae70 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ You can also download the objects as separate scripts: Note that you always need CommandExecute, DatabaseBackup, DatabaseIntegrityCheck, and IndexOptimize are using it. You need CommandLog if you are going to use the option to log commands to a table. -Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, and SQL Server 2017 +Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, Azure SQL Database, and Azure SQL Database Managed Instance ## Documentation From 401efef88f426d5529d4447f35525013877f279e Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 20 Jun 2018 21:04:50 +0200 Subject: [PATCH 049/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 235 +++++++++++++- DatabaseIntegrityCheck.sql | 200 +++++++++++- IndexOptimize.sql | 200 +++++++++++- MaintenanceSolution.sql | 639 ++++++++++++++++++++++++++++++++++--- Queue.sql | 23 ++ QueueDatabase.sql | 31 ++ 7 files changed, 1251 insertions(+), 79 deletions(-) create mode 100644 Queue.sql create mode 100644 QueueDatabase.sql diff --git a/CommandExecute.sql b/CommandExecute.sql index e31d7159..5f47734a 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -33,7 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-18 19:09:39 //-- + --// Version: 2018-06-20 20:30:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index e8ee6a09..af607254 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -60,6 +60,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @FileExtensionLog nvarchar(max) = NULL, @Init nvarchar(max) = 'N', @DatabaseOrder nvarchar(max) = NULL, +@ExecutionMode nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -71,7 +72,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-18 19:09:39 //-- + --// Version: 2018-06-20 20:30:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -98,6 +99,9 @@ BEGIN DECLARE @DefaultDirectory nvarchar(4000) + DECLARE @QueueID int + DECLARE @QueueStartTime datetime + DECLARE @CurrentRootDirectoryID int DECLARE @CurrentRootDirectoryPath nvarchar(4000) @@ -173,6 +177,7 @@ BEGIN AvailabilityGroup bit, StartPosition int, DatabaseSize bigint, + LogSizeSinceLastLogBackup float, [Order] int, Selected bit, Completed bit, @@ -300,6 +305,7 @@ BEGIN SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ExecutionMode = ' + ISNULL('''' + REPLACE(@ExecutionMode,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -356,6 +362,27 @@ BEGIN SET @Error = @@ERROR END + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'Queue') + BEGIN + SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'QueueDatabase') + BEGIN + SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @@TRANCOUNT <> 0 + BEGIN + SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @AmazonRDS = 1 BEGIN SET @ErrorMessage = 'The stored procedure DatabaseBackup is not supported on Amazon RDS.' + CHAR(13) + CHAR(10) + ' ' @@ -1284,13 +1311,20 @@ BEGIN SET @Error = @@ERROR END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT (@Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END + IF @ExecutionMode NOT IN('DATABASES_IN_PARALLEL') OR (@ExecutionMode IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + BEGIN + SET @ErrorMessage = 'The value for the parameter @ExecutionMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1373,6 +1407,13 @@ BEGIN FROM @tmpDatabases tmpDatabases END + IF @DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') + BEGIN + UPDATE tmpDatabases + SET LogSizeSinceLastLogBackup = (SELECT log_since_last_log_backup_mb FROM sys.dm_db_log_stats(DB_ID(tmpDatabases.DatabaseName))) + FROM @tmpDatabases tmpDatabases + END + IF @DatabaseOrder IS NULL BEGIN WITH tmpDatabases AS ( @@ -1427,6 +1468,125 @@ BEGIN UPDATE tmpDatabases SET [Order] = RowNumber END + ELSE + IF @DatabaseOrder = 'LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY LogSizeSinceLastLogBackup ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY LogSizeSinceLastLogBackup DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + + ---------------------------------------------------------------------------------------------------- + --// Update the queue //-- + ---------------------------------------------------------------------------------------------------- + + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + + BEGIN TRY + + SELECT @QueueID = QueueID + FROM dbo.[Queue] + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @Parameters + + IF @QueueID IS NULL + BEGIN + BEGIN TRANSACTION + + SELECT @QueueID = QueueID + FROM dbo.[Queue] WITH (UPDLOCK, TABLOCK) + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @Parameters + + IF @QueueID IS NULL + BEGIN + INSERT INTO dbo.[Queue] (SchemaName, ObjectName, [Parameters]) + SELECT @SchemaName, @ObjectName, @Parameters + + SET @QueueID = SCOPE_IDENTITY() + END + + COMMIT TRANSACTION + END + + BEGIN TRANSACTION + + UPDATE [Queue] + SET QueueStartTime = GETDATE(), + SessionID = @@SPID, + RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), + RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID) + FROM dbo.[Queue] [Queue] + WHERE QueueID = @QueueID + AND NOT EXISTS (SELECT * + FROM sys.dm_exec_requests + WHERE session_id = [Queue].SessionID + AND request_id = [Queue].RequestID + AND start_time = [Queue].RequestStartTime) + AND NOT EXISTS (SELECT * + FROM dbo.QueueDatabase QueueDatabase + INNER JOIN sys.dm_exec_requests ON QueueDatabase.SessionID = session_id AND QueueDatabase.RequestID = request_id AND QueueDatabase.RequestStartTime = start_time + WHERE QueueDatabase.QueueID = @QueueID) + + IF @@ROWCOUNT = 1 + BEGIN + INSERT INTO dbo.QueueDatabase (QueueID, DatabaseName) + SELECT @QueueID AS QueueID, + DatabaseName + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName = tmpDatabases.DatabaseName AND QueueID = @QueueID) + + DELETE QueueDatabase + FROM dbo.QueueDatabase QueueDatabase + WHERE QueueID = @QueueID + AND NOT EXISTS (SELECT * FROM @tmpDatabases tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName AND Selected = 1) + + UPDATE QueueDatabase + SET DatabaseOrder = tmpDatabases.[Order] + FROM dbo.QueueDatabase QueueDatabase + INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + END + + COMMIT TRANSACTION + + SELECT @QueueStartTime = QueueStartTime + FROM dbo.[Queue] + WHERE QueueID = @QueueID + + END TRY + + BEGIN CATCH + IF XACT_STATE() <> 0 + BEGIN + ROLLBACK TRANSACTION + END + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + SET @ReturnCode = @Error + GOTO Logging + END CATCH + + END ---------------------------------------------------------------------------------------------------- --// Execute backup commands //-- @@ -1435,13 +1595,50 @@ BEGIN WHILE (1 = 1) BEGIN - SELECT TOP 1 @CurrentDBID = ID, - @CurrentDatabaseName = DatabaseName, - @CurrentDatabaseNameFS = DatabaseNameFS - FROM @tmpDatabases - WHERE Selected = 1 - AND Completed = 0 - ORDER BY [Order] ASC + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + UPDATE QueueDatabase + SET DatabaseStartTime = NULL, + SessionID = NULL, + RequestID = NULL, + RequestStartTime = NULL + FROM dbo.QueueDatabase QueueDatabase + WHERE QueueID = @QueueID + AND DatabaseStartTime IS NOT NULL + AND DatabaseEndTime IS NULL + AND NOT EXISTS (SELECT * FROM sys.dm_exec_requests WHERE session_id = QueueDatabase.SessionID AND request_id = QueueDatabase.RequestID AND start_time = QueueDatabase.RequestStartTime) + + UPDATE QueueDatabase + SET DatabaseStartTime = GETDATE(), + DatabaseEndTime = NULL, + SessionID = @@SPID, + RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), + RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID), + @CurrentDatabaseName = DatabaseName, + @CurrentDatabaseNameFS = (SELECT DatabaseNameFS FROM @tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName) + FROM (SELECT TOP 1 DatabaseStartTime, + DatabaseEndTime, + SessionID, + RequestID, + RequestStartTime, + DatabaseName + FROM dbo.QueueDatabase + WHERE QueueID = @QueueID + AND (DatabaseStartTime < @QueueStartTime OR DatabaseStartTime IS NULL) + AND NOT (DatabaseStartTime IS NOT NULL AND DatabaseEndTime IS NULL) + ORDER BY DatabaseOrder ASC + ) QueueDatabase + END + ELSE + BEGIN + SELECT TOP 1 @CurrentDBID = ID, + @CurrentDatabaseName = DatabaseName, + @CurrentDatabaseNameFS = DatabaseNameFS + FROM @tmpDatabases + WHERE Selected = 1 + AND Completed = 0 + ORDER BY [Order] ASC + END IF @@ROWCOUNT = 0 BEGIN @@ -2723,11 +2920,21 @@ BEGIN END -- Update that the database is completed - UPDATE @tmpDatabases - SET Completed = 1 - WHERE Selected = 1 - AND Completed = 0 - AND ID = @CurrentDBID + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + UPDATE dbo.QueueDatabase + SET DatabaseEndTime = GETDATE() + WHERE QueueID = @QueueID + AND DatabaseName = @CurrentDatabaseName + END + ELSE + BEGIN + UPDATE @tmpDatabases + SET Completed = 1 + WHERE Selected = 1 + AND Completed = 0 + AND ID = @CurrentDBID + END -- Clear variables SET @CurrentDBID = NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 3b4c87b8..dbba2770 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -24,6 +24,7 @@ ALTER PROCEDURE [dbo].[DatabaseIntegrityCheck] @TimeLimit int = NULL, @LockTimeout int = NULL, @DatabaseOrder nvarchar(max) = NULL, +@ExecutionMode nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -35,7 +36,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-18 19:09:39 //-- + --// Version: 2018-06-20 20:30:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -55,6 +56,9 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @AmazonRDS bit + DECLARE @QueueID int + DECLARE @QueueStartTime datetime + DECLARE @CurrentDBID int DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -211,6 +215,7 @@ BEGIN SET @Parameters = @Parameters + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ExecutionMode = ' + ISNULL('''' + REPLACE(@ExecutionMode,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -267,6 +272,27 @@ BEGIN SET @Error = @@ERROR END + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'Queue') + BEGIN + SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'QueueDatabase') + BEGIN + SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @@TRANCOUNT <> 0 + BEGIN + SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @Error <> 0 BEGIN SET @ReturnCode = @Error @@ -732,6 +758,13 @@ BEGIN SET @Error = @@ERROR END + IF @ExecutionMode NOT IN('DATABASES_IN_PARALLEL') OR (@ExecutionMode IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + BEGIN + SET @ErrorMessage = 'The value for the parameter @ExecutionMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -973,6 +1006,103 @@ BEGIN SET [Order] = RowNumber END + ---------------------------------------------------------------------------------------------------- + --// Update the queue //-- + ---------------------------------------------------------------------------------------------------- + + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + + BEGIN TRY + + SELECT @QueueID = QueueID + FROM dbo.[Queue] + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @Parameters + + IF @QueueID IS NULL + BEGIN + BEGIN TRANSACTION + + SELECT @QueueID = QueueID + FROM dbo.[Queue] WITH (UPDLOCK, TABLOCK) + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @Parameters + + IF @QueueID IS NULL + BEGIN + INSERT INTO dbo.[Queue] (SchemaName, ObjectName, [Parameters]) + SELECT @SchemaName, @ObjectName, @Parameters + + SET @QueueID = SCOPE_IDENTITY() + END + + COMMIT TRANSACTION + END + + BEGIN TRANSACTION + + UPDATE [Queue] + SET QueueStartTime = GETDATE(), + SessionID = @@SPID, + RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), + RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID) + FROM dbo.[Queue] [Queue] + WHERE QueueID = @QueueID + AND NOT EXISTS (SELECT * + FROM sys.dm_exec_requests + WHERE session_id = [Queue].SessionID + AND request_id = [Queue].RequestID + AND start_time = [Queue].RequestStartTime) + AND NOT EXISTS (SELECT * + FROM dbo.QueueDatabase QueueDatabase + INNER JOIN sys.dm_exec_requests ON QueueDatabase.SessionID = session_id AND QueueDatabase.RequestID = request_id AND QueueDatabase.RequestStartTime = start_time + WHERE QueueDatabase.QueueID = @QueueID) + + IF @@ROWCOUNT = 1 + BEGIN + INSERT INTO dbo.QueueDatabase (QueueID, DatabaseName) + SELECT @QueueID AS QueueID, + DatabaseName + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName = tmpDatabases.DatabaseName AND QueueID = @QueueID) + + DELETE QueueDatabase + FROM dbo.QueueDatabase QueueDatabase + WHERE QueueID = @QueueID + AND NOT EXISTS (SELECT * FROM @tmpDatabases tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName AND Selected = 1) + + UPDATE QueueDatabase + SET DatabaseOrder = tmpDatabases.[Order] + FROM dbo.QueueDatabase QueueDatabase + INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + END + + COMMIT TRANSACTION + + SELECT @QueueStartTime = QueueStartTime + FROM dbo.[Queue] + WHERE QueueID = @QueueID + + END TRY + + BEGIN CATCH + IF XACT_STATE() <> 0 + BEGIN + ROLLBACK TRANSACTION + END + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + SET @ReturnCode = @Error + GOTO Logging + END CATCH + + END + ---------------------------------------------------------------------------------------------------- --// Execute commands //-- ---------------------------------------------------------------------------------------------------- @@ -980,12 +1110,48 @@ BEGIN WHILE (1 = 1) BEGIN - SELECT TOP 1 @CurrentDBID = ID, - @CurrentDatabaseName = DatabaseName - FROM @tmpDatabases - WHERE Selected = 1 - AND Completed = 0 - ORDER BY [Order] ASC + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + UPDATE QueueDatabase + SET DatabaseStartTime = NULL, + SessionID = NULL, + RequestID = NULL, + RequestStartTime = NULL + FROM dbo.QueueDatabase QueueDatabase + WHERE QueueID = @QueueID + AND DatabaseStartTime IS NOT NULL + AND DatabaseEndTime IS NULL + AND NOT EXISTS (SELECT * FROM sys.dm_exec_requests WHERE session_id = QueueDatabase.SessionID AND request_id = QueueDatabase.RequestID AND start_time = QueueDatabase.RequestStartTime) + + UPDATE QueueDatabase + SET DatabaseStartTime = GETDATE(), + DatabaseEndTime = NULL, + SessionID = @@SPID, + RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), + RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID), + @CurrentDatabaseName = DatabaseName + FROM (SELECT TOP 1 DatabaseStartTime, + DatabaseEndTime, + SessionID, + RequestID, + RequestStartTime, + DatabaseName + FROM dbo.QueueDatabase + WHERE QueueID = @QueueID + AND (DatabaseStartTime < @QueueStartTime OR DatabaseStartTime IS NULL) + AND NOT (DatabaseStartTime IS NOT NULL AND DatabaseEndTime IS NULL) + ORDER BY DatabaseOrder ASC + ) QueueDatabase + END + ELSE + BEGIN + SELECT TOP 1 @CurrentDBID = ID, + @CurrentDatabaseName = DatabaseName + FROM @tmpDatabases + WHERE Selected = 1 + AND Completed = 0 + ORDER BY [Order] ASC + END IF @@ROWCOUNT = 0 BEGIN @@ -1445,11 +1611,21 @@ BEGIN END -- Update that the database is completed - UPDATE @tmpDatabases - SET Completed = 1 - WHERE Selected = 1 - AND Completed = 0 - AND ID = @CurrentDBID + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + UPDATE dbo.QueueDatabase + SET DatabaseEndTime = GETDATE() + WHERE QueueID = @QueueID + AND DatabaseName = @CurrentDatabaseName + END + ELSE + BEGIN + UPDATE @tmpDatabases + SET Completed = 1 + WHERE Selected = 1 + AND Completed = 0 + AND ID = @CurrentDBID + END -- Clear variables SET @CurrentDBID = NULL diff --git a/IndexOptimize.sql b/IndexOptimize.sql index ed34eb99..2b0ea617 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -38,6 +38,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @AvailabilityGroups nvarchar(max) = NULL, @LockTimeout int = NULL, @DatabaseOrder nvarchar(max) = NULL, +@ExecutionMode nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -49,7 +50,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-18 19:09:39 //-- + --// Version: 2018-06-20 20:30:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -75,6 +76,9 @@ BEGIN DECLARE @PartitionLevelStatistics bit + DECLARE @QueueID int + DECLARE @QueueStartTime datetime + DECLARE @CurrentDBID int DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -294,6 +298,7 @@ BEGIN SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ExecutionMode = ' + ISNULL('''' + REPLACE(@ExecutionMode,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -350,6 +355,27 @@ BEGIN SET @Error = @@ERROR END + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'Queue') + BEGIN + SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'QueueDatabase') + BEGIN + SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @@TRANCOUNT <> 0 + BEGIN + SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @Error <> 0 BEGIN SET @ReturnCode = @Error @@ -920,6 +946,13 @@ BEGIN SET @Error = @@ERROR END + IF @ExecutionMode NOT IN('DATABASES_IN_PARALLEL') OR (@ExecutionMode IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + BEGIN + SET @ErrorMessage = 'The value for the parameter @ExecutionMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1067,6 +1100,103 @@ BEGIN SET [Order] = RowNumber END + ---------------------------------------------------------------------------------------------------- + --// Update the queue //-- + ---------------------------------------------------------------------------------------------------- + + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + + BEGIN TRY + + SELECT @QueueID = QueueID + FROM dbo.[Queue] + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @Parameters + + IF @QueueID IS NULL + BEGIN + BEGIN TRANSACTION + + SELECT @QueueID = QueueID + FROM dbo.[Queue] WITH (UPDLOCK, TABLOCK) + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @Parameters + + IF @QueueID IS NULL + BEGIN + INSERT INTO dbo.[Queue] (SchemaName, ObjectName, [Parameters]) + SELECT @SchemaName, @ObjectName, @Parameters + + SET @QueueID = SCOPE_IDENTITY() + END + + COMMIT TRANSACTION + END + + BEGIN TRANSACTION + + UPDATE [Queue] + SET QueueStartTime = GETDATE(), + SessionID = @@SPID, + RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), + RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID) + FROM dbo.[Queue] [Queue] + WHERE QueueID = @QueueID + AND NOT EXISTS (SELECT * + FROM sys.dm_exec_requests + WHERE session_id = [Queue].SessionID + AND request_id = [Queue].RequestID + AND start_time = [Queue].RequestStartTime) + AND NOT EXISTS (SELECT * + FROM dbo.QueueDatabase QueueDatabase + INNER JOIN sys.dm_exec_requests ON QueueDatabase.SessionID = session_id AND QueueDatabase.RequestID = request_id AND QueueDatabase.RequestStartTime = start_time + WHERE QueueDatabase.QueueID = @QueueID) + + IF @@ROWCOUNT = 1 + BEGIN + INSERT INTO dbo.QueueDatabase (QueueID, DatabaseName) + SELECT @QueueID AS QueueID, + DatabaseName + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName = tmpDatabases.DatabaseName AND QueueID = @QueueID) + + DELETE QueueDatabase + FROM dbo.QueueDatabase QueueDatabase + WHERE QueueID = @QueueID + AND NOT EXISTS (SELECT * FROM @tmpDatabases tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName AND Selected = 1) + + UPDATE QueueDatabase + SET DatabaseOrder = tmpDatabases.[Order] + FROM dbo.QueueDatabase QueueDatabase + INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + END + + COMMIT TRANSACTION + + SELECT @QueueStartTime = QueueStartTime + FROM dbo.[Queue] + WHERE QueueID = @QueueID + + END TRY + + BEGIN CATCH + IF XACT_STATE() <> 0 + BEGIN + ROLLBACK TRANSACTION + END + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + SET @ReturnCode = @Error + GOTO Logging + END CATCH + + END + ---------------------------------------------------------------------------------------------------- --// Execute commands //-- ---------------------------------------------------------------------------------------------------- @@ -1074,12 +1204,48 @@ BEGIN WHILE (1 = 1) BEGIN - SELECT TOP 1 @CurrentDBID = ID, - @CurrentDatabaseName = DatabaseName - FROM @tmpDatabases - WHERE Selected = 1 - AND Completed = 0 - ORDER BY [Order] ASC + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + UPDATE QueueDatabase + SET DatabaseStartTime = NULL, + SessionID = NULL, + RequestID = NULL, + RequestStartTime = NULL + FROM dbo.QueueDatabase QueueDatabase + WHERE QueueID = @QueueID + AND DatabaseStartTime IS NOT NULL + AND DatabaseEndTime IS NULL + AND NOT EXISTS (SELECT * FROM sys.dm_exec_requests WHERE session_id = QueueDatabase.SessionID AND request_id = QueueDatabase.RequestID AND start_time = QueueDatabase.RequestStartTime) + + UPDATE QueueDatabase + SET DatabaseStartTime = GETDATE(), + DatabaseEndTime = NULL, + SessionID = @@SPID, + RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), + RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID), + @CurrentDatabaseName = DatabaseName + FROM (SELECT TOP 1 DatabaseStartTime, + DatabaseEndTime, + SessionID, + RequestID, + RequestStartTime, + DatabaseName + FROM dbo.QueueDatabase + WHERE QueueID = @QueueID + AND (DatabaseStartTime < @QueueStartTime OR DatabaseStartTime IS NULL) + AND NOT (DatabaseStartTime IS NOT NULL AND DatabaseEndTime IS NULL) + ORDER BY DatabaseOrder ASC + ) QueueDatabase + END + ELSE + BEGIN + SELECT TOP 1 @CurrentDBID = ID, + @CurrentDatabaseName = DatabaseName + FROM @tmpDatabases + WHERE Selected = 1 + AND Completed = 0 + ORDER BY [Order] ASC + END IF @@ROWCOUNT = 0 BEGIN @@ -1945,11 +2111,21 @@ BEGIN END -- Update that the database is completed - UPDATE @tmpDatabases - SET Completed = 1 - WHERE Selected = 1 - AND Completed = 0 - AND ID = @CurrentDBID + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + UPDATE dbo.QueueDatabase + SET DatabaseEndTime = GETDATE() + WHERE QueueID = @QueueID + AND DatabaseName = @CurrentDatabaseName + END + ELSE + BEGIN + UPDATE @tmpDatabases + SET Completed = 1 + WHERE Selected = 1 + AND Completed = 0 + AND ID = @CurrentDBID + END -- Clear variables SET @CurrentDBID = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 9827ddc1..9deafb1b 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-06-18 19:09:39 +Version: 2018-06-20 20:30:47 You can contact me by e-mail at ola@hallengren.com. @@ -117,7 +117,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-18 19:09:39 //-- + --// Version: 2018-06-20 20:30:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -354,6 +354,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @FileExtensionLog nvarchar(max) = NULL, @Init nvarchar(max) = 'N', @DatabaseOrder nvarchar(max) = NULL, +@ExecutionMode nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -365,7 +366,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-18 19:09:39 //-- + --// Version: 2018-06-20 20:30:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -392,6 +393,9 @@ BEGIN DECLARE @DefaultDirectory nvarchar(4000) + DECLARE @QueueID int + DECLARE @QueueStartTime datetime + DECLARE @CurrentRootDirectoryID int DECLARE @CurrentRootDirectoryPath nvarchar(4000) @@ -467,6 +471,7 @@ BEGIN AvailabilityGroup bit, StartPosition int, DatabaseSize bigint, + LogSizeSinceLastLogBackup float, [Order] int, Selected bit, Completed bit, @@ -594,6 +599,7 @@ BEGIN SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ExecutionMode = ' + ISNULL('''' + REPLACE(@ExecutionMode,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -650,6 +656,27 @@ BEGIN SET @Error = @@ERROR END + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'Queue') + BEGIN + SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'QueueDatabase') + BEGIN + SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @@TRANCOUNT <> 0 + BEGIN + SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @AmazonRDS = 1 BEGIN SET @ErrorMessage = 'The stored procedure DatabaseBackup is not supported on Amazon RDS.' + CHAR(13) + CHAR(10) + ' ' @@ -1578,13 +1605,20 @@ BEGIN SET @Error = @@ERROR END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT (@Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END + IF @ExecutionMode NOT IN('DATABASES_IN_PARALLEL') OR (@ExecutionMode IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + BEGIN + SET @ErrorMessage = 'The value for the parameter @ExecutionMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1667,6 +1701,13 @@ BEGIN FROM @tmpDatabases tmpDatabases END + IF @DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') + BEGIN + UPDATE tmpDatabases + SET LogSizeSinceLastLogBackup = (SELECT log_since_last_log_backup_mb FROM sys.dm_db_log_stats(DB_ID(tmpDatabases.DatabaseName))) + FROM @tmpDatabases tmpDatabases + END + IF @DatabaseOrder IS NULL BEGIN WITH tmpDatabases AS ( @@ -1721,6 +1762,125 @@ BEGIN UPDATE tmpDatabases SET [Order] = RowNumber END + ELSE + IF @DatabaseOrder = 'LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY LogSizeSinceLastLogBackup ASC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + ELSE + IF @DatabaseOrder = 'LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC' + BEGIN + WITH tmpDatabases AS ( + SELECT DatabaseName, [Order], ROW_NUMBER() OVER (ORDER BY LogSizeSinceLastLogBackup DESC) AS RowNumber + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + ) + UPDATE tmpDatabases + SET [Order] = RowNumber + END + + ---------------------------------------------------------------------------------------------------- + --// Update the queue //-- + ---------------------------------------------------------------------------------------------------- + + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + + BEGIN TRY + + SELECT @QueueID = QueueID + FROM dbo.[Queue] + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @Parameters + + IF @QueueID IS NULL + BEGIN + BEGIN TRANSACTION + + SELECT @QueueID = QueueID + FROM dbo.[Queue] WITH (UPDLOCK, TABLOCK) + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @Parameters + + IF @QueueID IS NULL + BEGIN + INSERT INTO dbo.[Queue] (SchemaName, ObjectName, [Parameters]) + SELECT @SchemaName, @ObjectName, @Parameters + + SET @QueueID = SCOPE_IDENTITY() + END + + COMMIT TRANSACTION + END + + BEGIN TRANSACTION + + UPDATE [Queue] + SET QueueStartTime = GETDATE(), + SessionID = @@SPID, + RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), + RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID) + FROM dbo.[Queue] [Queue] + WHERE QueueID = @QueueID + AND NOT EXISTS (SELECT * + FROM sys.dm_exec_requests + WHERE session_id = [Queue].SessionID + AND request_id = [Queue].RequestID + AND start_time = [Queue].RequestStartTime) + AND NOT EXISTS (SELECT * + FROM dbo.QueueDatabase QueueDatabase + INNER JOIN sys.dm_exec_requests ON QueueDatabase.SessionID = session_id AND QueueDatabase.RequestID = request_id AND QueueDatabase.RequestStartTime = start_time + WHERE QueueDatabase.QueueID = @QueueID) + + IF @@ROWCOUNT = 1 + BEGIN + INSERT INTO dbo.QueueDatabase (QueueID, DatabaseName) + SELECT @QueueID AS QueueID, + DatabaseName + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName = tmpDatabases.DatabaseName AND QueueID = @QueueID) + + DELETE QueueDatabase + FROM dbo.QueueDatabase QueueDatabase + WHERE QueueID = @QueueID + AND NOT EXISTS (SELECT * FROM @tmpDatabases tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName AND Selected = 1) + + UPDATE QueueDatabase + SET DatabaseOrder = tmpDatabases.[Order] + FROM dbo.QueueDatabase QueueDatabase + INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + END + + COMMIT TRANSACTION + + SELECT @QueueStartTime = QueueStartTime + FROM dbo.[Queue] + WHERE QueueID = @QueueID + + END TRY + + BEGIN CATCH + IF XACT_STATE() <> 0 + BEGIN + ROLLBACK TRANSACTION + END + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + SET @ReturnCode = @Error + GOTO Logging + END CATCH + + END ---------------------------------------------------------------------------------------------------- --// Execute backup commands //-- @@ -1729,13 +1889,50 @@ BEGIN WHILE (1 = 1) BEGIN - SELECT TOP 1 @CurrentDBID = ID, - @CurrentDatabaseName = DatabaseName, - @CurrentDatabaseNameFS = DatabaseNameFS - FROM @tmpDatabases - WHERE Selected = 1 - AND Completed = 0 - ORDER BY [Order] ASC + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + UPDATE QueueDatabase + SET DatabaseStartTime = NULL, + SessionID = NULL, + RequestID = NULL, + RequestStartTime = NULL + FROM dbo.QueueDatabase QueueDatabase + WHERE QueueID = @QueueID + AND DatabaseStartTime IS NOT NULL + AND DatabaseEndTime IS NULL + AND NOT EXISTS (SELECT * FROM sys.dm_exec_requests WHERE session_id = QueueDatabase.SessionID AND request_id = QueueDatabase.RequestID AND start_time = QueueDatabase.RequestStartTime) + + UPDATE QueueDatabase + SET DatabaseStartTime = GETDATE(), + DatabaseEndTime = NULL, + SessionID = @@SPID, + RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), + RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID), + @CurrentDatabaseName = DatabaseName, + @CurrentDatabaseNameFS = (SELECT DatabaseNameFS FROM @tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName) + FROM (SELECT TOP 1 DatabaseStartTime, + DatabaseEndTime, + SessionID, + RequestID, + RequestStartTime, + DatabaseName + FROM dbo.QueueDatabase + WHERE QueueID = @QueueID + AND (DatabaseStartTime < @QueueStartTime OR DatabaseStartTime IS NULL) + AND NOT (DatabaseStartTime IS NOT NULL AND DatabaseEndTime IS NULL) + ORDER BY DatabaseOrder ASC + ) QueueDatabase + END + ELSE + BEGIN + SELECT TOP 1 @CurrentDBID = ID, + @CurrentDatabaseName = DatabaseName, + @CurrentDatabaseNameFS = DatabaseNameFS + FROM @tmpDatabases + WHERE Selected = 1 + AND Completed = 0 + ORDER BY [Order] ASC + END IF @@ROWCOUNT = 0 BEGIN @@ -3017,11 +3214,21 @@ BEGIN END -- Update that the database is completed - UPDATE @tmpDatabases - SET Completed = 1 - WHERE Selected = 1 - AND Completed = 0 - AND ID = @CurrentDBID + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + UPDATE dbo.QueueDatabase + SET DatabaseEndTime = GETDATE() + WHERE QueueID = @QueueID + AND DatabaseName = @CurrentDatabaseName + END + ELSE + BEGIN + UPDATE @tmpDatabases + SET Completed = 1 + WHERE Selected = 1 + AND Completed = 0 + AND ID = @CurrentDBID + END -- Clear variables SET @CurrentDBID = NULL @@ -3113,6 +3320,7 @@ ALTER PROCEDURE [dbo].[DatabaseIntegrityCheck] @TimeLimit int = NULL, @LockTimeout int = NULL, @DatabaseOrder nvarchar(max) = NULL, +@ExecutionMode nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -3124,7 +3332,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-18 19:09:39 //-- + --// Version: 2018-06-20 20:30:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3144,6 +3352,9 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @AmazonRDS bit + DECLARE @QueueID int + DECLARE @QueueStartTime datetime + DECLARE @CurrentDBID int DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -3300,6 +3511,7 @@ BEGIN SET @Parameters = @Parameters + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ExecutionMode = ' + ISNULL('''' + REPLACE(@ExecutionMode,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -3356,6 +3568,27 @@ BEGIN SET @Error = @@ERROR END + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'Queue') + BEGIN + SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'QueueDatabase') + BEGIN + SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @@TRANCOUNT <> 0 + BEGIN + SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @Error <> 0 BEGIN SET @ReturnCode = @Error @@ -3821,6 +4054,13 @@ BEGIN SET @Error = @@ERROR END + IF @ExecutionMode NOT IN('DATABASES_IN_PARALLEL') OR (@ExecutionMode IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + BEGIN + SET @ErrorMessage = 'The value for the parameter @ExecutionMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -4062,6 +4302,103 @@ BEGIN SET [Order] = RowNumber END + ---------------------------------------------------------------------------------------------------- + --// Update the queue //-- + ---------------------------------------------------------------------------------------------------- + + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + + BEGIN TRY + + SELECT @QueueID = QueueID + FROM dbo.[Queue] + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @Parameters + + IF @QueueID IS NULL + BEGIN + BEGIN TRANSACTION + + SELECT @QueueID = QueueID + FROM dbo.[Queue] WITH (UPDLOCK, TABLOCK) + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @Parameters + + IF @QueueID IS NULL + BEGIN + INSERT INTO dbo.[Queue] (SchemaName, ObjectName, [Parameters]) + SELECT @SchemaName, @ObjectName, @Parameters + + SET @QueueID = SCOPE_IDENTITY() + END + + COMMIT TRANSACTION + END + + BEGIN TRANSACTION + + UPDATE [Queue] + SET QueueStartTime = GETDATE(), + SessionID = @@SPID, + RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), + RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID) + FROM dbo.[Queue] [Queue] + WHERE QueueID = @QueueID + AND NOT EXISTS (SELECT * + FROM sys.dm_exec_requests + WHERE session_id = [Queue].SessionID + AND request_id = [Queue].RequestID + AND start_time = [Queue].RequestStartTime) + AND NOT EXISTS (SELECT * + FROM dbo.QueueDatabase QueueDatabase + INNER JOIN sys.dm_exec_requests ON QueueDatabase.SessionID = session_id AND QueueDatabase.RequestID = request_id AND QueueDatabase.RequestStartTime = start_time + WHERE QueueDatabase.QueueID = @QueueID) + + IF @@ROWCOUNT = 1 + BEGIN + INSERT INTO dbo.QueueDatabase (QueueID, DatabaseName) + SELECT @QueueID AS QueueID, + DatabaseName + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName = tmpDatabases.DatabaseName AND QueueID = @QueueID) + + DELETE QueueDatabase + FROM dbo.QueueDatabase QueueDatabase + WHERE QueueID = @QueueID + AND NOT EXISTS (SELECT * FROM @tmpDatabases tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName AND Selected = 1) + + UPDATE QueueDatabase + SET DatabaseOrder = tmpDatabases.[Order] + FROM dbo.QueueDatabase QueueDatabase + INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + END + + COMMIT TRANSACTION + + SELECT @QueueStartTime = QueueStartTime + FROM dbo.[Queue] + WHERE QueueID = @QueueID + + END TRY + + BEGIN CATCH + IF XACT_STATE() <> 0 + BEGIN + ROLLBACK TRANSACTION + END + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + SET @ReturnCode = @Error + GOTO Logging + END CATCH + + END + ---------------------------------------------------------------------------------------------------- --// Execute commands //-- ---------------------------------------------------------------------------------------------------- @@ -4069,12 +4406,48 @@ BEGIN WHILE (1 = 1) BEGIN - SELECT TOP 1 @CurrentDBID = ID, - @CurrentDatabaseName = DatabaseName - FROM @tmpDatabases - WHERE Selected = 1 - AND Completed = 0 - ORDER BY [Order] ASC + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + UPDATE QueueDatabase + SET DatabaseStartTime = NULL, + SessionID = NULL, + RequestID = NULL, + RequestStartTime = NULL + FROM dbo.QueueDatabase QueueDatabase + WHERE QueueID = @QueueID + AND DatabaseStartTime IS NOT NULL + AND DatabaseEndTime IS NULL + AND NOT EXISTS (SELECT * FROM sys.dm_exec_requests WHERE session_id = QueueDatabase.SessionID AND request_id = QueueDatabase.RequestID AND start_time = QueueDatabase.RequestStartTime) + + UPDATE QueueDatabase + SET DatabaseStartTime = GETDATE(), + DatabaseEndTime = NULL, + SessionID = @@SPID, + RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), + RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID), + @CurrentDatabaseName = DatabaseName + FROM (SELECT TOP 1 DatabaseStartTime, + DatabaseEndTime, + SessionID, + RequestID, + RequestStartTime, + DatabaseName + FROM dbo.QueueDatabase + WHERE QueueID = @QueueID + AND (DatabaseStartTime < @QueueStartTime OR DatabaseStartTime IS NULL) + AND NOT (DatabaseStartTime IS NOT NULL AND DatabaseEndTime IS NULL) + ORDER BY DatabaseOrder ASC + ) QueueDatabase + END + ELSE + BEGIN + SELECT TOP 1 @CurrentDBID = ID, + @CurrentDatabaseName = DatabaseName + FROM @tmpDatabases + WHERE Selected = 1 + AND Completed = 0 + ORDER BY [Order] ASC + END IF @@ROWCOUNT = 0 BEGIN @@ -4534,11 +4907,21 @@ BEGIN END -- Update that the database is completed - UPDATE @tmpDatabases - SET Completed = 1 - WHERE Selected = 1 - AND Completed = 0 - AND ID = @CurrentDBID + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + UPDATE dbo.QueueDatabase + SET DatabaseEndTime = GETDATE() + WHERE QueueID = @QueueID + AND DatabaseName = @CurrentDatabaseName + END + ELSE + BEGIN + UPDATE @tmpDatabases + SET Completed = 1 + WHERE Selected = 1 + AND Completed = 0 + AND ID = @CurrentDBID + END -- Clear variables SET @CurrentDBID = NULL @@ -4630,6 +5013,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @AvailabilityGroups nvarchar(max) = NULL, @LockTimeout int = NULL, @DatabaseOrder nvarchar(max) = NULL, +@ExecutionMode nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -4641,7 +5025,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-18 19:09:39 //-- + --// Version: 2018-06-20 20:30:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4667,6 +5051,9 @@ BEGIN DECLARE @PartitionLevelStatistics bit + DECLARE @QueueID int + DECLARE @QueueStartTime datetime + DECLARE @CurrentDBID int DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -4886,6 +5273,7 @@ BEGIN SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ExecutionMode = ' + ISNULL('''' + REPLACE(@ExecutionMode,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -4942,6 +5330,27 @@ BEGIN SET @Error = @@ERROR END + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'Queue') + BEGIN + SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'QueueDatabase') + BEGIN + SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF @@TRANCOUNT <> 0 + BEGIN + SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @Error <> 0 BEGIN SET @ReturnCode = @Error @@ -5512,6 +5921,13 @@ BEGIN SET @Error = @@ERROR END + IF @ExecutionMode NOT IN('DATABASES_IN_PARALLEL') OR (@ExecutionMode IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + BEGIN + SET @ErrorMessage = 'The value for the parameter @ExecutionMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -5659,6 +6075,103 @@ BEGIN SET [Order] = RowNumber END + ---------------------------------------------------------------------------------------------------- + --// Update the queue //-- + ---------------------------------------------------------------------------------------------------- + + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + + BEGIN TRY + + SELECT @QueueID = QueueID + FROM dbo.[Queue] + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @Parameters + + IF @QueueID IS NULL + BEGIN + BEGIN TRANSACTION + + SELECT @QueueID = QueueID + FROM dbo.[Queue] WITH (UPDLOCK, TABLOCK) + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @Parameters + + IF @QueueID IS NULL + BEGIN + INSERT INTO dbo.[Queue] (SchemaName, ObjectName, [Parameters]) + SELECT @SchemaName, @ObjectName, @Parameters + + SET @QueueID = SCOPE_IDENTITY() + END + + COMMIT TRANSACTION + END + + BEGIN TRANSACTION + + UPDATE [Queue] + SET QueueStartTime = GETDATE(), + SessionID = @@SPID, + RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), + RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID) + FROM dbo.[Queue] [Queue] + WHERE QueueID = @QueueID + AND NOT EXISTS (SELECT * + FROM sys.dm_exec_requests + WHERE session_id = [Queue].SessionID + AND request_id = [Queue].RequestID + AND start_time = [Queue].RequestStartTime) + AND NOT EXISTS (SELECT * + FROM dbo.QueueDatabase QueueDatabase + INNER JOIN sys.dm_exec_requests ON QueueDatabase.SessionID = session_id AND QueueDatabase.RequestID = request_id AND QueueDatabase.RequestStartTime = start_time + WHERE QueueDatabase.QueueID = @QueueID) + + IF @@ROWCOUNT = 1 + BEGIN + INSERT INTO dbo.QueueDatabase (QueueID, DatabaseName) + SELECT @QueueID AS QueueID, + DatabaseName + FROM @tmpDatabases tmpDatabases + WHERE Selected = 1 + AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName = tmpDatabases.DatabaseName AND QueueID = @QueueID) + + DELETE QueueDatabase + FROM dbo.QueueDatabase QueueDatabase + WHERE QueueID = @QueueID + AND NOT EXISTS (SELECT * FROM @tmpDatabases tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName AND Selected = 1) + + UPDATE QueueDatabase + SET DatabaseOrder = tmpDatabases.[Order] + FROM dbo.QueueDatabase QueueDatabase + INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + END + + COMMIT TRANSACTION + + SELECT @QueueStartTime = QueueStartTime + FROM dbo.[Queue] + WHERE QueueID = @QueueID + + END TRY + + BEGIN CATCH + IF XACT_STATE() <> 0 + BEGIN + ROLLBACK TRANSACTION + END + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + SET @ReturnCode = @Error + GOTO Logging + END CATCH + + END + ---------------------------------------------------------------------------------------------------- --// Execute commands //-- ---------------------------------------------------------------------------------------------------- @@ -5666,12 +6179,48 @@ BEGIN WHILE (1 = 1) BEGIN - SELECT TOP 1 @CurrentDBID = ID, - @CurrentDatabaseName = DatabaseName - FROM @tmpDatabases - WHERE Selected = 1 - AND Completed = 0 - ORDER BY [Order] ASC + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + UPDATE QueueDatabase + SET DatabaseStartTime = NULL, + SessionID = NULL, + RequestID = NULL, + RequestStartTime = NULL + FROM dbo.QueueDatabase QueueDatabase + WHERE QueueID = @QueueID + AND DatabaseStartTime IS NOT NULL + AND DatabaseEndTime IS NULL + AND NOT EXISTS (SELECT * FROM sys.dm_exec_requests WHERE session_id = QueueDatabase.SessionID AND request_id = QueueDatabase.RequestID AND start_time = QueueDatabase.RequestStartTime) + + UPDATE QueueDatabase + SET DatabaseStartTime = GETDATE(), + DatabaseEndTime = NULL, + SessionID = @@SPID, + RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), + RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID), + @CurrentDatabaseName = DatabaseName + FROM (SELECT TOP 1 DatabaseStartTime, + DatabaseEndTime, + SessionID, + RequestID, + RequestStartTime, + DatabaseName + FROM dbo.QueueDatabase + WHERE QueueID = @QueueID + AND (DatabaseStartTime < @QueueStartTime OR DatabaseStartTime IS NULL) + AND NOT (DatabaseStartTime IS NOT NULL AND DatabaseEndTime IS NULL) + ORDER BY DatabaseOrder ASC + ) QueueDatabase + END + ELSE + BEGIN + SELECT TOP 1 @CurrentDBID = ID, + @CurrentDatabaseName = DatabaseName + FROM @tmpDatabases + WHERE Selected = 1 + AND Completed = 0 + ORDER BY [Order] ASC + END IF @@ROWCOUNT = 0 BEGIN @@ -6537,11 +7086,21 @@ BEGIN END -- Update that the database is completed - UPDATE @tmpDatabases - SET Completed = 1 - WHERE Selected = 1 - AND Completed = 0 - AND ID = @CurrentDBID + IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + BEGIN + UPDATE dbo.QueueDatabase + SET DatabaseEndTime = GETDATE() + WHERE QueueID = @QueueID + AND DatabaseName = @CurrentDatabaseName + END + ELSE + BEGIN + UPDATE @tmpDatabases + SET Completed = 1 + WHERE Selected = 1 + AND Completed = 0 + AND ID = @CurrentDBID + END -- Clear variables SET @CurrentDBID = NULL diff --git a/Queue.sql b/Queue.sql new file mode 100644 index 00000000..3d8f6f38 --- /dev/null +++ b/Queue.sql @@ -0,0 +1,23 @@ +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Queue]') AND type in (N'U')) +BEGIN +CREATE TABLE [dbo].[Queue]( + [QueueID] [int] IDENTITY(1,1) NOT NULL, + [SchemaName] [sysname] NOT NULL, + [ObjectName] [sysname] NOT NULL, + [Parameters] [nvarchar](max) NOT NULL, + [QueueStartTime] [datetime] NULL, + [SessionID] [smallint] NULL, + [RequestID] [int] NULL, + [RequestStartTime] [datetime] NULL, + CONSTRAINT [PK_Queue] PRIMARY KEY CLUSTERED +( + [QueueID] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) +) +END +GO + diff --git a/QueueDatabase.sql b/QueueDatabase.sql new file mode 100644 index 00000000..53d1170b --- /dev/null +++ b/QueueDatabase.sql @@ -0,0 +1,31 @@ +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[QueueDatabase]') AND type in (N'U')) +BEGIN +CREATE TABLE [dbo].[QueueDatabase]( + [QueueID] [int] NOT NULL, + [DatabaseName] [sysname] NOT NULL, + [DatabaseOrder] [int] NULL, + [DatabaseStartTime] [datetime] NULL, + [DatabaseEndTime] [datetime] NULL, + [SessionID] [smallint] NULL, + [RequestID] [int] NULL, + [RequestStartTime] [datetime] NULL, + CONSTRAINT [PK_QueueDatabase] PRIMARY KEY CLUSTERED +( + [QueueID] ASC, + [DatabaseName] ASC +)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) +) +END +GO +IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_QueueDatabase_Queue]') AND parent_object_id = OBJECT_ID(N'[dbo].[QueueDatabase]')) +ALTER TABLE [dbo].[QueueDatabase] WITH CHECK ADD CONSTRAINT [FK_QueueDatabase_Queue] FOREIGN KEY([QueueID]) +REFERENCES [dbo].[Queue] ([QueueID]) +GO +IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_QueueDatabase_Queue]') AND parent_object_id = OBJECT_ID(N'[dbo].[QueueDatabase]')) +ALTER TABLE [dbo].[QueueDatabase] CHECK CONSTRAINT [FK_QueueDatabase_Queue] +GO + From 2386b72654966953339f3022057c16fb4ad6fdf3 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 20 Jun 2018 23:53:16 +0200 Subject: [PATCH 050/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 20 ++++++------ DatabaseIntegrityCheck.sql | 20 ++++++------ IndexOptimize.sql | 20 ++++++------ MaintenanceSolution.sql | 64 +++++++++++++++++++------------------- 5 files changed, 63 insertions(+), 63 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 5f47734a..d60e0490 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -33,7 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 20:30:47 //-- + --// Version: 2018-06-20 23:42:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index af607254..63b4da77 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -60,7 +60,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @FileExtensionLog nvarchar(max) = NULL, @Init nvarchar(max) = 'N', @DatabaseOrder nvarchar(max) = NULL, -@ExecutionMode nvarchar(max) = NULL, +@DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -72,7 +72,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 20:30:47 //-- + --// Version: 2018-06-20 23:42:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -305,7 +305,7 @@ BEGIN SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ExecutionMode = ' + ISNULL('''' + REPLACE(@ExecutionMode,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -362,14 +362,14 @@ BEGIN SET @Error = @@ERROR END - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'Queue') + IF @DatabasesInParallel = '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] = 'Queue') BEGIN SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'QueueDatabase') + IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1318,9 +1318,9 @@ BEGIN SET @Error = @@ERROR END - IF @ExecutionMode NOT IN('DATABASES_IN_PARALLEL') OR (@ExecutionMode IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @ExecutionMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END @@ -1495,7 +1495,7 @@ BEGIN --// Update the queue //-- ---------------------------------------------------------------------------------------------------- - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN BEGIN TRY @@ -1595,7 +1595,7 @@ BEGIN WHILE (1 = 1) BEGIN - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN UPDATE QueueDatabase SET DatabaseStartTime = NULL, @@ -2920,7 +2920,7 @@ BEGIN END -- Update that the database is completed - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN UPDATE dbo.QueueDatabase SET DatabaseEndTime = GETDATE() diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index dbba2770..d930e7dd 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -24,7 +24,7 @@ ALTER PROCEDURE [dbo].[DatabaseIntegrityCheck] @TimeLimit int = NULL, @LockTimeout int = NULL, @DatabaseOrder nvarchar(max) = NULL, -@ExecutionMode nvarchar(max) = NULL, +@DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -36,7 +36,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 20:30:47 //-- + --// Version: 2018-06-20 23:42:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -215,7 +215,7 @@ BEGIN SET @Parameters = @Parameters + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ExecutionMode = ' + ISNULL('''' + REPLACE(@ExecutionMode,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -272,14 +272,14 @@ BEGIN SET @Error = @@ERROR END - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'Queue') + IF @DatabasesInParallel = '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] = 'Queue') BEGIN SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'QueueDatabase') + IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -758,9 +758,9 @@ BEGIN SET @Error = @@ERROR END - IF @ExecutionMode NOT IN('DATABASES_IN_PARALLEL') OR (@ExecutionMode IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @ExecutionMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END @@ -1010,7 +1010,7 @@ BEGIN --// Update the queue //-- ---------------------------------------------------------------------------------------------------- - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN BEGIN TRY @@ -1110,7 +1110,7 @@ BEGIN WHILE (1 = 1) BEGIN - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN UPDATE QueueDatabase SET DatabaseStartTime = NULL, @@ -1611,7 +1611,7 @@ BEGIN END -- Update that the database is completed - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN UPDATE dbo.QueueDatabase SET DatabaseEndTime = GETDATE() diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 2b0ea617..90014518 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -38,7 +38,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @AvailabilityGroups nvarchar(max) = NULL, @LockTimeout int = NULL, @DatabaseOrder nvarchar(max) = NULL, -@ExecutionMode nvarchar(max) = NULL, +@DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -50,7 +50,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 20:30:47 //-- + --// Version: 2018-06-20 23:42:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -298,7 +298,7 @@ BEGIN SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ExecutionMode = ' + ISNULL('''' + REPLACE(@ExecutionMode,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -355,14 +355,14 @@ BEGIN SET @Error = @@ERROR END - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'Queue') + IF @DatabasesInParallel = '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] = 'Queue') BEGIN SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'QueueDatabase') + IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -946,9 +946,9 @@ BEGIN SET @Error = @@ERROR END - IF @ExecutionMode NOT IN('DATABASES_IN_PARALLEL') OR (@ExecutionMode IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @ExecutionMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END @@ -1104,7 +1104,7 @@ BEGIN --// Update the queue //-- ---------------------------------------------------------------------------------------------------- - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN BEGIN TRY @@ -1204,7 +1204,7 @@ BEGIN WHILE (1 = 1) BEGIN - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN UPDATE QueueDatabase SET DatabaseStartTime = NULL, @@ -2111,7 +2111,7 @@ BEGIN END -- Update that the database is completed - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN UPDATE dbo.QueueDatabase SET DatabaseEndTime = GETDATE() diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 9deafb1b..519abbfb 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-06-20 20:30:47 +Version: 2018-06-20 23:42:47 You can contact me by e-mail at ola@hallengren.com. @@ -117,7 +117,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 20:30:47 //-- + --// Version: 2018-06-20 23:42:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -354,7 +354,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @FileExtensionLog nvarchar(max) = NULL, @Init nvarchar(max) = 'N', @DatabaseOrder nvarchar(max) = NULL, -@ExecutionMode nvarchar(max) = NULL, +@DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -366,7 +366,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 20:30:47 //-- + --// Version: 2018-06-20 23:42:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -599,7 +599,7 @@ BEGIN SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ExecutionMode = ' + ISNULL('''' + REPLACE(@ExecutionMode,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -656,14 +656,14 @@ BEGIN SET @Error = @@ERROR END - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'Queue') + IF @DatabasesInParallel = '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] = 'Queue') BEGIN SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'QueueDatabase') + IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1612,9 +1612,9 @@ BEGIN SET @Error = @@ERROR END - IF @ExecutionMode NOT IN('DATABASES_IN_PARALLEL') OR (@ExecutionMode IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @ExecutionMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END @@ -1789,7 +1789,7 @@ BEGIN --// Update the queue //-- ---------------------------------------------------------------------------------------------------- - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN BEGIN TRY @@ -1889,7 +1889,7 @@ BEGIN WHILE (1 = 1) BEGIN - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN UPDATE QueueDatabase SET DatabaseStartTime = NULL, @@ -3214,7 +3214,7 @@ BEGIN END -- Update that the database is completed - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN UPDATE dbo.QueueDatabase SET DatabaseEndTime = GETDATE() @@ -3320,7 +3320,7 @@ ALTER PROCEDURE [dbo].[DatabaseIntegrityCheck] @TimeLimit int = NULL, @LockTimeout int = NULL, @DatabaseOrder nvarchar(max) = NULL, -@ExecutionMode nvarchar(max) = NULL, +@DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -3332,7 +3332,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 20:30:47 //-- + --// Version: 2018-06-20 23:42:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3511,7 +3511,7 @@ BEGIN SET @Parameters = @Parameters + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ExecutionMode = ' + ISNULL('''' + REPLACE(@ExecutionMode,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -3568,14 +3568,14 @@ BEGIN SET @Error = @@ERROR END - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'Queue') + IF @DatabasesInParallel = '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] = 'Queue') BEGIN SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'QueueDatabase') + IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -4054,9 +4054,9 @@ BEGIN SET @Error = @@ERROR END - IF @ExecutionMode NOT IN('DATABASES_IN_PARALLEL') OR (@ExecutionMode IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @ExecutionMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END @@ -4306,7 +4306,7 @@ BEGIN --// Update the queue //-- ---------------------------------------------------------------------------------------------------- - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN BEGIN TRY @@ -4406,7 +4406,7 @@ BEGIN WHILE (1 = 1) BEGIN - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN UPDATE QueueDatabase SET DatabaseStartTime = NULL, @@ -4907,7 +4907,7 @@ BEGIN END -- Update that the database is completed - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN UPDATE dbo.QueueDatabase SET DatabaseEndTime = GETDATE() @@ -5013,7 +5013,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @AvailabilityGroups nvarchar(max) = NULL, @LockTimeout int = NULL, @DatabaseOrder nvarchar(max) = NULL, -@ExecutionMode nvarchar(max) = NULL, +@DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -5025,7 +5025,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 20:30:47 //-- + --// Version: 2018-06-20 23:42:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5273,7 +5273,7 @@ BEGIN SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ExecutionMode = ' + ISNULL('''' + REPLACE(@ExecutionMode,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -5330,14 +5330,14 @@ BEGIN SET @Error = @@ERROR END - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'Queue') + IF @DatabasesInParallel = '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] = 'Queue') BEGIN SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' 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] = 'QueueDatabase') + IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -5921,9 +5921,9 @@ BEGIN SET @Error = @@ERROR END - IF @ExecutionMode NOT IN('DATABASES_IN_PARALLEL') OR (@ExecutionMode IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @ExecutionMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END @@ -6079,7 +6079,7 @@ BEGIN --// Update the queue //-- ---------------------------------------------------------------------------------------------------- - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN BEGIN TRY @@ -6179,7 +6179,7 @@ BEGIN WHILE (1 = 1) BEGIN - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN UPDATE QueueDatabase SET DatabaseStartTime = NULL, @@ -7086,7 +7086,7 @@ BEGIN END -- Update that the database is completed - IF @ExecutionMode = 'DATABASES_IN_PARALLEL' + IF @DatabasesInParallel = 'Y' BEGIN UPDATE dbo.QueueDatabase SET DatabaseEndTime = GETDATE() From f83654c1d8b382472ee29e84ec0f5c8f4ba0a497 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 20 Jun 2018 23:53:45 +0200 Subject: [PATCH 051/188] Add files via upload From 097eb557ba4100ff690a21d020dbc88cdb0fb528 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 20 Jun 2018 23:54:12 +0200 Subject: [PATCH 052/188] Add files via upload From c989ef4aa6709eb07f6adef9d682002032d86e96 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 23 Jun 2018 11:30:06 +0200 Subject: [PATCH 053/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 4 ++-- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 ++++++------ 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index d60e0490..9cfc823c 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -33,7 +33,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 23:42:47 //-- + --// Version: 2018-06-23 11:25:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 63b4da77..e21d9ec8 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -72,7 +72,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 23:42:47 //-- + --// Version: 2018-06-23 11:25:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index d930e7dd..64924d2c 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -36,7 +36,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 23:42:47 //-- + --// Version: 2018-06-23 11:25:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -751,7 +751,7 @@ BEGIN SET @Error = @@ERROR END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 13.05026 AND @Version < 14)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 90014518..f524bec2 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -50,7 +50,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 23:42:47 //-- + --// Version: 2018-06-23 11:25:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 519abbfb..eda55e2d 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-06-20 23:42:47 +Version: 2018-06-23 11:25:41 You can contact me by e-mail at ola@hallengren.com. @@ -117,7 +117,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 23:42:47 //-- + --// Version: 2018-06-23 11:25:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -366,7 +366,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 23:42:47 //-- + --// Version: 2018-06-23 11:25:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3332,7 +3332,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 23:42:47 //-- + --// Version: 2018-06-23 11:25:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4047,7 +4047,7 @@ BEGIN SET @Error = @@ERROR END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 13.05026 AND @Version < 14)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -5025,7 +5025,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-20 23:42:47 //-- + --// Version: 2018-06-23 11:25:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From b87ef0bed4120b314b1dcef5275383e1eed08cc5 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 24 Jun 2018 15:33:57 +0200 Subject: [PATCH 054/188] Add files via upload --- CommandExecute.sql | 23 +++- DatabaseBackup.sql | 7 +- DatabaseIntegrityCheck.sql | 73 ++++++----- IndexOptimize.sql | 146 ++++++++++++--------- MaintenanceSolution.sql | 251 ++++++++++++++++++++++--------------- 5 files changed, 303 insertions(+), 197 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 9cfc823c..f4cdde00 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -22,6 +22,7 @@ ALTER PROCEDURE [dbo].[CommandExecute] @StatisticsName nvarchar(max) = NULL, @PartitionNumber int = NULL, @ExtendedInfo xml = NULL, +@LockMessageSeverity int = 16, @LogToTable nvarchar(max), @Execute nvarchar(max) @@ -33,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-23 11:25:41 //-- + --// Version: 2018-06-24 15:24:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -42,6 +43,7 @@ BEGIN DECLARE @EndMessage nvarchar(max) DECLARE @ErrorMessage nvarchar(max) DECLARE @ErrorMessageOriginal nvarchar(max) + DECLARE @Severity int DECLARE @StartTime datetime DECLARE @EndTime datetime @@ -99,6 +101,13 @@ BEGIN SET @Error = @@ERROR END + IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL + BEGIN + SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -166,10 +175,16 @@ BEGIN END TRY BEGIN CATCH SET @Error = ERROR_NUMBER() - SET @ReturnCode = @Error SET @ErrorMessageOriginal = ERROR_MESSAGE() - SET @ErrorMessage = 'Msg ' + CAST(@Error AS nvarchar) + ', ' + ISNULL(@ErrorMessageOriginal,'') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END + RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END END CATCH END diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index e21d9ec8..3397a29b 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -72,7 +72,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-23 11:25:41 //-- + --// Version: 2018-06-24 15:24:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -348,7 +348,7 @@ BEGIN SET @Error = @@ERROR END - IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND (OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LogToTable%' OR OBJECT_DEFINITION(objects.[object_id]) LIKE '%LOCK_TIMEOUT%')) + IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1581,8 +1581,7 @@ BEGIN END SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - SET @Error = @@ERROR - SET @ReturnCode = @Error + SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 64924d2c..fa8058ee 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -23,6 +23,7 @@ ALTER PROCEDURE [dbo].[DatabaseIntegrityCheck] @Updateability nvarchar(max) = 'ALL', @TimeLimit int = NULL, @LockTimeout int = NULL, +@LockMessageSeverity int = 16, @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -36,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-23 11:25:41 //-- + --// Version: 2018-06-24 15:24:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -45,6 +46,7 @@ BEGIN DECLARE @EndMessage nvarchar(max) DECLARE @DatabaseMessage nvarchar(max) DECLARE @ErrorMessage nvarchar(max) + DECLARE @Severity int DECLARE @StartTime datetime DECLARE @SchemaName nvarchar(max) @@ -214,6 +216,7 @@ BEGIN SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -258,7 +261,7 @@ BEGIN SET @Error = @@ERROR END - IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND (OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LogToTable%' OR OBJECT_DEFINITION(objects.[object_id]) LIKE '%LOCK_TIMEOUT%')) + IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -751,6 +754,13 @@ BEGIN SET @Error = @@ERROR END + IF @LockMessageSeverity NOT IN(10,16) + BEGIN + SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1096,8 +1106,7 @@ BEGIN END SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - SET @Error = @@ERROR - SET @ReturnCode = @Error + SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -1368,19 +1377,21 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups WHERE [type] <> ''FX'' AND filegroups.data_space_id = @ParamFileGroupID AND filegroups.[name] = @ParamFileGroupName) BEGIN SET @ParamFileGroupExists = 1 END' - EXECUTE sp_executesql @statement = @CurrentCommand03, @params = N'@ParamFileGroupID int, @ParamFileGroupName sysname, @ParamFileGroupExists bit OUTPUT', @ParamFileGroupID = @CurrentFileGroupID, @ParamFileGroupName = @CurrentFileGroupName, @ParamFileGroupExists = @CurrentFileGroupExists OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentFileGroupExists IS NULL SET @CurrentFileGroupExists = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The file group ' + QUOTENAME(@CurrentFileGroupName) + ' in the database ' + QUOTENAME(@CurrentDatabaseName) + ' is locked. It could not be checked if the filegroup exists.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - END + BEGIN TRY + EXECUTE sp_executesql @statement = @CurrentCommand03, @params = N'@ParamFileGroupID int, @ParamFileGroupName sysname, @ParamFileGroupExists bit OUTPUT', @ParamFileGroupID = @CurrentFileGroupID, @ParamFileGroupName = @CurrentFileGroupName, @ParamFileGroupExists = @CurrentFileGroupExists OUTPUT + + IF @CurrentFileGroupExists IS NULL SET @CurrentFileGroupExists = 0 + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + ' The file group ' + QUOTENAME(@CurrentFileGroupName) + ' in the database ' + QUOTENAME(@CurrentDatabaseName) + ' is locked. It could not be checked if the filegroup exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END + RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END + END CATCH IF @CurrentFileGroupExists = 1 BEGIN @@ -1527,19 +1538,21 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand07 = @CurrentCommand07 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType) BEGIN SET @ParamObjectExists = 1 END' - EXECUTE sp_executesql @statement = @CurrentCommand07, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamObjectExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamObjectExists = @CurrentObjectExists OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentObjectExists IS NULL SET @CurrentObjectExists = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the object exists.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - END + BEGIN TRY + EXECUTE sp_executesql @statement = @CurrentCommand07, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamObjectExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamObjectExists = @CurrentObjectExists OUTPUT + + IF @CurrentObjectExists IS NULL SET @CurrentObjectExists = 0 + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + 'The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the object exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END + RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END + END CATCH IF @CurrentObjectExists = 1 BEGIN diff --git a/IndexOptimize.sql b/IndexOptimize.sql index f524bec2..b9424c0b 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -37,6 +37,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @Resumable nvarchar(max) = 'N', @AvailabilityGroups nvarchar(max) = NULL, @LockTimeout int = NULL, +@LockMessageSeverity int = 16, @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -50,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-23 11:25:41 //-- + --// Version: 2018-06-24 15:24:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -63,6 +64,7 @@ BEGIN DECLARE @EndMessage nvarchar(max) DECLARE @DatabaseMessage nvarchar(max) DECLARE @ErrorMessage nvarchar(max) + DECLARE @Severity int DECLARE @StartTime datetime DECLARE @SchemaName nvarchar(max) @@ -297,6 +299,7 @@ BEGIN SET @Parameters = @Parameters + ', @Resumable = ' + ISNULL('''' + REPLACE(@Resumable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -341,7 +344,7 @@ BEGIN SET @Error = @@ERROR END - IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND (OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LogToTable%' OR OBJECT_DEFINITION(objects.[object_id]) LIKE '%LOCK_TIMEOUT%')) + IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -939,6 +942,13 @@ BEGIN SET @Error = @@ERROR END + IF @LockMessageSeverity NOT IN(10,16) + BEGIN + SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -1190,8 +1200,7 @@ BEGIN END SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - SET @Error = @@ERROR - SET @ReturnCode = @Error + SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -1591,21 +1600,27 @@ BEGIN IF @CurrentIsPartition = 0 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' IF @CurrentIsPartition = 1 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' - EXECUTE sp_executesql @statement = @CurrentCommand02, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentIndexExists IS NULL SET @CurrentIndexExists = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index exists.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error + BEGIN TRY + EXECUTE sp_executesql @statement = @CurrentCommand02, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT + + IF @CurrentIndexExists IS NULL + BEGIN + SET @CurrentIndexExists = 0 + GOTO NoAction + END + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END + RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END + GOTO NoAction - END - IF @CurrentIndexExists = 0 GOTO NoAction + END CATCH END -- Does the statistics exist? @@ -1618,21 +1633,27 @@ BEGIN SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM sys.stats stats INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' - EXECUTE sp_executesql @statement = @CurrentCommand03, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentStatisticsExists IS NULL SET @CurrentStatisticsExists = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the statistics exists.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error + BEGIN TRY + EXECUTE sp_executesql @statement = @CurrentCommand03, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT + + IF @CurrentStatisticsExists IS NULL + BEGIN + SET @CurrentStatisticsExists = 0 + GOTO NoAction + END + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the statistics exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END + RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END + GOTO NoAction - END - IF @CurrentStatisticsExists = 0 GOTO NoAction + END CATCH END -- Has the data in the statistics been modified since the statistics was last updated? @@ -1657,21 +1678,24 @@ BEGIN SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = rowcnt, @ParamModificationCounter = rowmodctr FROM sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID' END - EXECUTE sp_executesql @statement = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentRowCount IS NULL SET @CurrentRowCount = 0 - IF @Error = 0 AND @CurrentModificationCounter IS NULL SET @CurrentModificationCounter = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if any rows has been modified since the most recent statistics update.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error + BEGIN TRY + EXECUTE sp_executesql @statement = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT + + IF @CurrentRowCount IS NULL SET @CurrentRowCount = 0 + IF @CurrentModificationCounter IS NULL SET @CurrentModificationCounter = 0 + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The rows and modification_counter could not be checked.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END + RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END + GOTO NoAction - END + END CATCH END -- Is the index fragmented? @@ -1686,19 +1710,21 @@ BEGIN SET @CurrentCommand05 = @CurrentCommand05 + 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(@ParamDatabaseID, @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' - EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamDatabaseID int, @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseID = @CurrentDatabaseID, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT - SET @Error = @@ERROR - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The size and fragmentation of the index could not be checked.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error + BEGIN TRY + EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamDatabaseID int, @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseID = @CurrentDatabaseID, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The page_count and avg_fragmentation_in_percent could not be checked.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END + RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END + GOTO NoAction - END + END CATCH END -- Select fragmentation group @@ -1951,7 +1977,7 @@ BEGIN IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand06 = @CurrentCommand06 + @CurrentAlterIndexWithClause - EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment06, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo06, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment06, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo06, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput06 = @Error IF @CurrentCommandOutput06 <> 0 SET @ReturnCode = @CurrentCommandOutput06 @@ -2018,7 +2044,7 @@ BEGIN IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' - EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput07 = @Error IF @CurrentCommandOutput07 <> 0 SET @ReturnCode = @CurrentCommandOutput07 diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index eda55e2d..ae3e7def 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-06-23 11:25:41 +Version: 2018-06-24 15:24:40 You can contact me by e-mail at ola@hallengren.com. @@ -106,6 +106,7 @@ ALTER PROCEDURE [dbo].[CommandExecute] @StatisticsName nvarchar(max) = NULL, @PartitionNumber int = NULL, @ExtendedInfo xml = NULL, +@LockMessageSeverity int = 16, @LogToTable nvarchar(max), @Execute nvarchar(max) @@ -117,7 +118,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-23 11:25:41 //-- + --// Version: 2018-06-24 15:24:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -126,6 +127,7 @@ BEGIN DECLARE @EndMessage nvarchar(max) DECLARE @ErrorMessage nvarchar(max) DECLARE @ErrorMessageOriginal nvarchar(max) + DECLARE @Severity int DECLARE @StartTime datetime DECLARE @EndTime datetime @@ -183,6 +185,13 @@ BEGIN SET @Error = @@ERROR END + IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL + BEGIN + SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -250,10 +259,16 @@ BEGIN END TRY BEGIN CATCH SET @Error = ERROR_NUMBER() - SET @ReturnCode = @Error SET @ErrorMessageOriginal = ERROR_MESSAGE() - SET @ErrorMessage = 'Msg ' + CAST(@Error AS nvarchar) + ', ' + ISNULL(@ErrorMessageOriginal,'') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END + RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END END CATCH END @@ -366,7 +381,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-23 11:25:41 //-- + --// Version: 2018-06-24 15:24:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -642,7 +657,7 @@ BEGIN SET @Error = @@ERROR END - IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND (OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LogToTable%' OR OBJECT_DEFINITION(objects.[object_id]) LIKE '%LOCK_TIMEOUT%')) + IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1875,8 +1890,7 @@ BEGIN END SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - SET @Error = @@ERROR - SET @ReturnCode = @Error + SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -3319,6 +3333,7 @@ ALTER PROCEDURE [dbo].[DatabaseIntegrityCheck] @Updateability nvarchar(max) = 'ALL', @TimeLimit int = NULL, @LockTimeout int = NULL, +@LockMessageSeverity int = 16, @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -3332,7 +3347,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-23 11:25:41 //-- + --// Version: 2018-06-24 15:24:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3341,6 +3356,7 @@ BEGIN DECLARE @EndMessage nvarchar(max) DECLARE @DatabaseMessage nvarchar(max) DECLARE @ErrorMessage nvarchar(max) + DECLARE @Severity int DECLARE @StartTime datetime DECLARE @SchemaName nvarchar(max) @@ -3510,6 +3526,7 @@ BEGIN SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -3554,7 +3571,7 @@ BEGIN SET @Error = @@ERROR END - IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND (OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LogToTable%' OR OBJECT_DEFINITION(objects.[object_id]) LIKE '%LOCK_TIMEOUT%')) + IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -4047,6 +4064,13 @@ BEGIN SET @Error = @@ERROR END + IF @LockMessageSeverity NOT IN(10,16) + BEGIN + SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -4392,8 +4416,7 @@ BEGIN END SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - SET @Error = @@ERROR - SET @ReturnCode = @Error + SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -4664,19 +4687,21 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups WHERE [type] <> ''FX'' AND filegroups.data_space_id = @ParamFileGroupID AND filegroups.[name] = @ParamFileGroupName) BEGIN SET @ParamFileGroupExists = 1 END' - EXECUTE sp_executesql @statement = @CurrentCommand03, @params = N'@ParamFileGroupID int, @ParamFileGroupName sysname, @ParamFileGroupExists bit OUTPUT', @ParamFileGroupID = @CurrentFileGroupID, @ParamFileGroupName = @CurrentFileGroupName, @ParamFileGroupExists = @CurrentFileGroupExists OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentFileGroupExists IS NULL SET @CurrentFileGroupExists = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The file group ' + QUOTENAME(@CurrentFileGroupName) + ' in the database ' + QUOTENAME(@CurrentDatabaseName) + ' is locked. It could not be checked if the filegroup exists.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - END + BEGIN TRY + EXECUTE sp_executesql @statement = @CurrentCommand03, @params = N'@ParamFileGroupID int, @ParamFileGroupName sysname, @ParamFileGroupExists bit OUTPUT', @ParamFileGroupID = @CurrentFileGroupID, @ParamFileGroupName = @CurrentFileGroupName, @ParamFileGroupExists = @CurrentFileGroupExists OUTPUT + + IF @CurrentFileGroupExists IS NULL SET @CurrentFileGroupExists = 0 + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + ' The file group ' + QUOTENAME(@CurrentFileGroupName) + ' in the database ' + QUOTENAME(@CurrentDatabaseName) + ' is locked. It could not be checked if the filegroup exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END + RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END + END CATCH IF @CurrentFileGroupExists = 1 BEGIN @@ -4823,19 +4848,21 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand07 = @CurrentCommand07 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType) BEGIN SET @ParamObjectExists = 1 END' - EXECUTE sp_executesql @statement = @CurrentCommand07, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamObjectExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamObjectExists = @CurrentObjectExists OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentObjectExists IS NULL SET @CurrentObjectExists = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the object exists.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - END + BEGIN TRY + EXECUTE sp_executesql @statement = @CurrentCommand07, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamObjectExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamObjectExists = @CurrentObjectExists OUTPUT + + IF @CurrentObjectExists IS NULL SET @CurrentObjectExists = 0 + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + 'The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the object exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END + RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END + END CATCH IF @CurrentObjectExists = 1 BEGIN @@ -5012,6 +5039,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @Resumable nvarchar(max) = 'N', @AvailabilityGroups nvarchar(max) = NULL, @LockTimeout int = NULL, +@LockMessageSeverity int = 16, @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -5025,7 +5053,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-23 11:25:41 //-- + --// Version: 2018-06-24 15:24:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5038,6 +5066,7 @@ BEGIN DECLARE @EndMessage nvarchar(max) DECLARE @DatabaseMessage nvarchar(max) DECLARE @ErrorMessage nvarchar(max) + DECLARE @Severity int DECLARE @StartTime datetime DECLARE @SchemaName nvarchar(max) @@ -5272,6 +5301,7 @@ BEGIN SET @Parameters = @Parameters + ', @Resumable = ' + ISNULL('''' + REPLACE(@Resumable,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters = @Parameters + ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -5316,7 +5346,7 @@ BEGIN SET @Error = @@ERROR END - IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND (OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LogToTable%' OR OBJECT_DEFINITION(objects.[object_id]) LIKE '%LOCK_TIMEOUT%')) + IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -5914,6 +5944,13 @@ BEGIN SET @Error = @@ERROR END + IF @LockMessageSeverity NOT IN(10,16) + BEGIN + SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -6165,8 +6202,7 @@ BEGIN END SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - SET @Error = @@ERROR - SET @ReturnCode = @Error + SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -6566,21 +6602,27 @@ BEGIN IF @CurrentIsPartition = 0 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' IF @CurrentIsPartition = 1 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' - EXECUTE sp_executesql @statement = @CurrentCommand02, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentIndexExists IS NULL SET @CurrentIndexExists = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index exists.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error + BEGIN TRY + EXECUTE sp_executesql @statement = @CurrentCommand02, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT + + IF @CurrentIndexExists IS NULL + BEGIN + SET @CurrentIndexExists = 0 + GOTO NoAction + END + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END + RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END + GOTO NoAction - END - IF @CurrentIndexExists = 0 GOTO NoAction + END CATCH END -- Does the statistics exist? @@ -6593,21 +6635,27 @@ BEGIN SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM sys.stats stats INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' - EXECUTE sp_executesql @statement = @CurrentCommand03, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentStatisticsExists IS NULL SET @CurrentStatisticsExists = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the statistics exists.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error + BEGIN TRY + EXECUTE sp_executesql @statement = @CurrentCommand03, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT + + IF @CurrentStatisticsExists IS NULL + BEGIN + SET @CurrentStatisticsExists = 0 + GOTO NoAction + END + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the statistics exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END + RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END + GOTO NoAction - END - IF @CurrentStatisticsExists = 0 GOTO NoAction + END CATCH END -- Has the data in the statistics been modified since the statistics was last updated? @@ -6632,21 +6680,24 @@ BEGIN SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = rowcnt, @ParamModificationCounter = rowmodctr FROM sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID' END - EXECUTE sp_executesql @statement = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT - SET @Error = @@ERROR - IF @Error = 0 AND @CurrentRowCount IS NULL SET @CurrentRowCount = 0 - IF @Error = 0 AND @CurrentModificationCounter IS NULL SET @CurrentModificationCounter = 0 - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if any rows has been modified since the most recent statistics update.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error + BEGIN TRY + EXECUTE sp_executesql @statement = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT + + IF @CurrentRowCount IS NULL SET @CurrentRowCount = 0 + IF @CurrentModificationCounter IS NULL SET @CurrentModificationCounter = 0 + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The rows and modification_counter could not be checked.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END + RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END + GOTO NoAction - END + END CATCH END -- Is the index fragmented? @@ -6661,19 +6712,21 @@ BEGIN SET @CurrentCommand05 = @CurrentCommand05 + 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(@ParamDatabaseID, @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' - EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamDatabaseID int, @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseID = @CurrentDatabaseID, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT - SET @Error = @@ERROR - IF @Error = 1222 - BEGIN - SET @ErrorMessage = 'The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The size and fragmentation of the index could not be checked.' + CHAR(13) + CHAR(10) + ' ' - SET @ErrorMessage = REPLACE(@ErrorMessage,'%','%%') - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT - END - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error + BEGIN TRY + EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamDatabaseID int, @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseID = @CurrentDatabaseID, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The page_count and avg_fragmentation_in_percent could not be checked.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END + RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END + GOTO NoAction - END + END CATCH END -- Select fragmentation group @@ -6926,7 +6979,7 @@ BEGIN IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand06 = @CurrentCommand06 + @CurrentAlterIndexWithClause - EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment06, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo06, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment06, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo06, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput06 = @Error IF @CurrentCommandOutput06 <> 0 SET @ReturnCode = @CurrentCommandOutput06 @@ -6993,7 +7046,7 @@ BEGIN IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' - EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput07 = @Error IF @CurrentCommandOutput07 <> 0 SET @ReturnCode = @CurrentCommandOutput07 From 073b8ee03edf03b8b1a442cca7f1d5b106076b3b Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 27 Jun 2018 21:13:01 +0200 Subject: [PATCH 055/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 82 ++++++++++++++++++++++++++++++---- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 90 +++++++++++++++++++++++++++++++++----- 5 files changed, 155 insertions(+), 23 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index f4cdde00..5f6bbdf9 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-24 15:24:40 //-- + --// Version: 2018-06-27 20:44:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 3397a29b..ca607b97 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -41,6 +41,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @MirrorDirectory nvarchar(max) = NULL, @MirrorCleanupTime int = NULL, @MirrorCleanupMode nvarchar(max) = 'AFTER_BACKUP', +@MirrorURL nvarchar(max) = NULL, @AvailabilityGroups nvarchar(max) = NULL, @Updateability nvarchar(max) = 'ALL', @AdaptiveCompression nvarchar(max) = NULL, @@ -72,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-24 15:24:40 //-- + --// Version: 2018-06-27 20:44:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -166,6 +167,10 @@ BEGIN Mirror bit, Completed bit) + DECLARE @URLs TABLE (ID int IDENTITY PRIMARY KEY, + DirectoryPath nvarchar(max), + Mirror bit) + DECLARE @DirectoryInfo TABLE (FileExists bit, FileIsADirectory bit, ParentDirectoryExists bit) @@ -217,6 +222,10 @@ BEGIN CreateOutput int, CleanupOutput int) + DECLARE @CurrentURLs TABLE (ID int PRIMARY KEY, + DirectoryPath nvarchar(max), + Mirror bit) + DECLARE @CurrentFiles TABLE ([Type] nvarchar(max), FilePath nvarchar(max), Mirror bit) @@ -286,6 +295,7 @@ BEGIN SET @Parameters = @Parameters + ', @MirrorDirectory = ' + ISNULL('''' + REPLACE(@MirrorDirectory,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @MirrorCleanupTime = ' + ISNULL(CAST(@MirrorCleanupTime AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @MirrorCleanupMode = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @MirrorURL = ' + ISNULL('''' + REPLACE(@MirrorURL,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL') @@ -807,6 +817,18 @@ BEGIN END END + ---------------------------------------------------------------------------------------------------- + --// Select URLs //-- + ---------------------------------------------------------------------------------------------------- + + INSERT INTO @URLs (DirectoryPath, Mirror) + SELECT @URL, 0 + WHERE @URL IS NOT NULL + + INSERT INTO @URLs (DirectoryPath, Mirror) + SELECT @MirrorURL, 1 + WHERE @MirrorURL IS NOT NULL + ---------------------------------------------------------------------------------------------------- --// Get directory separator //-- ---------------------------------------------------------------------------------------------------- @@ -821,10 +843,9 @@ BEGIN SET DirectoryPath = LEFT(DirectoryPath,LEN(DirectoryPath) - 1) WHERE RIGHT(DirectoryPath,1) = @DirectorySeparator - IF RIGHT(@URL,1) = @DirectorySeparator - BEGIN - SET @URL = LEFT(@URL,LEN(@URL) - 1) - END + UPDATE @URLs + SET DirectoryPath = LEFT(DirectoryPath,LEN(DirectoryPath) - 1) + WHERE RIGHT(DirectoryPath,1) = @DirectorySeparator ---------------------------------------------------------------------------------------------------- --// Get file extension //-- @@ -1160,6 +1181,13 @@ BEGIN SET @Error = @@ERROR END + IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL NOT LIKE 'https://%/%') OR (@MirrorURL IS NOT NULL AND @URL IS NULL) + BEGIN + SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -2074,6 +2102,13 @@ BEGIN FROM @Directories ORDER BY ID ASC + INSERT INTO @CurrentURLs (ID, DirectoryPath, Mirror) + SELECT ROW_NUMBER() OVER (ORDER BY ID), + DirectoryPath + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END, + Mirror + FROM @URLs + ORDER BY ID ASC + SELECT @CurrentDatabaseFileName = CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @AvailabilityGroupFileName ELSE @FileName @@ -2201,7 +2236,7 @@ BEGIN SELECT @CurrentMaxFilePathLength = CASE WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) - WHEN @URL IS NOT NULL THEN LEN(@URL + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END + @DirectorySeparator) + WHEN EXISTS (SELECT * FROM @CurrentURLs) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentURLs) END + LEN(REPLACE(REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '1' WHEN @NumberOfFiles >= 10 THEN '01' ELSE '' END)) @@ -2275,7 +2310,7 @@ BEGIN SELECT 1, 0 END - IF @URL IS NOT NULL + IF EXISTS (SELECT * FROM @CurrentURLs WHERE Mirror = 0) BEGIN SET @CurrentFileNumber = 0 @@ -2283,7 +2318,9 @@ BEGIN BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 - SET @CurrentDirectoryPath = @URL + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END + SELECT @CurrentDirectoryPath = DirectoryPath + FROM @CurrentURLs + WHERE Mirror = 0 SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) @@ -2301,6 +2338,34 @@ BEGIN SELECT 0, 0 END + IF EXISTS (SELECT * FROM @CurrentURLs WHERE Mirror = 1) + BEGIN + SET @CurrentFileNumber = 0 + + WHILE @CurrentFileNumber < @NumberOfFiles + BEGIN + SET @CurrentFileNumber = @CurrentFileNumber + 1 + + SELECT @CurrentDirectoryPath = DirectoryPath + FROM @CurrentURLs + WHERE Mirror = 1 + + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) + + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName + + INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) + SELECT 'URL', @CurrentFilePath, 1 + + SET @CurrentDirectoryPath = NULL + SET @CurrentFileName = NULL + SET @CurrentFilePath = NULL + END + + INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) + SELECT 1, 0 + END + -- Create directory IF @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) @@ -2975,6 +3040,7 @@ BEGIN SET @CurrentCommandType03 = NULL DELETE FROM @CurrentDirectories + DELETE FROM @CurrentURLs DELETE FROM @CurrentFiles DELETE FROM @CurrentCleanupDates DELETE FROM @CurrentBackupSet diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index fa8058ee..609eb288 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-24 15:24:40 //-- + --// Version: 2018-06-27 20:44:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index b9424c0b..ac25c854 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-24 15:24:40 //-- + --// Version: 2018-06-27 20:44:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index ae3e7def..d3c4e88a 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-06-24 15:24:40 +Version: 2018-06-27 20:44:12 You can contact me by e-mail at ola@hallengren.com. @@ -118,7 +118,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-24 15:24:40 //-- + --// Version: 2018-06-27 20:44:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -350,6 +350,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @MirrorDirectory nvarchar(max) = NULL, @MirrorCleanupTime int = NULL, @MirrorCleanupMode nvarchar(max) = 'AFTER_BACKUP', +@MirrorURL nvarchar(max) = NULL, @AvailabilityGroups nvarchar(max) = NULL, @Updateability nvarchar(max) = 'ALL', @AdaptiveCompression nvarchar(max) = NULL, @@ -381,7 +382,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-24 15:24:40 //-- + --// Version: 2018-06-27 20:44:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -475,6 +476,10 @@ BEGIN Mirror bit, Completed bit) + DECLARE @URLs TABLE (ID int IDENTITY PRIMARY KEY, + DirectoryPath nvarchar(max), + Mirror bit) + DECLARE @DirectoryInfo TABLE (FileExists bit, FileIsADirectory bit, ParentDirectoryExists bit) @@ -526,6 +531,10 @@ BEGIN CreateOutput int, CleanupOutput int) + DECLARE @CurrentURLs TABLE (ID int PRIMARY KEY, + DirectoryPath nvarchar(max), + Mirror bit) + DECLARE @CurrentFiles TABLE ([Type] nvarchar(max), FilePath nvarchar(max), Mirror bit) @@ -595,6 +604,7 @@ BEGIN SET @Parameters = @Parameters + ', @MirrorDirectory = ' + ISNULL('''' + REPLACE(@MirrorDirectory,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @MirrorCleanupTime = ' + ISNULL(CAST(@MirrorCleanupTime AS nvarchar),'NULL') SET @Parameters = @Parameters + ', @MirrorCleanupMode = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @MirrorURL = ' + ISNULL('''' + REPLACE(@MirrorURL,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL') @@ -1116,6 +1126,18 @@ BEGIN END END + ---------------------------------------------------------------------------------------------------- + --// Select URLs //-- + ---------------------------------------------------------------------------------------------------- + + INSERT INTO @URLs (DirectoryPath, Mirror) + SELECT @URL, 0 + WHERE @URL IS NOT NULL + + INSERT INTO @URLs (DirectoryPath, Mirror) + SELECT @MirrorURL, 1 + WHERE @MirrorURL IS NOT NULL + ---------------------------------------------------------------------------------------------------- --// Get directory separator //-- ---------------------------------------------------------------------------------------------------- @@ -1130,10 +1152,9 @@ BEGIN SET DirectoryPath = LEFT(DirectoryPath,LEN(DirectoryPath) - 1) WHERE RIGHT(DirectoryPath,1) = @DirectorySeparator - IF RIGHT(@URL,1) = @DirectorySeparator - BEGIN - SET @URL = LEFT(@URL,LEN(@URL) - 1) - END + UPDATE @URLs + SET DirectoryPath = LEFT(DirectoryPath,LEN(DirectoryPath) - 1) + WHERE RIGHT(DirectoryPath,1) = @DirectorySeparator ---------------------------------------------------------------------------------------------------- --// Get file extension //-- @@ -1469,6 +1490,13 @@ BEGIN SET @Error = @@ERROR END + IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL NOT LIKE 'https://%/%') OR (@MirrorURL IS NOT NULL AND @URL IS NULL) + BEGIN + SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' + CHAR(13) + CHAR(10) + ' ' @@ -2383,6 +2411,13 @@ BEGIN FROM @Directories ORDER BY ID ASC + INSERT INTO @CurrentURLs (ID, DirectoryPath, Mirror) + SELECT ROW_NUMBER() OVER (ORDER BY ID), + DirectoryPath + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END, + Mirror + FROM @URLs + ORDER BY ID ASC + SELECT @CurrentDatabaseFileName = CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @AvailabilityGroupFileName ELSE @FileName @@ -2510,7 +2545,7 @@ BEGIN SELECT @CurrentMaxFilePathLength = CASE WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) - WHEN @URL IS NOT NULL THEN LEN(@URL + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END + @DirectorySeparator) + WHEN EXISTS (SELECT * FROM @CurrentURLs) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentURLs) END + LEN(REPLACE(REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '1' WHEN @NumberOfFiles >= 10 THEN '01' ELSE '' END)) @@ -2584,7 +2619,7 @@ BEGIN SELECT 1, 0 END - IF @URL IS NOT NULL + IF EXISTS (SELECT * FROM @CurrentURLs WHERE Mirror = 0) BEGIN SET @CurrentFileNumber = 0 @@ -2592,7 +2627,9 @@ BEGIN BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 - SET @CurrentDirectoryPath = @URL + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END + SELECT @CurrentDirectoryPath = DirectoryPath + FROM @CurrentURLs + WHERE Mirror = 0 SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) @@ -2610,6 +2647,34 @@ BEGIN SELECT 0, 0 END + IF EXISTS (SELECT * FROM @CurrentURLs WHERE Mirror = 1) + BEGIN + SET @CurrentFileNumber = 0 + + WHILE @CurrentFileNumber < @NumberOfFiles + BEGIN + SET @CurrentFileNumber = @CurrentFileNumber + 1 + + SELECT @CurrentDirectoryPath = DirectoryPath + FROM @CurrentURLs + WHERE Mirror = 1 + + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) + + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName + + INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) + SELECT 'URL', @CurrentFilePath, 1 + + SET @CurrentDirectoryPath = NULL + SET @CurrentFileName = NULL + SET @CurrentFilePath = NULL + END + + INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) + SELECT 1, 0 + END + -- Create directory IF @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) @@ -3284,6 +3349,7 @@ BEGIN SET @CurrentCommandType03 = NULL DELETE FROM @CurrentDirectories + DELETE FROM @CurrentURLs DELETE FROM @CurrentFiles DELETE FROM @CurrentCleanupDates DELETE FROM @CurrentBackupSet @@ -3347,7 +3413,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-24 15:24:40 //-- + --// Version: 2018-06-27 20:44:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5053,7 +5119,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-24 15:24:40 //-- + --// Version: 2018-06-27 20:44:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 414500dd96d17578ee4207c86d8e4869c886cb22 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 10 Jul 2018 21:52:57 +0200 Subject: [PATCH 056/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index af3fae70..eaf350cf 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ You can also download the objects as separate scripts: - [CommandExecute](/CommandExecute.sql): Stored procedure to execute and log commands - [CommandLog](/CommandLog.sql): Table to log commands -Note that you always need CommandExecute, DatabaseBackup, DatabaseIntegrityCheck, and IndexOptimize are using it. +Note that you always need CommandExecute; DatabaseBackup, DatabaseIntegrityCheck, and IndexOptimize are using it. You need CommandLog if you are going to use the option to log commands to a table. Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, Azure SQL Database, and Azure SQL Database Managed Instance From 6647eed34c3950269cdd03cafc6066dd8b8e6b82 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 16 Jul 2018 22:01:34 +0200 Subject: [PATCH 057/188] Add files via upload --- CommandExecute.sql | 23 +++++- DatabaseBackup.sql | 41 +++++++--- DatabaseIntegrityCheck.sql | 43 +++++++--- IndexOptimize.sql | 37 +++++++-- MaintenanceSolution.sql | 158 +++++++++++++++++++++++++++++-------- 5 files changed, 239 insertions(+), 63 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 5f6bbdf9..fef71f62 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-27 20:44:12 //-- + --// Version: 2018-07-16 18:32:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -63,6 +63,27 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- + IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + 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') BEGIN SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index ca607b97..d0897d61 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-27 20:44:12 //-- + --// Version: 2018-07-16 18:32:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -351,6 +351,27 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- + IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' @@ -469,7 +490,7 @@ BEGIN BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, - 0 AS Selected + 0 AS Selected FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) @@ -480,12 +501,12 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, - LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - NULL AS AvailabilityGroup, - 0 AS [Order], - 0 AS Selected, - 0 AS Completed + LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, + CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + NULL AS AvailabilityGroup, + 0 AS [Order], + 0 AS Selected, + 0 AS Completed FROM sys.databases WHERE [name] <> 'tempdb' AND source_database_id IS NULL @@ -1429,14 +1450,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') - BEGIN + BEGIN UPDATE tmpDatabases SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) FROM @tmpDatabases tmpDatabases END IF @DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') - BEGIN + BEGIN UPDATE tmpDatabases SET LogSizeSinceLastLogBackup = (SELECT log_since_last_log_backup_mb FROM sys.dm_db_log_stats(DB_ID(tmpDatabases.DatabaseName))) FROM @tmpDatabases tmpDatabases diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 609eb288..7848bdf8 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-27 20:44:12 //-- + --// Version: 2018-07-16 18:32:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -254,6 +254,27 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- + IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' @@ -365,7 +386,7 @@ BEGIN BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, - 0 AS Selected + 0 AS Selected FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) @@ -376,12 +397,12 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], [Order], Selected, Completed) SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - NULL AS AvailabilityGroup, - CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], - 0 AS [Order], - 0 AS Selected, - 0 AS Completed + CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + NULL AS AvailabilityGroup, + CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], + 0 AS [Order], + 0 AS Selected, + 0 AS Completed FROM sys.databases ORDER BY [name] ASC @@ -891,21 +912,21 @@ BEGIN ---------------------------------------------------------------------------------------------------- IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') - BEGIN + BEGIN UPDATE tmpDatabases SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) FROM @tmpDatabases tmpDatabases END IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') - BEGIN + BEGIN UPDATE tmpDatabases SET LastGoodCheckDbTime = NULLIF(CAST(DATABASEPROPERTYEX (DatabaseName,'LastGoodCheckDbTime') AS datetime),'1900-01-01 00:00:00.000') FROM @tmpDatabases tmpDatabases END IF @DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') - BEGIN + BEGIN UPDATE tmpDatabases SET LastCommandTime = MaxStartTime FROM @tmpDatabases tmpDatabases diff --git a/IndexOptimize.sql b/IndexOptimize.sql index ac25c854..13000f5d 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-27 20:44:12 //-- + --// Version: 2018-07-16 18:32:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -337,6 +337,27 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- + IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' @@ -448,7 +469,7 @@ BEGIN BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, - 0 AS Selected + 0 AS Selected FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) @@ -459,11 +480,11 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - NULL AS AvailabilityGroup, - 0 AS [Order], - 0 AS Selected, - 0 AS Completed + CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + NULL AS AvailabilityGroup, + 0 AS [Order], + 0 AS Selected, + 0 AS Completed FROM sys.databases WHERE [name] <> 'tempdb' AND source_database_id IS NULL @@ -1049,7 +1070,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') - BEGIN + BEGIN UPDATE tmpDatabases SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) FROM @tmpDatabases tmpDatabases diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index d3c4e88a..0ce84286 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-06-27 20:44:12 +Version: 2018-07-16 18:32:21 You can contact me by e-mail at ola@hallengren.com. @@ -28,6 +28,7 @@ DECLARE @BackupDirectory nvarchar(max) DECLARE @CleanupTime int DECLARE @OutputFileDirectory nvarchar(max) DECLARE @LogToTable nvarchar(max) +DECLARE @ErrorMessage nvarchar(max) SET @CreateJobs = 'Y' -- Specify whether jobs should be created. SET @BackupDirectory = NULL -- Specify the backup root directory. If no directory is specified, the default backup directory is used. @@ -37,7 +38,14 @@ SET @LogToTable = 'Y' -- Log commands to a table. IF IS_SRVROLEMEMBER('sysadmin') = 0 AND NOT (DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa') BEGIN - RAISERROR('You need to be a member of the SysAdmin server role to install the SQL Server Maintenance Solution.',16,1) + SET @ErrorMessage = 'You need to be a member of the SysAdmin server role to install the SQL Server Maintenance Solution.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT +END + +IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 +BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT END IF OBJECT_ID('tempdb..#Config') IS NOT NULL DROP TABLE #Config @@ -118,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-27 20:44:12 //-- + --// Version: 2018-07-16 18:32:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -147,6 +155,27 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- + IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + 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') BEGIN SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' @@ -382,7 +411,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-27 20:44:12 //-- + --// Version: 2018-07-16 18:32:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -660,6 +689,27 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- + IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' @@ -778,7 +828,7 @@ BEGIN BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, - 0 AS Selected + 0 AS Selected FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) @@ -789,12 +839,12 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, - LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - NULL AS AvailabilityGroup, - 0 AS [Order], - 0 AS Selected, - 0 AS Completed + LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, + CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + NULL AS AvailabilityGroup, + 0 AS [Order], + 0 AS Selected, + 0 AS Completed FROM sys.databases WHERE [name] <> 'tempdb' AND source_database_id IS NULL @@ -1738,14 +1788,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') - BEGIN + BEGIN UPDATE tmpDatabases SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) FROM @tmpDatabases tmpDatabases END IF @DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') - BEGIN + BEGIN UPDATE tmpDatabases SET LogSizeSinceLastLogBackup = (SELECT log_since_last_log_backup_mb FROM sys.dm_db_log_stats(DB_ID(tmpDatabases.DatabaseName))) FROM @tmpDatabases tmpDatabases @@ -3413,7 +3463,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-27 20:44:12 //-- + --// Version: 2018-07-16 18:32:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3630,6 +3680,27 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- + IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' @@ -3741,7 +3812,7 @@ BEGIN BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, - 0 AS Selected + 0 AS Selected FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) @@ -3752,12 +3823,12 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], [Order], Selected, Completed) SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - NULL AS AvailabilityGroup, - CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], - 0 AS [Order], - 0 AS Selected, - 0 AS Completed + CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + NULL AS AvailabilityGroup, + CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], + 0 AS [Order], + 0 AS Selected, + 0 AS Completed FROM sys.databases ORDER BY [name] ASC @@ -4267,21 +4338,21 @@ BEGIN ---------------------------------------------------------------------------------------------------- IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') - BEGIN + BEGIN UPDATE tmpDatabases SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) FROM @tmpDatabases tmpDatabases END IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') - BEGIN + BEGIN UPDATE tmpDatabases SET LastGoodCheckDbTime = NULLIF(CAST(DATABASEPROPERTYEX (DatabaseName,'LastGoodCheckDbTime') AS datetime),'1900-01-01 00:00:00.000') FROM @tmpDatabases tmpDatabases END IF @DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') - BEGIN + BEGIN UPDATE tmpDatabases SET LastCommandTime = MaxStartTime FROM @tmpDatabases tmpDatabases @@ -5119,7 +5190,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-06-27 20:44:12 //-- + --// Version: 2018-07-16 18:32:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5405,6 +5476,27 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- + IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + + IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + SET @Error = @@ERROR + END + IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' @@ -5516,7 +5608,7 @@ BEGIN BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, - 0 AS Selected + 0 AS Selected FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) @@ -5527,11 +5619,11 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, - NULL AS AvailabilityGroup, - 0 AS [Order], - 0 AS Selected, - 0 AS Completed + CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + NULL AS AvailabilityGroup, + 0 AS [Order], + 0 AS Selected, + 0 AS Completed FROM sys.databases WHERE [name] <> 'tempdb' AND source_database_id IS NULL @@ -6117,7 +6209,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') - BEGIN + BEGIN UPDATE tmpDatabases SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) FROM @tmpDatabases tmpDatabases @@ -7256,7 +7348,7 @@ BEGIN END GO -IF (SELECT [Value] FROM #Config WHERE Name = 'CreateJobs') = 'Y' AND SERVERPROPERTY('EngineEdition') NOT IN(4, 5) AND (IS_SRVROLEMEMBER('sysadmin') = 1 OR (DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa')) +IF (SELECT [Value] FROM #Config WHERE Name = 'CreateJobs') = 'Y' AND SERVERPROPERTY('EngineEdition') NOT IN(4, 5) AND (IS_SRVROLEMEMBER('sysadmin') = 1 OR (DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa')) AND (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN DECLARE @BackupDirectory nvarchar(max) From 578f147b0446868c534af800494074fb07a79735 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 28 Oct 2018 14:02:20 +0100 Subject: [PATCH 058/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 3 ++- DatabaseIntegrityCheck.sql | 3 ++- IndexOptimize.sql | 3 ++- MaintenanceSolution.sql | 13 ++++++++----- 5 files changed, 15 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index fef71f62..c0d9c3e7 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-07-16 18:32:21 //-- + --// Version: 2018-10-28 13:55:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index d0897d61..02d676c5 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-07-16 18:32:21 //-- + --// Version: 2018-10-28 13:55:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1613,6 +1613,7 @@ BEGIN SET DatabaseOrder = tmpDatabases.[Order] FROM dbo.QueueDatabase QueueDatabase INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + WHERE QueueID = @QueueID END COMMIT TRANSACTION diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 7848bdf8..14d4b795 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-07-16 18:32:21 //-- + --// Version: 2018-10-28 13:55:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1110,6 +1110,7 @@ BEGIN SET DatabaseOrder = tmpDatabases.[Order] FROM dbo.QueueDatabase QueueDatabase INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + WHERE QueueID = @QueueID END COMMIT TRANSACTION diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 13000f5d..bcfada6f 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-07-16 18:32:21 //-- + --// Version: 2018-10-28 13:55:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1204,6 +1204,7 @@ BEGIN SET DatabaseOrder = tmpDatabases.[Order] FROM dbo.QueueDatabase QueueDatabase INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + WHERE QueueID = @QueueID END COMMIT TRANSACTION diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 0ce84286..d03ac4f9 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-07-16 18:32:21 +Version: 2018-10-28 13:55:49 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-07-16 18:32:21 //-- + --// Version: 2018-10-28 13:55:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -411,7 +411,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-07-16 18:32:21 //-- + --// Version: 2018-10-28 13:55:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1951,6 +1951,7 @@ BEGIN SET DatabaseOrder = tmpDatabases.[Order] FROM dbo.QueueDatabase QueueDatabase INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + WHERE QueueID = @QueueID END COMMIT TRANSACTION @@ -3463,7 +3464,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-07-16 18:32:21 //-- + --// Version: 2018-10-28 13:55:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4536,6 +4537,7 @@ BEGIN SET DatabaseOrder = tmpDatabases.[Order] FROM dbo.QueueDatabase QueueDatabase INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + WHERE QueueID = @QueueID END COMMIT TRANSACTION @@ -5190,7 +5192,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-07-16 18:32:21 //-- + --// Version: 2018-10-28 13:55:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6343,6 +6345,7 @@ BEGIN SET DatabaseOrder = tmpDatabases.[Order] FROM dbo.QueueDatabase QueueDatabase INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + WHERE QueueID = @QueueID END COMMIT TRANSACTION From e02d124c125cc30fef33fa7cd531f907b8588fb3 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 28 Oct 2018 14:49:15 +0100 Subject: [PATCH 059/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 4 ++-- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 ++++++------ 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index c0d9c3e7..d326dc58 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 13:55:49 //-- + --// Version: 2018-10-28 14:45:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 02d676c5..bd4d6a74 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 13:55:49 //-- + --// Version: 2018-10-28 14:45:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 14d4b795..33eaf478 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 13:55:49 //-- + --// Version: 2018-10-28 14:45:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -935,7 +935,7 @@ BEGIN WHERE CommandType = 'DBCC_CHECKDB' AND ErrorNumber = 0 GROUP BY DatabaseName) CommandLog - ON tmpDatabases.DatabaseName = CommandLog.DatabaseName + ON tmpDatabases.DatabaseName = CommandLog.DatabaseName COLLATE DATABASE_DEFAULT END IF @DatabaseOrder IS NULL diff --git a/IndexOptimize.sql b/IndexOptimize.sql index bcfada6f..f73b3002 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 13:55:49 //-- + --// Version: 2018-10-28 14:45:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index d03ac4f9..a54d496e 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-10-28 13:55:49 +Version: 2018-10-28 14:45:02 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 13:55:49 //-- + --// Version: 2018-10-28 14:45:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -411,7 +411,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 13:55:49 //-- + --// Version: 2018-10-28 14:45:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3464,7 +3464,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 13:55:49 //-- + --// Version: 2018-10-28 14:45:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4362,7 +4362,7 @@ BEGIN WHERE CommandType = 'DBCC_CHECKDB' AND ErrorNumber = 0 GROUP BY DatabaseName) CommandLog - ON tmpDatabases.DatabaseName = CommandLog.DatabaseName + ON tmpDatabases.DatabaseName = CommandLog.DatabaseName COLLATE DATABASE_DEFAULT END IF @DatabaseOrder IS NULL @@ -5192,7 +5192,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 13:55:49 //-- + --// Version: 2018-10-28 14:45:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From d7927be735e07cfe0986c93ac6ade9a8e32ed4ec Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 29 Dec 2018 14:11:51 +0100 Subject: [PATCH 060/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 6 +++--- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 14 +++++++------- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index d326dc58..8b0fb1c4 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 14:45:02 //-- + --// Version: 2018-12-29 14:02:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index bd4d6a74..a1864aee 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 14:45:02 //-- + --// Version: 2018-12-29 14:02:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -501,7 +501,7 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, - LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, + RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')) AS DatabaseNameFS, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, 0 AS [Order], @@ -1181,7 +1181,7 @@ BEGIN SET @Error = @@ERROR END - IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE credential_identity = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) + IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) BEGIN SET @ErrorMessage = 'The value for the parameter @Credential is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 33eaf478..b9e5dfd7 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 14:45:02 //-- + --// Version: 2018-12-29 14:02:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index f73b3002..31aecf02 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 14:45:02 //-- + --// Version: 2018-12-29 14:02:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index a54d496e..cee1f050 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-10-28 14:45:02 +Version: 2018-12-29 14:02:42 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 14:45:02 //-- + --// Version: 2018-12-29 14:02:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -411,7 +411,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 14:45:02 //-- + --// Version: 2018-12-29 14:02:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -839,7 +839,7 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, - LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) AS DatabaseNameFS, + RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')) AS DatabaseNameFS, CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, 0 AS [Order], @@ -1519,7 +1519,7 @@ BEGIN SET @Error = @@ERROR END - IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE credential_identity = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) + IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) BEGIN SET @ErrorMessage = 'The value for the parameter @Credential is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -3464,7 +3464,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 14:45:02 //-- + --// Version: 2018-12-29 14:02:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5192,7 +5192,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-10-28 14:45:02 //-- + --// Version: 2018-12-29 14:02:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 774f1393b74ef92171a9133331316ae64a0115e0 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 29 Dec 2018 17:16:31 +0100 Subject: [PATCH 061/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 18 +++++++++--------- DatabaseIntegrityCheck.sql | 4 ++-- IndexOptimize.sql | 4 ++-- MaintenanceSolution.sql | 30 +++++++++++++++--------------- 5 files changed, 29 insertions(+), 29 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 8b0fb1c4..f1f649ba 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 14:02:42 //-- + --// Version: 2018-12-29 16:42:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index a1864aee..9e1bfb45 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 14:02:42 //-- + --// Version: 2018-12-29 16:42:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1223,21 +1223,21 @@ BEGIN SET @Error = @@ERROR END - IF (@ModificationLevel IS NOT NULL AND NOT (@Version >= 13.05026)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') + IF (@ModificationLevel IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN SET @ErrorMessage = 'The value for the parameter @ModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 13.05026)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 13.05026)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @TimeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1360,7 +1360,7 @@ BEGIN SET @Error = @@ERROR END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT (@Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1745,7 +1745,7 @@ BEGIN WHERE database_id = @CurrentDatabaseID END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 13.05026 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) BEGIN SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_file_space_usage' @@ -1766,7 +1766,7 @@ BEGIN END END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 13.05026 + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) BEGIN SELECT @CurrentLastLogBackup = log_backup_time, @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb @@ -1876,7 +1876,7 @@ BEGIN SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT - IF @CurrentBackupType IN('DIFF','FULL') AND @Version >= 13.05026 + IF @CurrentBackupType IN('DIFF','FULL') AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) BEGIN SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT @@ -1885,7 +1885,7 @@ BEGIN RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT END - IF @CurrentBackupType = 'LOG' AND @Version >= 13.05026 + IF @CurrentBackupType = 'LOG' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) BEGIN SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),@CurrentLastLogBackup,120),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index b9e5dfd7..4273543b 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 14:02:42 //-- + --// Version: 2018-12-29 16:42:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -782,7 +782,7 @@ BEGIN SET @Error = @@ERROR END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 31aecf02..0b75847c 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 14:02:42 //-- + --// Version: 2018-12-29 16:42:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2021,7 +2021,7 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand07 = @CurrentCommand07 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) - IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) + IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index cee1f050..dfc5e14c 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-12-29 14:02:42 +Version: 2018-12-29 16:42:00 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 14:02:42 //-- + --// Version: 2018-12-29 16:42:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -411,7 +411,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 14:02:42 //-- + --// Version: 2018-12-29 16:42:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1561,21 +1561,21 @@ BEGIN SET @Error = @@ERROR END - IF (@ModificationLevel IS NOT NULL AND NOT (@Version >= 13.05026)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') + IF (@ModificationLevel IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN SET @ErrorMessage = 'The value for the parameter @ModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 13.05026)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT SET @Error = @@ERROR END - IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT (@Version >= 13.05026)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @TimeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -1698,7 +1698,7 @@ BEGIN SET @Error = @@ERROR END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT (@Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -2083,7 +2083,7 @@ BEGIN WHERE database_id = @CurrentDatabaseID END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 13.05026 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) BEGIN SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_file_space_usage' @@ -2104,7 +2104,7 @@ BEGIN END END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND @Version >= 13.05026 + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) BEGIN SELECT @CurrentLastLogBackup = log_backup_time, @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb @@ -2214,7 +2214,7 @@ BEGIN SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT - IF @CurrentBackupType IN('DIFF','FULL') AND @Version >= 13.05026 + IF @CurrentBackupType IN('DIFF','FULL') AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) BEGIN SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT @@ -2223,7 +2223,7 @@ BEGIN RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT END - IF @CurrentBackupType = 'LOG' AND @Version >= 13.05026 + IF @CurrentBackupType = 'LOG' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) BEGIN SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),@CurrentLastLogBackup,120),'N/A') RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT @@ -3464,7 +3464,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 14:02:42 //-- + --// Version: 2018-12-29 16:42:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4209,7 +4209,7 @@ BEGIN SET @Error = @@ERROR END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT @@ -5192,7 +5192,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 14:02:42 //-- + --// Version: 2018-12-29 16:42:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7162,7 +7162,7 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' SET @CurrentCommand07 = @CurrentCommand07 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) - IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) + IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) From 2b5f21ad3d38409ce0ae22664c0e7196b2fef7bb Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 29 Dec 2018 18:36:42 +0100 Subject: [PATCH 062/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 6 +++--- MaintenanceSolution.sql | 14 +++++++------- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index f1f649ba..b67ee3da 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 16:42:00 //-- + --// Version: 2018-12-29 18:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 9e1bfb45..24c84f1e 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 16:42:00 //-- + --// Version: 2018-12-29 18:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 4273543b..bcc98ed9 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 16:42:00 //-- + --// Version: 2018-12-29 18:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 0b75847c..308542f4 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 16:42:00 //-- + --// Version: 2018-12-29 18:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1881,7 +1881,7 @@ BEGIN SET @CurrentExtendedInfo06 = (SELECT * FROM (SELECT CAST(@CurrentPageCount AS nvarchar) AS [PageCount], CAST(@CurrentFragmentationLevel AS nvarchar) AS Fragmentation - ) ExtendedInfo FOR XML AUTO, ELEMENTS) + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END -- Create statistics comment @@ -1900,7 +1900,7 @@ BEGIN SET @CurrentExtendedInfo07 = (SELECT * FROM (SELECT CAST(@CurrentRowCount AS nvarchar) AS [RowCount], CAST(@CurrentModificationCounter AS nvarchar) AS ModificationCounter - ) ExtendedInfo FOR XML AUTO, ELEMENTS) + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END IF @CurrentIndexID IS NOT NULL AND @CurrentAction IS NOT NULL AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index dfc5e14c..84603da2 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-12-29 16:42:00 +Version: 2018-12-29 18:23:44 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 16:42:00 //-- + --// Version: 2018-12-29 18:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -411,7 +411,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 16:42:00 //-- + --// Version: 2018-12-29 18:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3464,7 +3464,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 16:42:00 //-- + --// Version: 2018-12-29 18:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5192,7 +5192,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 16:42:00 //-- + --// Version: 2018-12-29 18:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7022,7 +7022,7 @@ BEGIN SET @CurrentExtendedInfo06 = (SELECT * FROM (SELECT CAST(@CurrentPageCount AS nvarchar) AS [PageCount], CAST(@CurrentFragmentationLevel AS nvarchar) AS Fragmentation - ) ExtendedInfo FOR XML AUTO, ELEMENTS) + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END -- Create statistics comment @@ -7041,7 +7041,7 @@ BEGIN SET @CurrentExtendedInfo07 = (SELECT * FROM (SELECT CAST(@CurrentRowCount AS nvarchar) AS [RowCount], CAST(@CurrentModificationCounter AS nvarchar) AS ModificationCounter - ) ExtendedInfo FOR XML AUTO, ELEMENTS) + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END IF @CurrentIndexID IS NOT NULL AND @CurrentAction IS NOT NULL AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) From 77c5158d703c4e7698cabf73ba9f40cfddcc9410 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 29 Dec 2018 19:31:40 +0100 Subject: [PATCH 063/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 15 +++++++-------- MaintenanceSolution.sql | 23 +++++++++++------------ 5 files changed, 21 insertions(+), 23 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index b67ee3da..01b973fa 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 18:23:44 //-- + --// Version: 2018-12-29 19:23:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 24c84f1e..32476e04 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 18:23:44 //-- + --// Version: 2018-12-29 19:23:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index bcc98ed9..b0424c3c 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 18:23:44 //-- + --// Version: 2018-12-29 19:23:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 308542f4..51853fc8 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 18:23:44 //-- + --// Version: 2018-12-29 19:23:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1984,16 +1984,15 @@ BEGIN IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) BEGIN SET @CurrentAlterIndexWithClause = ' WITH (' - END - SELECT @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + Argument + ', ' - FROM @CurrentAlterIndexWithClauseArguments - ORDER BY ID ASC + SELECT @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + Argument + ', ' + FROM @CurrentAlterIndexWithClauseArguments + ORDER BY ID ASC - SET @CurrentAlterIndexWithClause = LEFT(@CurrentAlterIndexWithClause,LEN(@CurrentAlterIndexWithClause) - 1) + SET @CurrentAlterIndexWithClause = RTRIM(@CurrentAlterIndexWithClause) + + SET @CurrentAlterIndexWithClause = LEFT(@CurrentAlterIndexWithClause,LEN(@CurrentAlterIndexWithClause) - 1) - IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) - BEGIN SET @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + ')' END diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 84603da2..b1fd9239 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-12-29 18:23:44 +Version: 2018-12-29 19:23:12 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 18:23:44 //-- + --// Version: 2018-12-29 19:23:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -411,7 +411,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 18:23:44 //-- + --// Version: 2018-12-29 19:23:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3464,7 +3464,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 18:23:44 //-- + --// Version: 2018-12-29 19:23:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5192,7 +5192,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 18:23:44 //-- + --// Version: 2018-12-29 19:23:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7125,16 +7125,15 @@ BEGIN IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) BEGIN SET @CurrentAlterIndexWithClause = ' WITH (' - END - SELECT @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + Argument + ', ' - FROM @CurrentAlterIndexWithClauseArguments - ORDER BY ID ASC + SELECT @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + Argument + ', ' + FROM @CurrentAlterIndexWithClauseArguments + ORDER BY ID ASC - SET @CurrentAlterIndexWithClause = LEFT(@CurrentAlterIndexWithClause,LEN(@CurrentAlterIndexWithClause) - 1) + SET @CurrentAlterIndexWithClause = RTRIM(@CurrentAlterIndexWithClause) + + SET @CurrentAlterIndexWithClause = LEFT(@CurrentAlterIndexWithClause,LEN(@CurrentAlterIndexWithClause) - 1) - IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) - BEGIN SET @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + ')' END From 0c6bd28e8578147294f1cb1b0c1cc159f2633ef9 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 29 Dec 2018 19:34:37 +0100 Subject: [PATCH 064/188] Add files via upload From e8a673ef2d2456ce2d4104cda1d397bd615357ff Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 30 Dec 2018 11:31:43 +0100 Subject: [PATCH 065/188] Add files via upload --- CommandExecute.sql | 38 ++- DatabaseBackup.sql | 248 ++++++++-------- DatabaseIntegrityCheck.sql | 138 +++++---- IndexOptimize.sql | 164 +++++------ MaintenanceSolution.sql | 590 ++++++++++++++++++------------------- 5 files changed, 581 insertions(+), 597 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 01b973fa..30fecc5c 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 19:23:12 //-- + --// Version: 2018-12-30 11:14:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -66,28 +66,28 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END 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') BEGIN SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -104,42 +104,42 @@ BEGIN IF @Command IS NULL OR @Command = '' BEGIN SET @ErrorMessage = 'The value for the parameter @Command is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CommandType IS NULL OR @CommandType = '' OR LEN(@CommandType) > 60 BEGIN SET @ErrorMessage = 'The value for the parameter @CommandType is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Mode NOT IN(1,2) OR @Mode IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Mode is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -157,17 +157,15 @@ BEGIN SET @StartTimeSec = CONVERT(datetime,CONVERT(nvarchar,@StartTime,120),120) SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTimeSec,120) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Command: ' + @Command - SET @StartMessage = REPLACE(@StartMessage,'%','%%') - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT IF @Comment IS NOT NULL BEGIN SET @StartMessage = 'Comment: ' + @Comment - SET @StartMessage = REPLACE(@StartMessage,'%','%%') - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END IF @LogToTable = 'Y' @@ -200,7 +198,7 @@ BEGIN SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END - RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -217,13 +215,13 @@ BEGIN SET @EndTimeSec = CONVERT(datetime,CONVERT(varchar,@EndTime,120),120) SET @EndMessage = 'Outcome: ' + CASE WHEN @Execute = 'N' THEN 'Not Executed' WHEN @Error = 0 THEN 'Succeeded' ELSE 'Failed' END - RAISERROR(@EndMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT SET @EndMessage = 'Duration: ' + CASE WHEN DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) > 0 THEN CAST(DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) AS nvarchar) + '.' ELSE '' END + CONVERT(nvarchar,@EndTimeSec - @StartTimeSec,108) - RAISERROR(@EndMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTimeSec,120) + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@EndMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT IF @LogToTable = 'Y' BEGIN diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 32476e04..fb71ca59 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 19:23:12 //-- + --// Version: 2018-12-30 11:14:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -320,32 +320,31 @@ BEGIN SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Platform: ' + @HostPlatform - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Parameters: ' + @Parameters - SET @StartMessage = REPLACE(@StartMessage,'%','%%') - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + @VersionTimestamp - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- @@ -354,70 +353,70 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END 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') BEGIN SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel = '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] = 'Queue') BEGIN SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @@TRANCOUNT <> 0 BEGIN SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @AmazonRDS = 1 BEGIN SET @ErrorMessage = 'The stored procedure DatabaseBackup is not supported on Amazon RDS.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -550,7 +549,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -646,21 +645,21 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -677,7 +676,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -692,7 +691,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -789,7 +788,7 @@ BEGIN IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR SET @DirectoryCheck = 0 END @@ -797,7 +796,7 @@ BEGIN IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR SET @DirectoryCheck = 0 END @@ -823,7 +822,7 @@ BEGIN IF NOT EXISTS (SELECT * FROM @DirectoryInfo WHERE FileExists = 0 AND FileIsADirectory = 1 AND ParentDirectoryExists = 1) BEGIN SET @ErrorMessage = 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -932,371 +931,371 @@ BEGIN IF @BackupType NOT IN ('FULL','DIFF','LOG') OR @BackupType IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @BackupType is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF SERVERPROPERTY('EngineEdition') = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN SET @ErrorMessage = 'SQL Database Managed Instance only supports COPY_ONLY full backups.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @Verify is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CleanupTime < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CleanupTime IS NOT NULL AND @HostPlatform = 'Linux' BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupMode is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @Compress is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CopyOnly NOT IN ('Y','N') OR @CopyOnly IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @CopyOnly is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @ChangeBackupType is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN SET @ErrorMessage = 'The value for the parameter @BackupSoftware is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @BackupSoftware = 'LITESPEED' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_backup_database') BEGIN SET @ErrorMessage = 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN SET @ErrorMessage = 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @BackupSoftware = 'SQLSAFE' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_ss_backup') BEGIN SET @ErrorMessage = 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'PC' AND [name] = 'emc_run_backup') BEGIN SET @ErrorMessage = 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CheckSum NOT IN ('Y','N') OR @CheckSum IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @CheckSum is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @BlockSize is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @BufferCount <= 0 OR @BufferCount > 2147483647 OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE') BEGIN SET @ErrorMessage = 'The value for the parameter @BufferCount is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @MaxTransferSize is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @NumberOfFiles is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @CompressionLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF LEN(@Description) > 255 OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) BEGIN SET @ErrorMessage = 'The value for the parameter @Description is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) OR (@BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32)) OR (@BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32)) OR (@BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64)) BEGIN SET @ErrorMessage = 'The value for the parameter @Threads is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) OR @Throttle < 1 OR @Throttle > 100 BEGIN SET @ErrorMessage = 'The value for the parameter @Throttle is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @Encrypt is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @EncryptionAlgorithm is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL) OR (@ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate)) BEGIN SET @ErrorMessage = 'The value for the parameter @ServerCertificate is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL) OR (@ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey)) BEGIN SET @ErrorMessage = 'The value for the parameter @ServerAsymmetricKey is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @EncryptionKey is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL OR (@ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @ReadWriteFileGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @OverrideBackupPreference NOT IN('Y','N') OR @OverrideBackupPreference IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @OverrideBackupPreference is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL OR (@NoRecovery = 'Y' AND @BackupType <> 'LOG') OR (@NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE') BEGIN SET @ErrorMessage = 'The value for the parameter @NoRecovery is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@URL IS NOT NULL AND @Directory IS NOT NULL) OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@URL IS NOT NULL AND @Version < 11.03339) OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@URL NOT LIKE 'https://%/%') BEGIN SET @ErrorMessage = 'The value for the parameter @URL is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) BEGIN SET @ErrorMessage = 'The value for the parameter @Credential is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MirrorCleanupTime < 0 OR (@MirrorCleanupTime IS NOT NULL AND @MirrorDirectory IS NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorCleanupTime is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MirrorCleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @MirrorCleanupMode IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorCleanupMode is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL NOT LIKE 'https://%/%') OR (@MirrorURL IS NOT NULL AND @URL IS NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @AdaptiveCompression NOT IN('SIZE','SPEED') OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) BEGIN SET @ErrorMessage = 'The value for the parameter @AdaptiveCompression is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@ModificationLevel IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN SET @ErrorMessage = 'The value for the parameter @ModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @TimeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @DataDomainBoostHost is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @DataDomainBoostUser is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @DataDomainBoostDevicePath is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @DataDomainBoostLockboxPath is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DirectoryStructure = '' BEGIN SET @ErrorMessage = 'The value for the parameter @DirectoryStructure is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @AvailabilityGroupDirectoryStructure = '' BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @FileName IS NULL OR @FileName = '' OR @FileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') OR @FileName LIKE '%{DirectorySeperator}%' OR @FileName LIKE '%/%' OR @FileName LIKE '%\%' BEGIN SET @ErrorMessage = 'The value for the parameter @FileName is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) OR @AvailabilityGroupFileName = '' OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' OR @AvailabilityGroupFileName LIKE '%/%' OR @AvailabilityGroupFileName LIKE '%\%' BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupFileName is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1304,7 +1303,7 @@ BEGIN OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1312,7 +1311,7 @@ BEGIN OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1320,7 +1319,7 @@ BEGIN OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1328,70 +1327,70 @@ BEGIN OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @FileExtensionFull LIKE '%.%' BEGIN SET @ErrorMessage = 'The value for the parameter @FileExtensionFull is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @FileExtensionDiff LIKE '%.%' BEGIN SET @ErrorMessage = 'The value for the parameter @FileExtensionDiff is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @FileExtensionLog LIKE '%.%' BEGIN SET @ErrorMessage = 'The value for the parameter @FileExtensionLog is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Init NOT IN('Y','N') OR @Init IS NULL OR (@Init = 'Y' AND @BackupType = 'LOG') OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @Init is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Error <> 0 BEGIN SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @ReturnCode = @Error GOTO Logging END @@ -1408,7 +1407,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1420,7 +1419,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1431,7 +1430,7 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1630,7 +1629,7 @@ BEGIN ROLLBACK TRANSACTION END SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -1808,90 +1807,90 @@ BEGIN END SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentIsDatabaseAccessible IS NOT NULL BEGIN SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Encrypted: ' + CASE WHEN @CurrentIsEncrypted = 1 THEN 'Yes' WHEN @CurrentIsEncrypted = 0 THEN 'No' ELSE 'N/A' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentAvailabilityGroup IS NOT NULL BEGIN SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Availability group backup preference: ' + @CurrentAvailabilityGroupBackupPreference - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Is preferred backup replica: ' + CASE WHEN @CurrentIsPreferredBackupReplica = 1 THEN 'Yes' WHEN @CurrentIsPreferredBackupReplica = 0 THEN 'No' ELSE 'N/A' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END IF @CurrentDatabaseMirroringRole IS NOT NULL BEGIN SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END IF @CurrentLogShippingRole IS NOT NULL BEGIN SET @DatabaseMessage = 'Log shipping role: ' + @CurrentLogShippingRole - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END SET @DatabaseMessage = 'Differential base LSN: ' + ISNULL(CAST(@CurrentDifferentialBaseLSN AS nvarchar),'N/A') - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentBackupType = 'DIFF' BEGIN SET @DatabaseMessage = 'Differential base is snapshot: ' + CASE WHEN @CurrentDifferentialBaseIsSnapshot = 1 THEN 'Yes' WHEN @CurrentDifferentialBaseIsSnapshot = 0 THEN 'No' ELSE 'N/A' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentBackupType IN('DIFF','FULL') AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) BEGIN SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar),'N/A') - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Modified extent page count: ' + ISNULL(CAST(@CurrentModifiedExtentPageCount AS nvarchar),'N/A') - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END IF @CurrentBackupType = 'LOG' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) BEGIN SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),@CurrentLastLogBackup,120),'N/A') - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Log size since last log backup (MB): ' + ISNULL(CAST(@CurrentLogSizeSinceLastLogBackup AS nvarchar),'N/A') - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END RAISERROR('',10,1) WITH NOWAIT @@ -3001,7 +3000,7 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -3075,8 +3074,7 @@ BEGIN Logging: SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) - SET @EndMessage = REPLACE(@EndMessage,'%','%%') - RAISERROR(@EndMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT IF @ReturnCode <> 0 BEGIN diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index b0424c3c..f816ef95 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 19:23:12 //-- + --// Version: 2018-12-30 11:14:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -223,32 +223,31 @@ BEGIN SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Platform: ' + @HostPlatform - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Parameters: ' + @Parameters - SET @StartMessage = REPLACE(@StartMessage,'%','%%') - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + @VersionTimestamp - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- @@ -257,63 +256,63 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END 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') BEGIN SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel = '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] = 'Queue') BEGIN SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @@TRANCOUNT <> 0 BEGIN SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -446,7 +445,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -542,21 +541,21 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -694,126 +693,126 @@ BEGIN IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) OR EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) OR NOT EXISTS (SELECT * FROM @SelectedCheckCommands) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG'))) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE'))) BEGIN SET @ErrorMessage = 'The value for the parameter @CheckCommands is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @PhysicalOnly is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @NoIndex is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL OR (@ExtendedLogicalChecks = 'Y' AND NOT @Version >= 10) OR (@PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y') BEGIN SET @ErrorMessage = 'The value for the parameter @ExtendedLogicalChecks is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @TabLock is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) OR (@FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups)) OR (@FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP')) BEGIN SET @ErrorMessage = 'The value for the parameter @FileGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) OR (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) OR (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN SET @ErrorMessage = 'The value for the parameter @Objects is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) BEGIN SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupReplicas is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @TimeLimit < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LockTimeout < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LockMessageSeverity NOT IN(10,16) BEGIN SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Error <> 0 BEGIN SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @ReturnCode = @Error GOTO Logging END @@ -830,7 +829,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -842,7 +841,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -854,7 +853,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -866,7 +865,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -879,7 +878,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -892,7 +891,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -903,7 +902,7 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1127,7 +1126,7 @@ BEGIN ROLLBACK TRANSACTION END SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -1232,54 +1231,54 @@ BEGIN WHERE name = @CurrentDatabaseName SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentIsDatabaseAccessible IS NOT NULL BEGIN SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentAvailabilityGroup IS NOT NULL BEGIN SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' BEGIN SET @DatabaseMessage = 'Availability group backup preference: ' + @CurrentAvailabilityGroupBackupPreference - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Is preferred backup replica: ' + CASE WHEN @CurrentIsPreferredBackupReplica = 1 THEN 'Yes' WHEN @CurrentIsPreferredBackupReplica = 0 THEN 'No' ELSE 'N/A' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END END IF @CurrentDatabaseMirroringRole IS NOT NULL BEGIN SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END RAISERROR('',10,1) WITH NOWAIT @@ -1375,7 +1374,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following file groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1407,7 +1406,7 @@ BEGIN BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + ' The file group ' + QUOTENAME(@CurrentFileGroupName) + ' in the database ' + QUOTENAME(@CurrentDatabaseName) + ' is locked. It could not be checked if the filegroup exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END - RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -1533,7 +1532,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following objects do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1568,7 +1567,7 @@ BEGIN BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + 'The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the object exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END - RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -1641,7 +1640,7 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1699,8 +1698,7 @@ BEGIN Logging: SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) - SET @EndMessage = REPLACE(@EndMessage,'%','%%') - RAISERROR(@EndMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT IF @ReturnCode <> 0 BEGIN diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 51853fc8..a7f447a0 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 19:23:12 //-- + --// Version: 2018-12-30 11:14:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -306,32 +306,31 @@ BEGIN SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Platform: ' + @HostPlatform - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Parameters: ' + @Parameters - SET @StartMessage = REPLACE(@StartMessage,'%','%%') - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + @VersionTimestamp - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- @@ -340,63 +339,63 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END 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') BEGIN SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel = '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] = 'Queue') BEGIN SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @@TRANCOUNT <> 0 BEGIN SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -528,7 +527,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -624,21 +623,21 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -768,7 +767,7 @@ BEGIN OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN SET @ErrorMessage = 'The value for the parameter @FragmentationLow is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -776,7 +775,7 @@ BEGIN OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN SET @ErrorMessage = 'The value for the parameter @FragmentationMedium is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -784,224 +783,224 @@ BEGIN OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN SET @ErrorMessage = 'The value for the parameter @FragmentationHigh is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 >= @FragmentationLevel2 OR @FragmentationLevel1 IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @FragmentationLevel1 is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 <= @FragmentationLevel1 OR @FragmentationLevel2 IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @FragmentationLevel2 is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @MinNumberOfPages is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MaxNumberOfPages < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @MaxNumberOfPages is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @SortInTempdb is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN SET @ErrorMessage = 'The value for the parameter @FillFactor is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @PadIndex NOT IN('Y','N') BEGIN SET @ErrorMessage = 'The value for the parameter @PadIndex is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LOBCompaction is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN SET @ErrorMessage = 'The value for the parameter @UpdateStatistics is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @OnlyModifiedStatistics is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN SET @ErrorMessage = 'The value for the parameter @StatisticsModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN SET @ErrorMessage = 'The value for the parameter @StatisticsSample is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL OR (@StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @StatisticsResample is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @PartitionLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @MSShippedObjects is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) OR (@Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes)) BEGIN SET @ErrorMessage = 'The value for the parameter @Indexes is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @TimeLimit < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Delay < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @Delay is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @WaitAtLowPriorityMaxDuration < 0 OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @WaitAtLowPriorityAbortAfterWait IS NULL) OR (@WaitAtLowPriorityMaxDuration IS NULL AND @WaitAtLowPriorityAbortAfterWait IS NOT NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL OR (@Resumable = 'Y' AND NOT (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8))) BEGIN SET @ErrorMessage = 'The value for the parameter @Resumable is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Resumable and @SortInTempdb.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LockTimeout < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LockMessageSeverity NOT IN(10,16) BEGIN SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Error <> 0 BEGIN SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @ReturnCode = @Error GOTO Logging END @@ -1018,7 +1017,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1030,7 +1029,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1042,7 +1041,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1055,7 +1054,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1221,7 +1220,7 @@ BEGIN ROLLBACK TRANSACTION END SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -1320,45 +1319,45 @@ BEGIN WHERE name = @CurrentDatabaseName SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentIsDatabaseAccessible IS NOT NULL BEGIN SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentAvailabilityGroup IS NOT NULL BEGIN SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END IF @CurrentDatabaseMirroringRole IS NOT NULL BEGIN SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END RAISERROR('',10,1) WITH NOWAIT @@ -1551,7 +1550,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1566,7 +1565,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1634,7 +1633,7 @@ BEGIN BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END - RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -1667,7 +1666,7 @@ BEGIN BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the statistics exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END - RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -1709,7 +1708,7 @@ BEGIN BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The rows and modification_counter could not be checked.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END - RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -1738,7 +1737,7 @@ BEGIN BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The page_count and avg_fragmentation_in_percent could not be checked.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END - RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -2153,7 +2152,7 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -2196,8 +2195,7 @@ BEGIN Logging: SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) - SET @EndMessage = REPLACE(@EndMessage,'%','%%') - RAISERROR(@EndMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT IF @ReturnCode <> 0 BEGIN diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index b1fd9239..52b6abe5 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-12-29 19:23:12 +Version: 2018-12-30 11:14:12 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 19:23:12 //-- + --// Version: 2018-12-30 11:14:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -158,28 +158,28 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END 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') BEGIN SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -196,42 +196,42 @@ BEGIN IF @Command IS NULL OR @Command = '' BEGIN SET @ErrorMessage = 'The value for the parameter @Command is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CommandType IS NULL OR @CommandType = '' OR LEN(@CommandType) > 60 BEGIN SET @ErrorMessage = 'The value for the parameter @CommandType is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Mode NOT IN(1,2) OR @Mode IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Mode is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -249,17 +249,15 @@ BEGIN SET @StartTimeSec = CONVERT(datetime,CONVERT(nvarchar,@StartTime,120),120) SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTimeSec,120) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Command: ' + @Command - SET @StartMessage = REPLACE(@StartMessage,'%','%%') - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT IF @Comment IS NOT NULL BEGIN SET @StartMessage = 'Comment: ' + @Comment - SET @StartMessage = REPLACE(@StartMessage,'%','%%') - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END IF @LogToTable = 'Y' @@ -292,7 +290,7 @@ BEGIN SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END - RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -309,13 +307,13 @@ BEGIN SET @EndTimeSec = CONVERT(datetime,CONVERT(varchar,@EndTime,120),120) SET @EndMessage = 'Outcome: ' + CASE WHEN @Execute = 'N' THEN 'Not Executed' WHEN @Error = 0 THEN 'Succeeded' ELSE 'Failed' END - RAISERROR(@EndMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT SET @EndMessage = 'Duration: ' + CASE WHEN DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) > 0 THEN CAST(DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) AS nvarchar) + '.' ELSE '' END + CONVERT(nvarchar,@EndTimeSec - @StartTimeSec,108) - RAISERROR(@EndMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTimeSec,120) + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@EndMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT IF @LogToTable = 'Y' BEGIN @@ -411,7 +409,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 19:23:12 //-- + --// Version: 2018-12-30 11:14:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -658,32 +656,31 @@ BEGIN SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Platform: ' + @HostPlatform - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Parameters: ' + @Parameters - SET @StartMessage = REPLACE(@StartMessage,'%','%%') - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + @VersionTimestamp - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- @@ -692,70 +689,70 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END 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') BEGIN SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel = '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] = 'Queue') BEGIN SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @@TRANCOUNT <> 0 BEGIN SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @AmazonRDS = 1 BEGIN SET @ErrorMessage = 'The stored procedure DatabaseBackup is not supported on Amazon RDS.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -888,7 +885,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -984,21 +981,21 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1015,7 +1012,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1030,7 +1027,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1127,7 +1124,7 @@ BEGIN IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR SET @DirectoryCheck = 0 END @@ -1135,7 +1132,7 @@ BEGIN IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR SET @DirectoryCheck = 0 END @@ -1161,7 +1158,7 @@ BEGIN IF NOT EXISTS (SELECT * FROM @DirectoryInfo WHERE FileExists = 0 AND FileIsADirectory = 1 AND ParentDirectoryExists = 1) BEGIN SET @ErrorMessage = 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1270,371 +1267,371 @@ BEGIN IF @BackupType NOT IN ('FULL','DIFF','LOG') OR @BackupType IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @BackupType is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF SERVERPROPERTY('EngineEdition') = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN SET @ErrorMessage = 'SQL Database Managed Instance only supports COPY_ONLY full backups.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @Verify is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CleanupTime < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CleanupTime IS NOT NULL AND @HostPlatform = 'Linux' BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupMode is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @Compress is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CopyOnly NOT IN ('Y','N') OR @CopyOnly IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @CopyOnly is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @ChangeBackupType is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN SET @ErrorMessage = 'The value for the parameter @BackupSoftware is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @BackupSoftware = 'LITESPEED' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_backup_database') BEGIN SET @ErrorMessage = 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN SET @ErrorMessage = 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @BackupSoftware = 'SQLSAFE' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_ss_backup') BEGIN SET @ErrorMessage = 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'PC' AND [name] = 'emc_run_backup') BEGIN SET @ErrorMessage = 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @CheckSum NOT IN ('Y','N') OR @CheckSum IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @CheckSum is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @BlockSize is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @BufferCount <= 0 OR @BufferCount > 2147483647 OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE') BEGIN SET @ErrorMessage = 'The value for the parameter @BufferCount is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @MaxTransferSize is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @NumberOfFiles is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @CompressionLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF LEN(@Description) > 255 OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) BEGIN SET @ErrorMessage = 'The value for the parameter @Description is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) OR (@BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32)) OR (@BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32)) OR (@BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64)) BEGIN SET @ErrorMessage = 'The value for the parameter @Threads is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) OR @Throttle < 1 OR @Throttle > 100 BEGIN SET @ErrorMessage = 'The value for the parameter @Throttle is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @Encrypt is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @EncryptionAlgorithm is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL) OR (@ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate)) BEGIN SET @ErrorMessage = 'The value for the parameter @ServerCertificate is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL) OR (@ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey)) BEGIN SET @ErrorMessage = 'The value for the parameter @ServerAsymmetricKey is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @EncryptionKey is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL OR (@ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @ReadWriteFileGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @OverrideBackupPreference NOT IN('Y','N') OR @OverrideBackupPreference IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @OverrideBackupPreference is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL OR (@NoRecovery = 'Y' AND @BackupType <> 'LOG') OR (@NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE') BEGIN SET @ErrorMessage = 'The value for the parameter @NoRecovery is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@URL IS NOT NULL AND @Directory IS NOT NULL) OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@URL IS NOT NULL AND @Version < 11.03339) OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@URL NOT LIKE 'https://%/%') BEGIN SET @ErrorMessage = 'The value for the parameter @URL is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) BEGIN SET @ErrorMessage = 'The value for the parameter @Credential is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MirrorCleanupTime < 0 OR (@MirrorCleanupTime IS NOT NULL AND @MirrorDirectory IS NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorCleanupTime is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MirrorCleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @MirrorCleanupMode IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorCleanupMode is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL NOT LIKE 'https://%/%') OR (@MirrorURL IS NOT NULL AND @URL IS NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @AdaptiveCompression NOT IN('SIZE','SPEED') OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) BEGIN SET @ErrorMessage = 'The value for the parameter @AdaptiveCompression is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@ModificationLevel IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN SET @ErrorMessage = 'The value for the parameter @ModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @TimeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @DataDomainBoostHost is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @DataDomainBoostUser is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @DataDomainBoostDevicePath is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @DataDomainBoostLockboxPath is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DirectoryStructure = '' BEGIN SET @ErrorMessage = 'The value for the parameter @DirectoryStructure is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @AvailabilityGroupDirectoryStructure = '' BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @FileName IS NULL OR @FileName = '' OR @FileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') OR @FileName LIKE '%{DirectorySeperator}%' OR @FileName LIKE '%/%' OR @FileName LIKE '%\%' BEGIN SET @ErrorMessage = 'The value for the parameter @FileName is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) OR @AvailabilityGroupFileName = '' OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' OR @AvailabilityGroupFileName LIKE '%/%' OR @AvailabilityGroupFileName LIKE '%\%' BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupFileName is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1642,7 +1639,7 @@ BEGIN OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1650,7 +1647,7 @@ BEGIN OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1658,7 +1655,7 @@ BEGIN OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1666,70 +1663,70 @@ BEGIN OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @FileExtensionFull LIKE '%.%' BEGIN SET @ErrorMessage = 'The value for the parameter @FileExtensionFull is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @FileExtensionDiff LIKE '%.%' BEGIN SET @ErrorMessage = 'The value for the parameter @FileExtensionDiff is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @FileExtensionLog LIKE '%.%' BEGIN SET @ErrorMessage = 'The value for the parameter @FileExtensionLog is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Init NOT IN('Y','N') OR @Init IS NULL OR (@Init = 'Y' AND @BackupType = 'LOG') OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN SET @ErrorMessage = 'The value for the parameter @Init is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Error <> 0 BEGIN SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @ReturnCode = @Error GOTO Logging END @@ -1746,7 +1743,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1758,7 +1755,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1769,7 +1766,7 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1968,7 +1965,7 @@ BEGIN ROLLBACK TRANSACTION END SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -2146,90 +2143,90 @@ BEGIN END SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentIsDatabaseAccessible IS NOT NULL BEGIN SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Encrypted: ' + CASE WHEN @CurrentIsEncrypted = 1 THEN 'Yes' WHEN @CurrentIsEncrypted = 0 THEN 'No' ELSE 'N/A' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentAvailabilityGroup IS NOT NULL BEGIN SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Availability group backup preference: ' + @CurrentAvailabilityGroupBackupPreference - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Is preferred backup replica: ' + CASE WHEN @CurrentIsPreferredBackupReplica = 1 THEN 'Yes' WHEN @CurrentIsPreferredBackupReplica = 0 THEN 'No' ELSE 'N/A' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END IF @CurrentDatabaseMirroringRole IS NOT NULL BEGIN SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END IF @CurrentLogShippingRole IS NOT NULL BEGIN SET @DatabaseMessage = 'Log shipping role: ' + @CurrentLogShippingRole - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END SET @DatabaseMessage = 'Differential base LSN: ' + ISNULL(CAST(@CurrentDifferentialBaseLSN AS nvarchar),'N/A') - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentBackupType = 'DIFF' BEGIN SET @DatabaseMessage = 'Differential base is snapshot: ' + CASE WHEN @CurrentDifferentialBaseIsSnapshot = 1 THEN 'Yes' WHEN @CurrentDifferentialBaseIsSnapshot = 0 THEN 'No' ELSE 'N/A' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentBackupType IN('DIFF','FULL') AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) BEGIN SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar),'N/A') - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Modified extent page count: ' + ISNULL(CAST(@CurrentModifiedExtentPageCount AS nvarchar),'N/A') - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END IF @CurrentBackupType = 'LOG' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) BEGIN SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),@CurrentLastLogBackup,120),'N/A') - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Log size since last log backup (MB): ' + ISNULL(CAST(@CurrentLogSizeSinceLastLogBackup AS nvarchar),'N/A') - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END RAISERROR('',10,1) WITH NOWAIT @@ -3339,7 +3336,7 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -3413,8 +3410,7 @@ BEGIN Logging: SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) - SET @EndMessage = REPLACE(@EndMessage,'%','%%') - RAISERROR(@EndMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT IF @ReturnCode <> 0 BEGIN @@ -3464,7 +3460,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 19:23:12 //-- + --// Version: 2018-12-30 11:14:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3650,32 +3646,31 @@ BEGIN SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Platform: ' + @HostPlatform - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Parameters: ' + @Parameters - SET @StartMessage = REPLACE(@StartMessage,'%','%%') - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + @VersionTimestamp - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- @@ -3684,63 +3679,63 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END 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') BEGIN SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel = '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] = 'Queue') BEGIN SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @@TRANCOUNT <> 0 BEGIN SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -3873,7 +3868,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -3969,21 +3964,21 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4121,126 +4116,126 @@ BEGIN IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) OR EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) OR NOT EXISTS (SELECT * FROM @SelectedCheckCommands) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG'))) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE'))) BEGIN SET @ErrorMessage = 'The value for the parameter @CheckCommands is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @PhysicalOnly is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @NoIndex is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL OR (@ExtendedLogicalChecks = 'Y' AND NOT @Version >= 10) OR (@PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y') BEGIN SET @ErrorMessage = 'The value for the parameter @ExtendedLogicalChecks is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @TabLock is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) OR (@FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups)) OR (@FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP')) BEGIN SET @ErrorMessage = 'The value for the parameter @FileGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) OR (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) OR (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN SET @ErrorMessage = 'The value for the parameter @Objects is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) BEGIN SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupReplicas is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @TimeLimit < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LockTimeout < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LockMessageSeverity NOT IN(10,16) BEGIN SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Error <> 0 BEGIN SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @ReturnCode = @Error GOTO Logging END @@ -4257,7 +4252,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4269,7 +4264,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4281,7 +4276,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4293,7 +4288,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4306,7 +4301,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4319,7 +4314,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4330,7 +4325,7 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4554,7 +4549,7 @@ BEGIN ROLLBACK TRANSACTION END SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -4659,54 +4654,54 @@ BEGIN WHERE name = @CurrentDatabaseName SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentIsDatabaseAccessible IS NOT NULL BEGIN SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentAvailabilityGroup IS NOT NULL BEGIN SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' BEGIN SET @DatabaseMessage = 'Availability group backup preference: ' + @CurrentAvailabilityGroupBackupPreference - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Is preferred backup replica: ' + CASE WHEN @CurrentIsPreferredBackupReplica = 1 THEN 'Yes' WHEN @CurrentIsPreferredBackupReplica = 0 THEN 'No' ELSE 'N/A' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END END IF @CurrentDatabaseMirroringRole IS NOT NULL BEGIN SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END RAISERROR('',10,1) WITH NOWAIT @@ -4802,7 +4797,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following file groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4834,7 +4829,7 @@ BEGIN BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + ' The file group ' + QUOTENAME(@CurrentFileGroupName) + ' in the database ' + QUOTENAME(@CurrentDatabaseName) + ' is locked. It could not be checked if the filegroup exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END - RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -4960,7 +4955,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following objects do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4995,7 +4990,7 @@ BEGIN BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + 'The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the object exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END - RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -5068,7 +5063,7 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -5126,8 +5121,7 @@ BEGIN Logging: SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) - SET @EndMessage = REPLACE(@EndMessage,'%','%%') - RAISERROR(@EndMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT IF @ReturnCode <> 0 BEGIN @@ -5192,7 +5186,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-29 19:23:12 //-- + --// Version: 2018-12-30 11:14:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5447,32 +5441,31 @@ BEGIN SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Platform: ' + @HostPlatform - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME(DB_ID())) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Parameters: ' + @Parameters - SET @StartMessage = REPLACE(@StartMessage,'%','%%') - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + @VersionTimestamp - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@StartMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- @@ -5481,63 +5474,63 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END 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') BEGIN SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel = '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] = 'Queue') BEGIN SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @@TRANCOUNT <> 0 BEGIN SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -5669,7 +5662,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -5765,21 +5758,21 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -5909,7 +5902,7 @@ BEGIN OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN SET @ErrorMessage = 'The value for the parameter @FragmentationLow is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -5917,7 +5910,7 @@ BEGIN OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN SET @ErrorMessage = 'The value for the parameter @FragmentationMedium is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -5925,224 +5918,224 @@ BEGIN OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN SET @ErrorMessage = 'The value for the parameter @FragmentationHigh is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 >= @FragmentationLevel2 OR @FragmentationLevel1 IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @FragmentationLevel1 is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 <= @FragmentationLevel1 OR @FragmentationLevel2 IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @FragmentationLevel2 is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @MinNumberOfPages is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MaxNumberOfPages < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @MaxNumberOfPages is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @SortInTempdb is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN SET @ErrorMessage = 'The value for the parameter @FillFactor is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @PadIndex NOT IN('Y','N') BEGIN SET @ErrorMessage = 'The value for the parameter @PadIndex is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LOBCompaction is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN SET @ErrorMessage = 'The value for the parameter @UpdateStatistics is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @OnlyModifiedStatistics is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN SET @ErrorMessage = 'The value for the parameter @StatisticsModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN SET @ErrorMessage = 'The value for the parameter @StatisticsSample is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL OR (@StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @StatisticsResample is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @PartitionLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @MSShippedObjects is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) OR (@Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes)) BEGIN SET @ErrorMessage = 'The value for the parameter @Indexes is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @TimeLimit < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Delay < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @Delay is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @WaitAtLowPriorityMaxDuration < 0 OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @WaitAtLowPriorityAbortAfterWait IS NULL) OR (@WaitAtLowPriorityMaxDuration IS NULL AND @WaitAtLowPriorityAbortAfterWait IS NOT NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL OR (@Resumable = 'Y' AND NOT (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8))) BEGIN SET @ErrorMessage = 'The value for the parameter @Resumable is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN SET @ErrorMessage = 'You can only specify one of the parameters @Resumable and @SortInTempdb.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LockTimeout < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LockMessageSeverity NOT IN(10,16) BEGIN SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END IF @Error <> 0 BEGIN SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @ReturnCode = @Error GOTO Logging END @@ -6159,7 +6152,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -6171,7 +6164,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -6183,7 +6176,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -6196,7 +6189,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -6362,7 +6355,7 @@ BEGIN ROLLBACK TRANSACTION END SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -6461,45 +6454,45 @@ BEGIN WHERE name = @CurrentDatabaseName SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentIsDatabaseAccessible IS NOT NULL BEGIN SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentAvailabilityGroup IS NOT NULL BEGIN SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END IF @CurrentDatabaseMirroringRole IS NOT NULL BEGIN SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole - RAISERROR(@DatabaseMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END RAISERROR('',10,1) WITH NOWAIT @@ -6692,7 +6685,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -6707,7 +6700,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -6775,7 +6768,7 @@ BEGIN BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END - RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -6808,7 +6801,7 @@ BEGIN BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the statistics exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END - RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -6850,7 +6843,7 @@ BEGIN BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The rows and modification_counter could not be checked.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END - RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -6879,7 +6872,7 @@ BEGIN BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The page_count and avg_fragmentation_in_percent could not be checked.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END - RAISERROR(@ErrorMessage,@Severity,1) WITH NOWAIT + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -7294,7 +7287,7 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -7337,8 +7330,7 @@ BEGIN Logging: SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) - SET @EndMessage = REPLACE(@EndMessage,'%','%%') - RAISERROR(@EndMessage,10,1) WITH NOWAIT + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT IF @ReturnCode <> 0 BEGIN From 21dede5872975a913147d4c3ed241c727f7bb72d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 18:35:06 +0100 Subject: [PATCH 066/188] Update issue templates --- .github/ISSUE_TEMPLATE/bug_report.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..6824f3a2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,11 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. From 3768f7256ef9eb9e42ab9e4bd69c304c23da6dcc Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 18:38:23 +0100 Subject: [PATCH 067/188] Update issue templates --- .github/ISSUE_TEMPLATE/bug_report.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 6824f3a2..6f858e80 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -9,3 +9,5 @@ assignees: '' **Describe the bug** A clear and concise description of what the bug is. + +**SQL Server version and edition (SELECT @@VERSION)** From fa7b0f0219e7cb65a8454527c9d4331f8610096c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 18:47:59 +0100 Subject: [PATCH 068/188] Update issue templates --- .github/ISSUE_TEMPLATE/bug_report.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 6f858e80..ad1f9973 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -7,7 +7,12 @@ assignees: '' --- -**Describe the bug** -A clear and concise description of what the bug is. +Description of the issue: -**SQL Server version and edition (SELECT @@VERSION)** +SQL Server version and edition (SELECT @@VERSION): + +Version of the SQL Server Maintenance Solution: + +What command are you executing: + +What output are you getting? From 67db1c357a020b8c17fc5acbbe866e85c5c39e22 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 18:49:16 +0100 Subject: [PATCH 069/188] Update issue templates --- .github/ISSUE_TEMPLATE/bug_report.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index ad1f9973..a602a61d 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -9,7 +9,8 @@ assignees: '' Description of the issue: -SQL Server version and edition (SELECT @@VERSION): +SQL Server version and edition: +SELECT @@VERSION Version of the SQL Server Maintenance Solution: From dc287f12a6a803b743deb0ec216a14c375c98889 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 18:55:05 +0100 Subject: [PATCH 070/188] Update issue templates --- .github/ISSUE_TEMPLATE/bug_report.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index a602a61d..f3635100 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -2,7 +2,7 @@ name: Bug report about: Create a report to help us improve title: '' -labels: '' +labels: bug_report assignees: '' --- @@ -13,6 +13,7 @@ SQL Server version and edition: SELECT @@VERSION Version of the SQL Server Maintenance Solution: +https://ola.hallengren.com/frequently-asked-questions.html#VersionCheck What command are you executing: From 663e68bddac5cfe2962b75216906b36d8e67428b Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 18:58:30 +0100 Subject: [PATCH 071/188] Update issue templates --- .github/ISSUE_TEMPLATE/bug_report.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index f3635100..b3c88136 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -10,7 +10,7 @@ assignees: '' Description of the issue: SQL Server version and edition: -SELECT @@VERSION +```SELECT @@VERSION``` Version of the SQL Server Maintenance Solution: https://ola.hallengren.com/frequently-asked-questions.html#VersionCheck From ba21248728f5cebe0d925a2679ab456eff7bcc00 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 19:00:53 +0100 Subject: [PATCH 072/188] Update issue templates --- .github/ISSUE_TEMPLATE/bug_report.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index b3c88136..beb76e43 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -7,14 +7,14 @@ assignees: '' --- -Description of the issue: +**Description of the issue** -SQL Server version and edition: +**SQL Server version and edition** ```SELECT @@VERSION``` -Version of the SQL Server Maintenance Solution: +**Version of the SQL Server Maintenance Solution** https://ola.hallengren.com/frequently-asked-questions.html#VersionCheck -What command are you executing: +**What command are you executing** -What output are you getting? +**What output are you getting** From 35bfe9c4f29ea218ab37628d6f0d54a8c50a1f17 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 19:04:15 +0100 Subject: [PATCH 073/188] Update issue templates --- .github/ISSUE_TEMPLATE/bug_report.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index beb76e43..163ca067 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -12,9 +12,9 @@ assignees: '' **SQL Server version and edition** ```SELECT @@VERSION``` -**Version of the SQL Server Maintenance Solution** +**Version of the script** https://ola.hallengren.com/frequently-asked-questions.html#VersionCheck -**What command are you executing** +**What command are you executing?** -**What output are you getting** +**What output are you getting?** From ccfc039edf5916fd6feca64d78b110561f455bce Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 19:07:15 +0100 Subject: [PATCH 074/188] Update issue templates --- .github/ISSUE_TEMPLATE/bug_report.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 163ca067..d33eb7e3 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -10,10 +10,10 @@ assignees: '' **Description of the issue** **SQL Server version and edition** -```SELECT @@VERSION``` +Execute ```SELECT @@VERSION``` **Version of the script** -https://ola.hallengren.com/frequently-asked-questions.html#VersionCheck +Check the header of the stored procedures **What command are you executing?** From 4be854184a28f9ef19a9ffd4b2548b03a69c7ee4 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 19:08:19 +0100 Subject: [PATCH 075/188] Update issue templates --- .github/ISSUE_TEMPLATE/bug_report.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index d33eb7e3..35847a4b 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -13,7 +13,7 @@ assignees: '' Execute ```SELECT @@VERSION``` **Version of the script** -Check the header of the stored procedures +Check the header of the stored procedure **What command are you executing?** From 2f7c373e2b460ffdb560a7c1be554c51b7604843 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 19:12:05 +0100 Subject: [PATCH 076/188] Update issue templates --- .github/ISSUE_TEMPLATE/feature_request.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000..888d60fa --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,10 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: feature_request +assignees: '' + +--- + + From d3cce2f0d7f077cee10e6bf50330b0024763d8e6 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 19:14:28 +0100 Subject: [PATCH 077/188] Update issue templates --- .github/ISSUE_TEMPLATE/feature_request.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 888d60fa..c1975ff5 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -7,4 +7,4 @@ assignees: '' --- - +**Description of the feature that you would like to see** From 161bbbd7b4b9fbd84879618863cde48052a4d6e4 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 19:16:45 +0100 Subject: [PATCH 078/188] Update issue templates --- .github/ISSUE_TEMPLATE/feature_request.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index c1975ff5..e961bcad 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -8,3 +8,4 @@ assignees: '' --- **Description of the feature that you would like to see** +This can be a new feature, or a change to an existing feature From 424bc80f730d32a69ed0c0900efe57f0f9b69dc0 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 19:18:09 +0100 Subject: [PATCH 079/188] Update issue templates --- .github/ISSUE_TEMPLATE/feature_request.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index e961bcad..c140e2f7 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -7,5 +7,5 @@ assignees: '' --- -**Description of the feature that you would like to see** +**Description of the feature** This can be a new feature, or a change to an existing feature From 401ed4083ab29efda0da2756cb2add9da7805a19 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 19:19:06 +0100 Subject: [PATCH 080/188] Update issue templates --- .github/ISSUE_TEMPLATE/feature_request.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index c140e2f7..83e55c31 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -8,4 +8,4 @@ assignees: '' --- **Description of the feature** -This can be a new feature, or a change to an existing feature +It can be a new feature, or a change to an existing feature From df790fc7630b0ca422f08558e3706dc544f7115f Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 31 Dec 2018 19:22:35 +0100 Subject: [PATCH 081/188] Update issue templates From c31f452564f8dca53e3ee5ae371688241115e3dd Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 1 Jan 2019 01:04:36 +0100 Subject: [PATCH 082/188] Update LICENSE --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 081ee5e3..ff0e0f4a 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2018 Ola Hallengren +Copyright (c) 2019 Ola Hallengren Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From ae2a2275fe7ee5a14ad4cf1660f87220ed825ad9 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 1 Jan 2019 01:10:35 +0100 Subject: [PATCH 083/188] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index eaf350cf..732fc496 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ [![stars badge]][stars] [![forks badge]][forks] [![issues badge]][issues] +[![bug_reports badge]][bug reports] ## Getting Started @@ -33,8 +34,10 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [stars badge]:https://img.shields.io/github/stars/olahallengren/sql-server-maintenance-solution.svg [forks badge]:https://img.shields.io/github/forks/olahallengren/sql-server-maintenance-solution.svg [issues badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution.svg +[bug_reports badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/bug_report.svg [licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE [stars]:https://github.com/olahallengren/sql-server-maintenance-solution/stargazers [forks]:https://github.com/olahallengren/sql-server-maintenance-solution/network [issues]:https://github.com/olahallengren/sql-server-maintenance-solution/issues +[bug reports]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Abug_report From 27bdbc0f215a8d1d1a480307d67f5aa4c8091c3c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 1 Jan 2019 01:21:00 +0100 Subject: [PATCH 084/188] Update README.md --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 732fc496..b3f2dbbe 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,8 @@ [![stars badge]][stars] [![forks badge]][forks] [![issues badge]][issues] -[![bug_reports badge]][bug reports] +[![bug_report badge]][bug_report] +[![feature_request badge]][feature_request] ## Getting Started @@ -34,10 +35,12 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [stars badge]:https://img.shields.io/github/stars/olahallengren/sql-server-maintenance-solution.svg [forks badge]:https://img.shields.io/github/forks/olahallengren/sql-server-maintenance-solution.svg [issues badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution.svg -[bug_reports badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/bug_report.svg +[bug_report badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/bug_report.svg +[feature_request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/feature_request.svg [licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE [stars]:https://github.com/olahallengren/sql-server-maintenance-solution/stargazers [forks]:https://github.com/olahallengren/sql-server-maintenance-solution/network [issues]:https://github.com/olahallengren/sql-server-maintenance-solution/issues -[bug reports]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Abug_report +[bug_report]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Abug_report +[feature_request]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Afeature_request From d5bd5a0f99d87f26f5b9aa23429c47da8ec52ef5 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 1 Jan 2019 15:42:21 +0100 Subject: [PATCH 085/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 110 +++++++++++++++++++++++++++++----- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 118 +++++++++++++++++++++++++++++++------ 5 files changed, 197 insertions(+), 37 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 30fecc5c..4d84b6e9 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-30 11:14:12 //-- + --// Version: 2019-01-01 15:33:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index fb71ca59..a213c21e 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-30 11:14:12 //-- + --// Version: 2019-01-01 15:33:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -167,7 +167,7 @@ BEGIN Mirror bit, Completed bit) - DECLARE @URLs TABLE (ID int IDENTITY PRIMARY KEY, + DECLARE @URLs TABLE (ID int PRIMARY KEY, DirectoryPath nvarchar(max), Mirror bit) @@ -224,7 +224,8 @@ BEGIN DECLARE @CurrentURLs TABLE (ID int PRIMARY KEY, DirectoryPath nvarchar(max), - Mirror bit) + Mirror bit, + DirectoryNumber int) DECLARE @CurrentFiles TABLE ([Type] nvarchar(max), FilePath nvarchar(max), @@ -841,13 +842,83 @@ BEGIN --// Select URLs //-- ---------------------------------------------------------------------------------------------------- - INSERT INTO @URLs (DirectoryPath, Mirror) - SELECT @URL, 0 + SET @URL = REPLACE(@URL, CHAR(10), '') + SET @URL = REPLACE(@URL, CHAR(13), '') + + WHILE CHARINDEX(', ',@URL) > 0 SET @URL = REPLACE(@URL,', ',',') + WHILE CHARINDEX(' ,',@URL) > 0 SET @URL = REPLACE(@URL,' ,',',') + + SET @URL = LTRIM(RTRIM(@URL)); + + WITH URLs (StartPosition, EndPosition, [URL]) AS + ( + SELECT 1 AS StartPosition, + ISNULL(NULLIF(CHARINDEX(',', @URL, 1), 0), LEN(@URL) + 1) AS EndPosition, + SUBSTRING(@URL, 1, ISNULL(NULLIF(CHARINDEX(',', @URL, 1), 0), LEN(@URL) + 1) - 1) AS [URL] WHERE @URL IS NOT NULL + UNION ALL + SELECT CAST(EndPosition AS int) + 1 AS StartPosition, + ISNULL(NULLIF(CHARINDEX(',', @URL, EndPosition + 1), 0), LEN(@URL) + 1) AS EndPosition, + SUBSTRING(@URL, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @URL, EndPosition + 1), 0), LEN(@URL) + 1) - EndPosition - 1) AS [URL] + FROM URLs + WHERE EndPosition < LEN(@URL) + 1 + ) + INSERT INTO @URLs (ID, DirectoryPath, Mirror) + SELECT ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS ID, + [URL], + 0 + FROM URLs + OPTION (MAXRECURSION 0) - INSERT INTO @URLs (DirectoryPath, Mirror) - SELECT @MirrorURL, 1 + SET @MirrorURL = REPLACE(@MirrorURL, CHAR(10), '') + SET @MirrorURL = REPLACE(@MirrorURL, CHAR(13), '') + + WHILE CHARINDEX(', ',@MirrorURL) > 0 SET @MirrorURL = REPLACE(@MirrorURL,', ',',') + WHILE CHARINDEX(' ,',@MirrorURL) > 0 SET @MirrorURL = REPLACE(@MirrorURL,' ,',',') + + SET @MirrorURL = LTRIM(RTRIM(@MirrorURL)); + + WITH URLs (StartPosition, EndPosition, [URL]) AS + ( + SELECT 1 AS StartPosition, + ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, 1), 0), LEN(@MirrorURL) + 1) AS EndPosition, + SUBSTRING(@MirrorURL, 1, ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, 1), 0), LEN(@MirrorURL) + 1) - 1) AS [URL] WHERE @MirrorURL IS NOT NULL + UNION ALL + SELECT CAST(EndPosition AS int) + 1 AS StartPosition, + ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, EndPosition + 1), 0), LEN(@MirrorURL) + 1) AS EndPosition, + SUBSTRING(@MirrorURL, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, EndPosition + 1), 0), LEN(@MirrorURL) + 1) - EndPosition - 1) AS [URL] + FROM URLs + WHERE EndPosition < LEN(@MirrorURL) + 1 + ) + INSERT INTO @URLs (ID, DirectoryPath, Mirror) + SELECT (SELECT COUNT(*) FROM @URLs) + ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS ID, + [URL], + 1 + FROM URLs + OPTION (MAXRECURSION 0) + + ---------------------------------------------------------------------------------------------------- + --// Check URLs //-- + ---------------------------------------------------------------------------------------------------- + + IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath NOT LIKE 'https://%/%') + OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) + OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) + BEGIN + SET @ErrorMessage = 'The value for the parameter @URL is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + END + + IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath NOT LIKE 'https://%/%') + OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) + OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) + BEGIN + SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + END ---------------------------------------------------------------------------------------------------- --// Get directory separator //-- @@ -921,7 +992,11 @@ BEGIN IF @NumberOfFiles IS NULL BEGIN - SELECT @NumberOfFiles = CASE WHEN @URL IS NOT NULL THEN 1 WHEN @BackupSoftware = 'DATA_DOMAIN_BOOST' THEN 1 ELSE (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) END + SELECT @NumberOfFiles = CASE + WHEN @BackupSoftware = 'DATA_DOMAIN_BOOST' THEN 1 + WHEN @URL IS NOT NULL THEN (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) + ELSE (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) + END END ---------------------------------------------------------------------------------------------------- @@ -1082,7 +1157,7 @@ BEGIN SET @Error = @@ERROR END - IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN SET @ErrorMessage = 'The value for the parameter @NumberOfFiles is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1173,7 +1248,7 @@ BEGIN SET @Error = @@ERROR END - IF (@URL IS NOT NULL AND @Directory IS NOT NULL) OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@URL IS NOT NULL AND @Version < 11.03339) OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@URL NOT LIKE 'https://%/%') + IF (@URL IS NOT NULL AND @Directory IS NOT NULL) OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@URL IS NOT NULL AND @Version < 11.03339) OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @URL is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1201,7 +1276,7 @@ BEGIN SET @Error = @@ERROR END - IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL NOT LIKE 'https://%/%') OR (@MirrorURL IS NOT NULL AND @URL IS NULL) + IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @URL IS NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -2123,10 +2198,11 @@ BEGIN FROM @Directories ORDER BY ID ASC - INSERT INTO @CurrentURLs (ID, DirectoryPath, Mirror) + INSERT INTO @CurrentURLs (ID, DirectoryPath, Mirror, DirectoryNumber) SELECT ROW_NUMBER() OVER (ORDER BY ID), DirectoryPath + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END, - Mirror + Mirror, + ROW_NUMBER() OVER (PARTITION BY Mirror ORDER BY ID ASC) FROM @URLs ORDER BY ID ASC @@ -2341,7 +2417,9 @@ BEGIN SELECT @CurrentDirectoryPath = DirectoryPath FROM @CurrentURLs - WHERE Mirror = 0 + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + AND Mirror = 0 SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) @@ -2369,7 +2447,9 @@ BEGIN SELECT @CurrentDirectoryPath = DirectoryPath FROM @CurrentURLs - WHERE Mirror = 1 + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + AND Mirror = 1 SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index f816ef95..1af9d7bb 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-30 11:14:12 //-- + --// Version: 2019-01-01 15:33:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index a7f447a0..e66ddc1e 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-30 11:14:12 //-- + --// Version: 2019-01-01 15:33:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 52b6abe5..95e88325 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2018-12-30 11:14:12 +Version: 2019-01-01 15:33:12 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-30 11:14:12 //-- + --// Version: 2019-01-01 15:33:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -409,7 +409,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-30 11:14:12 //-- + --// Version: 2019-01-01 15:33:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -503,7 +503,7 @@ BEGIN Mirror bit, Completed bit) - DECLARE @URLs TABLE (ID int IDENTITY PRIMARY KEY, + DECLARE @URLs TABLE (ID int PRIMARY KEY, DirectoryPath nvarchar(max), Mirror bit) @@ -560,7 +560,8 @@ BEGIN DECLARE @CurrentURLs TABLE (ID int PRIMARY KEY, DirectoryPath nvarchar(max), - Mirror bit) + Mirror bit, + DirectoryNumber int) DECLARE @CurrentFiles TABLE ([Type] nvarchar(max), FilePath nvarchar(max), @@ -1177,13 +1178,83 @@ BEGIN --// Select URLs //-- ---------------------------------------------------------------------------------------------------- - INSERT INTO @URLs (DirectoryPath, Mirror) - SELECT @URL, 0 + SET @URL = REPLACE(@URL, CHAR(10), '') + SET @URL = REPLACE(@URL, CHAR(13), '') + + WHILE CHARINDEX(', ',@URL) > 0 SET @URL = REPLACE(@URL,', ',',') + WHILE CHARINDEX(' ,',@URL) > 0 SET @URL = REPLACE(@URL,' ,',',') + + SET @URL = LTRIM(RTRIM(@URL)); + + WITH URLs (StartPosition, EndPosition, [URL]) AS + ( + SELECT 1 AS StartPosition, + ISNULL(NULLIF(CHARINDEX(',', @URL, 1), 0), LEN(@URL) + 1) AS EndPosition, + SUBSTRING(@URL, 1, ISNULL(NULLIF(CHARINDEX(',', @URL, 1), 0), LEN(@URL) + 1) - 1) AS [URL] WHERE @URL IS NOT NULL + UNION ALL + SELECT CAST(EndPosition AS int) + 1 AS StartPosition, + ISNULL(NULLIF(CHARINDEX(',', @URL, EndPosition + 1), 0), LEN(@URL) + 1) AS EndPosition, + SUBSTRING(@URL, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @URL, EndPosition + 1), 0), LEN(@URL) + 1) - EndPosition - 1) AS [URL] + FROM URLs + WHERE EndPosition < LEN(@URL) + 1 + ) + INSERT INTO @URLs (ID, DirectoryPath, Mirror) + SELECT ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS ID, + [URL], + 0 + FROM URLs + OPTION (MAXRECURSION 0) - INSERT INTO @URLs (DirectoryPath, Mirror) - SELECT @MirrorURL, 1 + SET @MirrorURL = REPLACE(@MirrorURL, CHAR(10), '') + SET @MirrorURL = REPLACE(@MirrorURL, CHAR(13), '') + + WHILE CHARINDEX(', ',@MirrorURL) > 0 SET @MirrorURL = REPLACE(@MirrorURL,', ',',') + WHILE CHARINDEX(' ,',@MirrorURL) > 0 SET @MirrorURL = REPLACE(@MirrorURL,' ,',',') + + SET @MirrorURL = LTRIM(RTRIM(@MirrorURL)); + + WITH URLs (StartPosition, EndPosition, [URL]) AS + ( + SELECT 1 AS StartPosition, + ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, 1), 0), LEN(@MirrorURL) + 1) AS EndPosition, + SUBSTRING(@MirrorURL, 1, ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, 1), 0), LEN(@MirrorURL) + 1) - 1) AS [URL] WHERE @MirrorURL IS NOT NULL + UNION ALL + SELECT CAST(EndPosition AS int) + 1 AS StartPosition, + ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, EndPosition + 1), 0), LEN(@MirrorURL) + 1) AS EndPosition, + SUBSTRING(@MirrorURL, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, EndPosition + 1), 0), LEN(@MirrorURL) + 1) - EndPosition - 1) AS [URL] + FROM URLs + WHERE EndPosition < LEN(@MirrorURL) + 1 + ) + INSERT INTO @URLs (ID, DirectoryPath, Mirror) + SELECT (SELECT COUNT(*) FROM @URLs) + ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS ID, + [URL], + 1 + FROM URLs + OPTION (MAXRECURSION 0) + + ---------------------------------------------------------------------------------------------------- + --// Check URLs //-- + ---------------------------------------------------------------------------------------------------- + + IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath NOT LIKE 'https://%/%') + OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) + OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) + BEGIN + SET @ErrorMessage = 'The value for the parameter @URL is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + END + + IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath NOT LIKE 'https://%/%') + OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) + OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) + BEGIN + SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' + CHAR(13) + CHAR(10) + ' ' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + END ---------------------------------------------------------------------------------------------------- --// Get directory separator //-- @@ -1257,7 +1328,11 @@ BEGIN IF @NumberOfFiles IS NULL BEGIN - SELECT @NumberOfFiles = CASE WHEN @URL IS NOT NULL THEN 1 WHEN @BackupSoftware = 'DATA_DOMAIN_BOOST' THEN 1 ELSE (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) END + SELECT @NumberOfFiles = CASE + WHEN @BackupSoftware = 'DATA_DOMAIN_BOOST' THEN 1 + WHEN @URL IS NOT NULL THEN (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) + ELSE (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) + END END ---------------------------------------------------------------------------------------------------- @@ -1418,7 +1493,7 @@ BEGIN SET @Error = @@ERROR END - IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN SET @ErrorMessage = 'The value for the parameter @NumberOfFiles is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1509,7 +1584,7 @@ BEGIN SET @Error = @@ERROR END - IF (@URL IS NOT NULL AND @Directory IS NOT NULL) OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@URL IS NOT NULL AND @Version < 11.03339) OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@URL NOT LIKE 'https://%/%') + IF (@URL IS NOT NULL AND @Directory IS NOT NULL) OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@URL IS NOT NULL AND @Version < 11.03339) OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @URL is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1537,7 +1612,7 @@ BEGIN SET @Error = @@ERROR END - IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL NOT LIKE 'https://%/%') OR (@MirrorURL IS NOT NULL AND @URL IS NULL) + IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @URL IS NULL) BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -2459,10 +2534,11 @@ BEGIN FROM @Directories ORDER BY ID ASC - INSERT INTO @CurrentURLs (ID, DirectoryPath, Mirror) + INSERT INTO @CurrentURLs (ID, DirectoryPath, Mirror, DirectoryNumber) SELECT ROW_NUMBER() OVER (ORDER BY ID), DirectoryPath + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END, - Mirror + Mirror, + ROW_NUMBER() OVER (PARTITION BY Mirror ORDER BY ID ASC) FROM @URLs ORDER BY ID ASC @@ -2677,7 +2753,9 @@ BEGIN SELECT @CurrentDirectoryPath = DirectoryPath FROM @CurrentURLs - WHERE Mirror = 0 + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + AND Mirror = 0 SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) @@ -2705,7 +2783,9 @@ BEGIN SELECT @CurrentDirectoryPath = DirectoryPath FROM @CurrentURLs - WHERE Mirror = 1 + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + AND Mirror = 1 SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) @@ -3460,7 +3540,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-30 11:14:12 //-- + --// Version: 2019-01-01 15:33:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5186,7 +5266,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2018-12-30 11:14:12 //-- + --// Version: 2019-01-01 15:33:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 67c063aa469645895bb7275d354f25eeb8c48565 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 1 Jan 2019 15:42:46 +0100 Subject: [PATCH 086/188] Add files via upload From 5d23fc357c3b827b8f74b882c96845cd581c57f6 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 1 Jan 2019 19:38:26 +0100 Subject: [PATCH 087/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 6 +++++- MaintenanceSolution.sql | 14 +++++++++----- 5 files changed, 17 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 4d84b6e9..012d38da 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 15:33:12 //-- + --// Version: 2019-01-01 19:33:57 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index a213c21e..0d0f22c1 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 15:33:12 //-- + --// Version: 2019-01-01 19:33:57 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 1af9d7bb..8e525ac1 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 15:33:12 //-- + --// Version: 2019-01-01 19:33:57 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index e66ddc1e..e47fdcb2 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 15:33:12 //-- + --// Version: 2019-01-01 19:33:57 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -111,6 +111,7 @@ BEGIN DECLARE @CurrentExtendedInfo07 xml DECLARE @CurrentIxID int + DECLARE @CurrentIxOrder int DECLARE @CurrentSchemaID int DECLARE @CurrentSchemaName nvarchar(max) DECLARE @CurrentObjectID int @@ -1572,6 +1573,7 @@ BEGIN WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SELECT TOP 1 @CurrentIxID = ID, + @CurrentIxOrder = [Order], @CurrentSchemaID = SchemaID, @CurrentSchemaName = SchemaName, @CurrentObjectID = ObjectID, @@ -2077,6 +2079,7 @@ BEGIN SET Completed = 1 WHERE Selected = 1 AND Completed = 0 + AND [Order] = @CurrentIxOrder AND ID = @CurrentIxID -- Clear variables @@ -2100,6 +2103,7 @@ BEGIN SET @CurrentExtendedInfo07 = NULL SET @CurrentIxID = NULL + SET @CurrentIxOrder = NULL SET @CurrentSchemaID = NULL SET @CurrentSchemaName = NULL SET @CurrentObjectID = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 95e88325..dcc21050 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-01-01 15:33:12 +Version: 2019-01-01 19:33:57 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 15:33:12 //-- + --// Version: 2019-01-01 19:33:57 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -409,7 +409,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 15:33:12 //-- + --// Version: 2019-01-01 19:33:57 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3540,7 +3540,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 15:33:12 //-- + --// Version: 2019-01-01 19:33:57 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5266,7 +5266,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 15:33:12 //-- + --// Version: 2019-01-01 19:33:57 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5326,6 +5326,7 @@ BEGIN DECLARE @CurrentExtendedInfo07 xml DECLARE @CurrentIxID int + DECLARE @CurrentIxOrder int DECLARE @CurrentSchemaID int DECLARE @CurrentSchemaName nvarchar(max) DECLARE @CurrentObjectID int @@ -6787,6 +6788,7 @@ BEGIN WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SELECT TOP 1 @CurrentIxID = ID, + @CurrentIxOrder = [Order], @CurrentSchemaID = SchemaID, @CurrentSchemaName = SchemaName, @CurrentObjectID = ObjectID, @@ -7292,6 +7294,7 @@ BEGIN SET Completed = 1 WHERE Selected = 1 AND Completed = 0 + AND [Order] = @CurrentIxOrder AND ID = @CurrentIxID -- Clear variables @@ -7315,6 +7318,7 @@ BEGIN SET @CurrentExtendedInfo07 = NULL SET @CurrentIxID = NULL + SET @CurrentIxOrder = NULL SET @CurrentSchemaID = NULL SET @CurrentSchemaName = NULL SET @CurrentObjectID = NULL From 02d565b06236275ba59ac1c3a99a4508a7134231 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 5 Jan 2019 22:55:52 +0100 Subject: [PATCH 088/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 24 ++++++++++++++++-------- 5 files changed, 20 insertions(+), 12 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 012d38da..5ccb773c 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 19:33:57 //-- + --// Version: 2019-01-05 12:03:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 0d0f22c1..df4619a9 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 19:33:57 //-- + --// Version: 2019-01-05 12:03:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 8e525ac1..93ccb8d7 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 19:33:57 //-- + --// Version: 2019-01-05 12:03:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index e47fdcb2..b0e14594 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 19:33:57 //-- + --// Version: 2019-01-05 12:03:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index dcc21050..fecf7ff2 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-01-01 19:33:57 +Version: 2019-01-05 12:03:54 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 19:33:57 //-- + --// Version: 2019-01-05 12:03:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -409,7 +409,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 19:33:57 //-- + --// Version: 2019-01-05 12:03:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3540,7 +3540,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 19:33:57 //-- + --// Version: 2019-01-05 12:03:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5266,7 +5266,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-01 19:33:57 //-- + --// Version: 2019-01-05 12:03:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7443,7 +7443,9 @@ BEGIN DECLARE @TokenServer nvarchar(max) DECLARE @TokenJobID nvarchar(max) + DECLARE @TokenJobName nvarchar(max) DECLARE @TokenStepID nvarchar(max) + DECLARE @TokenStepName nvarchar(max) DECLARE @TokenDate nvarchar(max) DECLARE @TokenTime nvarchar(max) DECLARE @TokenLogDirectory nvarchar(max) @@ -7511,6 +7513,12 @@ BEGIN SET @TokenTime = '$' + '(STRTTM)' END + IF @Version >= 13 + BEGIN + SET @TokenJobName = '$' + '(ESCAPE_SQUOTE(JOBNAME))' + SET @TokenStepName = '$' + '(ESCAPE_SQUOTE(STEPNAME))' + END + IF @Version >= 12 AND @HostPlatform = 'Windows' BEGIN SET @TokenLogDirectory = '$' + '(ESCAPE_SQUOTE(SQLLOGDIR))' @@ -7713,9 +7721,9 @@ BEGIN IF @AmazonRDS = 0 AND SERVERPROPERTY('EngineEdition') <> 8 BEGIN - SET @CurrentOutputFileName = COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + @DirectorySeparator + ISNULL(@CurrentOutputFileNamePart01 + '_','') + ISNULL(@CurrentOutputFileNamePart02 + '_','') + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@CurrentOutputFileName) > 200 SET @CurrentOutputFileName = COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + @DirectorySeparator + ISNULL(@CurrentOutputFileNamePart01 + '_','') + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' - IF LEN(@CurrentOutputFileName) > 200 SET @CurrentOutputFileName = COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + @DirectorySeparator + @TokenJobID + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' + SET @CurrentOutputFileName = COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + @DirectorySeparator + ISNULL(CASE WHEN @TokenJobName IS NULL THEN @CurrentOutputFileNamePart01 END + '_','') + ISNULL(CASE WHEN @TokenJobName IS NULL THEN @CurrentOutputFileNamePart02 END + '_','') + ISNULL(@TokenJobName,@TokenJobID) + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' + IF LEN(@CurrentOutputFileName) > 200 SET @CurrentOutputFileName = COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + @DirectorySeparator + ISNULL(CASE WHEN @TokenJobName IS NULL THEN @CurrentOutputFileNamePart01 END + '_','') + ISNULL(@TokenJobName,@TokenJobID) + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' + IF LEN(@CurrentOutputFileName) > 200 SET @CurrentOutputFileName = COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + @DirectorySeparator + ISNULL(@TokenJobName,@TokenJobID) + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' IF LEN(@CurrentOutputFileName) > 200 SET @CurrentOutputFileName = NULL END From fb098ff5870d192f769bd0a61b6c7b754fc4f8dd Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 5 Jan 2019 22:57:55 +0100 Subject: [PATCH 089/188] Add files via upload From ca4c8985166a8ec8348d1e36d5e292565f1c5003 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 6 Jan 2019 11:05:09 +0100 Subject: [PATCH 090/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 61 +++++++++++++++++++++++++++------ MaintenanceSolution.sql | 69 ++++++++++++++++++++++++++++++-------- 5 files changed, 109 insertions(+), 27 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 5ccb773c..b86e0ae7 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-05 12:03:54 //-- + --// Version: 2019-01-06 10:58:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index df4619a9..6d6656dc 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-05 12:03:54 //-- + --// Version: 2019-01-06 10:58:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 93ccb8d7..05622d74 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-05 12:03:54 //-- + --// Version: 2019-01-06 10:58:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index b0e14594..adaeb772 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-05 12:03:54 //-- + --// Version: 2019-01-06 10:58:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -232,15 +232,20 @@ BEGIN DECLARE @CurrentActionsAllowed TABLE ([Action] nvarchar(max)) - DECLARE @CurrentAlterIndexWithClauseArguments TABLE (ID int IDENTITY, - Argument nvarchar(max)) + Argument nvarchar(max), + Added bit DEFAULT 0) + DECLARE @CurrentAlterIndexArgumentID int + DECLARE @CurrentAlterIndexArgument nvarchar(max) DECLARE @CurrentAlterIndexWithClause nvarchar(max) DECLARE @CurrentUpdateStatisticsWithClauseArguments TABLE (ID int IDENTITY, - Argument nvarchar(max)) + Argument nvarchar(max), + Added bit DEFAULT 0) + DECLARE @CurrentUpdateStatisticsArgumentID int + DECLARE @CurrentUpdateStatisticsArgument nvarchar(max) DECLARE @CurrentUpdateStatisticsWithClause nvarchar(max) DECLARE @Error int @@ -1986,9 +1991,25 @@ BEGIN BEGIN SET @CurrentAlterIndexWithClause = ' WITH (' - SELECT @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + Argument + ', ' - FROM @CurrentAlterIndexWithClauseArguments - ORDER BY ID ASC + WHILE (1 = 1) + BEGIN + SELECT TOP 1 @CurrentAlterIndexArgumentID = ID, + @CurrentAlterIndexArgument = Argument + FROM @CurrentAlterIndexWithClauseArguments + WHERE Added = 0 + ORDER BY ID ASC + + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + + SET @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + @CurrentAlterIndexArgument + ', ' + + UPDATE @CurrentAlterIndexWithClauseArguments + SET Added = 1 + WHERE [ID] = @CurrentAlterIndexArgumentID + END SET @CurrentAlterIndexWithClause = RTRIM(@CurrentAlterIndexWithClause) @@ -2055,9 +2076,25 @@ BEGIN BEGIN SET @CurrentUpdateStatisticsWithClause = ' WITH' - SELECT @CurrentUpdateStatisticsWithClause = @CurrentUpdateStatisticsWithClause + ' ' + Argument + ',' - FROM @CurrentUpdateStatisticsWithClauseArguments - ORDER BY ID ASC + WHILE (1 = 1) + BEGIN + SELECT TOP 1 @CurrentUpdateStatisticsArgumentID = ID, + @CurrentUpdateStatisticsArgument = Argument + FROM @CurrentUpdateStatisticsWithClauseArguments + WHERE Added = 0 + ORDER BY ID ASC + + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + + SET @CurrentUpdateStatisticsWithClause = @CurrentUpdateStatisticsWithClause + ' ' + @CurrentUpdateStatisticsArgument + ',' + + UPDATE @CurrentUpdateStatisticsWithClauseArguments + SET Added = 1 + WHERE [ID] = @CurrentUpdateStatisticsArgumentID + END SET @CurrentUpdateStatisticsWithClause = LEFT(@CurrentUpdateStatisticsWithClause,LEN(@CurrentUpdateStatisticsWithClause) - 1) END @@ -2142,7 +2179,11 @@ BEGIN SET @CurrentUpdateStatistics = NULL SET @CurrentStatisticsSample = NULL SET @CurrentStatisticsResample = NULL + SET @CurrentAlterIndexArgumentID = NULL + SET @CurrentAlterIndexArgument = NULL SET @CurrentAlterIndexWithClause = NULL + SET @CurrentUpdateStatisticsArgumentID = NULL + SET @CurrentUpdateStatisticsArgument = NULL SET @CurrentUpdateStatisticsWithClause = NULL DELETE FROM @CurrentActionsAllowed diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index fecf7ff2..b482f1d0 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-01-05 12:03:54 +Version: 2019-01-06 10:58:01 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-05 12:03:54 //-- + --// Version: 2019-01-06 10:58:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -409,7 +409,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-05 12:03:54 //-- + --// Version: 2019-01-06 10:58:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3540,7 +3540,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-05 12:03:54 //-- + --// Version: 2019-01-06 10:58:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5266,7 +5266,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-05 12:03:54 //-- + --// Version: 2019-01-06 10:58:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5447,15 +5447,20 @@ BEGIN DECLARE @CurrentActionsAllowed TABLE ([Action] nvarchar(max)) - DECLARE @CurrentAlterIndexWithClauseArguments TABLE (ID int IDENTITY, - Argument nvarchar(max)) + Argument nvarchar(max), + Added bit DEFAULT 0) + DECLARE @CurrentAlterIndexArgumentID int + DECLARE @CurrentAlterIndexArgument nvarchar(max) DECLARE @CurrentAlterIndexWithClause nvarchar(max) DECLARE @CurrentUpdateStatisticsWithClauseArguments TABLE (ID int IDENTITY, - Argument nvarchar(max)) + Argument nvarchar(max), + Added bit DEFAULT 0) + DECLARE @CurrentUpdateStatisticsArgumentID int + DECLARE @CurrentUpdateStatisticsArgument nvarchar(max) DECLARE @CurrentUpdateStatisticsWithClause nvarchar(max) DECLARE @Error int @@ -7201,9 +7206,25 @@ BEGIN BEGIN SET @CurrentAlterIndexWithClause = ' WITH (' - SELECT @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + Argument + ', ' - FROM @CurrentAlterIndexWithClauseArguments - ORDER BY ID ASC + WHILE (1 = 1) + BEGIN + SELECT TOP 1 @CurrentAlterIndexArgumentID = ID, + @CurrentAlterIndexArgument = Argument + FROM @CurrentAlterIndexWithClauseArguments + WHERE Added = 0 + ORDER BY ID ASC + + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + + SET @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + @CurrentAlterIndexArgument + ', ' + + UPDATE @CurrentAlterIndexWithClauseArguments + SET Added = 1 + WHERE [ID] = @CurrentAlterIndexArgumentID + END SET @CurrentAlterIndexWithClause = RTRIM(@CurrentAlterIndexWithClause) @@ -7270,9 +7291,25 @@ BEGIN BEGIN SET @CurrentUpdateStatisticsWithClause = ' WITH' - SELECT @CurrentUpdateStatisticsWithClause = @CurrentUpdateStatisticsWithClause + ' ' + Argument + ',' - FROM @CurrentUpdateStatisticsWithClauseArguments - ORDER BY ID ASC + WHILE (1 = 1) + BEGIN + SELECT TOP 1 @CurrentUpdateStatisticsArgumentID = ID, + @CurrentUpdateStatisticsArgument = Argument + FROM @CurrentUpdateStatisticsWithClauseArguments + WHERE Added = 0 + ORDER BY ID ASC + + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + + SET @CurrentUpdateStatisticsWithClause = @CurrentUpdateStatisticsWithClause + ' ' + @CurrentUpdateStatisticsArgument + ',' + + UPDATE @CurrentUpdateStatisticsWithClauseArguments + SET Added = 1 + WHERE [ID] = @CurrentUpdateStatisticsArgumentID + END SET @CurrentUpdateStatisticsWithClause = LEFT(@CurrentUpdateStatisticsWithClause,LEN(@CurrentUpdateStatisticsWithClause) - 1) END @@ -7357,7 +7394,11 @@ BEGIN SET @CurrentUpdateStatistics = NULL SET @CurrentStatisticsSample = NULL SET @CurrentStatisticsResample = NULL + SET @CurrentAlterIndexArgumentID = NULL + SET @CurrentAlterIndexArgument = NULL SET @CurrentAlterIndexWithClause = NULL + SET @CurrentUpdateStatisticsArgumentID = NULL + SET @CurrentUpdateStatisticsArgument = NULL SET @CurrentUpdateStatisticsWithClause = NULL DELETE FROM @CurrentActionsAllowed From a267183bb6d8106954827efc850e61e4a0c55811 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 6 Jan 2019 19:51:04 +0100 Subject: [PATCH 091/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 16 +++++++++--- DatabaseIntegrityCheck.sql | 18 ++++++------- IndexOptimize.sql | 14 +++++----- MaintenanceSolution.sql | 52 ++++++++++++++++++++++---------------- 5 files changed, 59 insertions(+), 43 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index b86e0ae7..c78e1a7f 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 10:58:01 //-- + --// Version: 2019-01-06 19:21:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 6d6656dc..dc35b4de 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 10:58:01 //-- + --// Version: 2019-01-06 19:21:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1482,7 +1482,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1494,7 +1494,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1834,7 +1834,7 @@ BEGIN BEGIN SET @CurrentBackupType = 'DIFF' END - IF @CurrentBackupType = 'DIFF' AND @CurrentDatabaseName <> 'master' AND (@CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @ModificationLevel)) + IF @CurrentBackupType = 'DIFF' AND (@CurrentDatabaseName = 'master' OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @ModificationLevel)) BEGIN SET @CurrentBackupType = 'FULL' END @@ -1856,6 +1856,14 @@ BEGIN AND checkpoint_lsn = @CurrentDifferentialBaseLSN END + IF @ChangeBackupType = 'Y' + BEGIN + IF @CurrentBackupType = 'DIFF' AND @CurrentDifferentialBaseIsSnapshot = 1 + BEGIN + SET @CurrentBackupType = 'FULL' + END + END + SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring WHERE database_id = @CurrentDatabaseID diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 05622d74..c7250360 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 10:58:01 //-- + --// Version: 2019-01-06 19:21:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -829,7 +829,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -841,7 +841,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -853,7 +853,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -865,7 +865,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -878,7 +878,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -891,7 +891,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1374,7 +1374,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following file groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1532,7 +1532,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following objects do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END diff --git a/IndexOptimize.sql b/IndexOptimize.sql index adaeb772..7fa3dc00 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 10:58:01 //-- + --// Version: 2019-01-06 19:21:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1023,7 +1023,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1035,7 +1035,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1047,7 +1047,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1060,7 +1060,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1556,7 +1556,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1571,7 +1571,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index b482f1d0..eb10fbb4 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-01-06 10:58:01 +Version: 2019-01-06 19:21:46 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 10:58:01 //-- + --// Version: 2019-01-06 19:21:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -409,7 +409,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 10:58:01 //-- + --// Version: 2019-01-06 19:21:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1818,7 +1818,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -1830,7 +1830,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -2170,7 +2170,7 @@ BEGIN BEGIN SET @CurrentBackupType = 'DIFF' END - IF @CurrentBackupType = 'DIFF' AND @CurrentDatabaseName <> 'master' AND (@CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @ModificationLevel)) + IF @CurrentBackupType = 'DIFF' AND (@CurrentDatabaseName = 'master' OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @ModificationLevel)) BEGIN SET @CurrentBackupType = 'FULL' END @@ -2192,6 +2192,14 @@ BEGIN AND checkpoint_lsn = @CurrentDifferentialBaseLSN END + IF @ChangeBackupType = 'Y' + BEGIN + IF @CurrentBackupType = 'DIFF' AND @CurrentDifferentialBaseIsSnapshot = 1 + BEGIN + SET @CurrentBackupType = 'FULL' + END + END + SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring WHERE database_id = @CurrentDatabaseID @@ -3540,7 +3548,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 10:58:01 //-- + --// Version: 2019-01-06 19:21:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4332,7 +4340,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4344,7 +4352,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4356,7 +4364,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4368,7 +4376,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4381,7 +4389,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4394,7 +4402,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -4877,7 +4885,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following file groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -5035,7 +5043,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following objects do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -5266,7 +5274,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 10:58:01 //-- + --// Version: 2019-01-06 19:21:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6238,7 +6246,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -6250,7 +6258,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -6262,7 +6270,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -6275,7 +6283,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -6771,7 +6779,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END @@ -6786,7 +6794,7 @@ BEGIN IF @@ROWCOUNT > 0 BEGIN SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END From fc1a6bdada5c56bab1c793656893ebe086990a9e Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 11 Jan 2019 00:58:41 +0100 Subject: [PATCH 092/188] Update issue templates --- .github/ISSUE_TEMPLATE/question.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/question.md diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 00000000..82d1e966 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,10 @@ +--- +name: Question +about: Ask a question about the project +title: '' +labels: question +assignees: '' + +--- + + From 410db79b696c3e91c7ac6c30eae0ccd712f9c15f Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 11 Jan 2019 21:34:40 +0100 Subject: [PATCH 093/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 24 +++++++++++++++--------- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 32 +++++++++++++++++++------------- 5 files changed, 37 insertions(+), 25 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index c78e1a7f..1b8a8116 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 19:21:46 //-- + --// Version: 2019-01-11 21:26:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index dc35b4de..2d15a5dc 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 19:21:46 //-- + --// Version: 2019-01-11 21:26:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1374,32 +1374,32 @@ BEGIN SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -2194,6 +2194,9 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),3))) END INSERT INTO @CurrentDirectories (ID, DirectoryPath, Mirror, DirectoryNumber, CreateCompleted, CleanupCompleted) @@ -2337,7 +2340,10 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),3))) SELECT @CurrentMaxFilePathLength = CASE WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index c7250360..6335c026 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 19:21:46 //-- + --// Version: 2019-01-11 21:26:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 7fa3dc00..407d1a1d 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 19:21:46 //-- + --// Version: 2019-01-11 21:26:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index eb10fbb4..63040c07 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-01-06 19:21:46 +Version: 2019-01-11 21:26:19 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 19:21:46 //-- + --// Version: 2019-01-11 21:26:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -409,7 +409,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 19:21:46 //-- + --// Version: 2019-01-11 21:26:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1710,32 +1710,32 @@ BEGIN SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{FileNumber}',''),'{FileExtension}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -2530,6 +2530,9 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),3))) END INSERT INTO @CurrentDirectories (ID, DirectoryPath, Mirror, DirectoryNumber, CreateCompleted, CleanupCompleted) @@ -2673,7 +2676,10 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),3))) SELECT @CurrentMaxFilePathLength = CASE WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) @@ -3548,7 +3554,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 19:21:46 //-- + --// Version: 2019-01-11 21:26:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5274,7 +5280,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-06 19:21:46 //-- + --// Version: 2019-01-11 21:26:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 936ef1f4870c6d1c6710fd37d95a6a4eb3a1b756 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 12 Jan 2019 12:53:52 +0100 Subject: [PATCH 094/188] Add files via upload --- CommandExecute.sql | 40 ++- DatabaseBackup.sql | 288 ++++++++++------ DatabaseIntegrityCheck.sql | 142 +++++--- IndexOptimize.sql | 187 +++++++---- MaintenanceSolution.sql | 663 +++++++++++++++++++++++++------------ 5 files changed, 889 insertions(+), 431 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 1b8a8116..dd4bce35 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-11 21:26:19 //-- + --// Version: 2019-01-12 12:45:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -56,39 +56,47 @@ BEGIN DECLARE @Error int DECLARE @ReturnCode int + DECLARE @EmptyLine nvarchar(max) + SET @Error = 0 SET @ReturnCode = 0 + SET @EmptyLine = CHAR(9) + ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 @@ -103,44 +111,50 @@ BEGIN IF @Command IS NULL OR @Command = '' BEGIN - SET @ErrorMessage = 'The value for the parameter @Command is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Command is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CommandType IS NULL OR @CommandType = '' OR LEN(@CommandType) > 60 BEGIN - SET @ErrorMessage = 'The value for the parameter @CommandType is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CommandType is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Mode NOT IN(1,2) OR @Mode IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Mode is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Mode is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 @@ -220,9 +234,11 @@ BEGIN SET @EndMessage = 'Duration: ' + CASE WHEN DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) > 0 THEN CAST(DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) AS nvarchar) + '.' ELSE '' END + CONVERT(nvarchar,@EndTimeSec - @StartTimeSec,108) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTimeSec,120) + CHAR(13) + CHAR(10) + ' ' + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTimeSec,120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + IF @LogToTable = 'Y' BEGIN UPDATE dbo.CommandLog diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 2d15a5dc..74815bb7 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-11 21:26:19 //-- + --// Version: 2019-01-12 12:45:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -238,9 +238,13 @@ BEGIN DECLARE @Error int DECLARE @ReturnCode int + DECLARE @EmptyLine nvarchar(max) + SET @Error = 0 SET @ReturnCode = 0 + SET @EmptyLine = CHAR(9) + SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) IF @Version >= 14 @@ -344,81 +348,93 @@ BEGIN SET @StartMessage = 'Version: ' + @VersionTimestamp RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' + SET @StartMessage = 'Source: https://ola.hallengren.com' RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @@TRANCOUNT <> 0 BEGIN - SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The transaction count is not 0.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @AmazonRDS = 1 BEGIN - SET @ErrorMessage = 'The stored procedure DatabaseBackup is not supported on Amazon RDS.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The stored procedure DatabaseBackup is not supported on Amazon RDS.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 @@ -549,9 +565,10 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -645,23 +662,26 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -676,9 +696,10 @@ BEGIN ORDER BY DatabaseName ASC IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -691,9 +712,10 @@ BEGIN OPTION (RECOMPILE) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -788,17 +810,19 @@ BEGIN IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @DirectoryCheck = 0 END IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @DirectoryCheck = 0 END @@ -822,9 +846,10 @@ BEGIN IF NOT EXISTS (SELECT * FROM @DirectoryInfo WHERE FileExists = 0 AND FileIsADirectory = 1 AND ParentDirectoryExists = 1) BEGIN - SET @ErrorMessage = 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END UPDATE @Directories @@ -906,18 +931,20 @@ BEGIN OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @URL is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @URL is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath NOT LIKE 'https://%/%') OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -1005,467 +1032,533 @@ BEGIN IF @BackupType NOT IN ('FULL','DIFF','LOG') OR @BackupType IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @BackupType is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @BackupType is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF SERVERPROPERTY('EngineEdition') = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN - SET @ErrorMessage = 'SQL Database Managed Instance only supports COPY_ONLY full backups.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'SQL Database Managed Instance only supports COPY_ONLY full backups.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Verify is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Verify is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CleanupTime < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CleanupTime IS NOT NULL AND @HostPlatform = 'Linux' BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CleanupMode is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @Compress is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Compress is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CopyOnly NOT IN ('Y','N') OR @CopyOnly IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CopyOnly is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CopyOnly is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @ChangeBackupType is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @ChangeBackupType is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN - SET @ErrorMessage = 'The value for the parameter @BackupSoftware is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @BackupSoftware is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @BackupSoftware = 'LITESPEED' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_backup_database') BEGIN - SET @ErrorMessage = 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN - SET @ErrorMessage = 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @BackupSoftware = 'SQLSAFE' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_ss_backup') BEGIN - SET @ErrorMessage = 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'PC' AND [name] = 'emc_run_backup') BEGIN - SET @ErrorMessage = 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CheckSum NOT IN ('Y','N') OR @CheckSum IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CheckSum is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CheckSum is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @BlockSize is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @BlockSize is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @BufferCount <= 0 OR @BufferCount > 2147483647 OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE') BEGIN - SET @ErrorMessage = 'The value for the parameter @BufferCount is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @BufferCount is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxTransferSize is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MaxTransferSize is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @NumberOfFiles is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @NumberOfFiles is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @CompressionLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CompressionLevel is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF LEN(@Description) > 255 OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) BEGIN - SET @ErrorMessage = 'The value for the parameter @Description is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Description is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) OR (@BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32)) OR (@BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32)) OR (@BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64)) BEGIN - SET @ErrorMessage = 'The value for the parameter @Threads is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Threads is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) OR @Throttle < 1 OR @Throttle > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @Throttle is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Throttle is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Encrypt is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Encrypt is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @EncryptionAlgorithm is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @EncryptionAlgorithm is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL) OR (@ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate)) BEGIN - SET @ErrorMessage = 'The value for the parameter @ServerCertificate is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @ServerCertificate is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL) OR (@ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey)) BEGIN - SET @ErrorMessage = 'The value for the parameter @ServerAsymmetricKey is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @ServerAsymmetricKey is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @EncryptionKey is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @EncryptionKey is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL OR (@ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG') BEGIN - SET @ErrorMessage = 'The value for the parameter @ReadWriteFileGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @ReadWriteFileGroups is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @OverrideBackupPreference NOT IN('Y','N') OR @OverrideBackupPreference IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @OverrideBackupPreference is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @OverrideBackupPreference is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL OR (@NoRecovery = 'Y' AND @BackupType <> 'LOG') OR (@NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE') BEGIN - SET @ErrorMessage = 'The value for the parameter @NoRecovery is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @NoRecovery is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@URL IS NOT NULL AND @Directory IS NOT NULL) OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@URL IS NOT NULL AND @Version < 11.03339) OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @URL is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @URL is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) BEGIN - SET @ErrorMessage = 'The value for the parameter @Credential is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Credential is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MirrorCleanupTime < 0 OR (@MirrorCleanupTime IS NOT NULL AND @MirrorDirectory IS NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorCleanupTime is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MirrorCleanupTime is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MirrorCleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @MirrorCleanupMode IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorCleanupMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MirrorCleanupMode is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @URL IS NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @AdaptiveCompression NOT IN('SIZE','SPEED') OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) BEGIN - SET @ErrorMessage = 'The value for the parameter @AdaptiveCompression is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @AdaptiveCompression is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@ModificationLevel IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN - SET @ErrorMessage = 'The value for the parameter @ModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @ModificationLevel is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN - SET @ErrorMessage = 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN - SET @ErrorMessage = 'The value for the parameter @TimeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @TimeSinceLastLogBackup is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostHost is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostHost is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostUser is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostUser is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostDevicePath is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostDevicePath is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostLockboxPath is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostLockboxPath is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DirectoryStructure = '' BEGIN - SET @ErrorMessage = 'The value for the parameter @DirectoryStructure is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DirectoryStructure is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @AvailabilityGroupDirectoryStructure = '' BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @FileName IS NULL OR @FileName = '' OR @FileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') OR @FileName LIKE '%{DirectorySeperator}%' OR @FileName LIKE '%/%' OR @FileName LIKE '%\%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileName is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FileName is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) OR @AvailabilityGroupFileName = '' OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' OR @AvailabilityGroupFileName LIKE '%/%' OR @AvailabilityGroupFileName LIKE '%\%' BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupFileName is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupFileName is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @FileExtensionFull LIKE '%.%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileExtensionFull is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FileExtensionFull is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @FileExtensionDiff LIKE '%.%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileExtensionDiff is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FileExtensionDiff is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @FileExtensionLog LIKE '%.%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileExtensionLog is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FileExtensionLog is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Init NOT IN('Y','N') OR @Init IS NULL OR (@Init = 'Y' AND @BackupType = 'LOG') OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Init is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Init is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 BEGIN - SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = @Error GOTO Logging END @@ -1481,9 +1574,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -1493,9 +1587,10 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -1504,9 +1599,10 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -1703,8 +1799,9 @@ BEGIN BEGIN ROLLBACK TRANSACTION END - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -1976,7 +2073,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - RAISERROR('',10,1) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) @@ -3093,9 +3190,10 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END -- Update that the database is completed diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 6335c026..cd314b48 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-11 21:26:19 //-- + --// Version: 2019-01-12 12:45:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -176,9 +176,13 @@ BEGIN DECLARE @Error int DECLARE @ReturnCode int + DECLARE @EmptyLine nvarchar(max) + SET @Error = 0 SET @ReturnCode = 0 + SET @EmptyLine = CHAR(9) + SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) IF @Version >= 14 @@ -246,74 +250,85 @@ BEGIN SET @StartMessage = 'Version: ' + @VersionTimestamp RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' + SET @StartMessage = 'Source: https://ola.hallengren.com' RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @@TRANCOUNT <> 0 BEGIN - SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The transaction count is not 0.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 @@ -444,9 +459,10 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -540,23 +556,26 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -692,127 +711,145 @@ BEGIN IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) OR EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) OR NOT EXISTS (SELECT * FROM @SelectedCheckCommands) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG'))) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE'))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CheckCommands is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CheckCommands is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @PhysicalOnly is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @PhysicalOnly is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @NoIndex is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @NoIndex is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL OR (@ExtendedLogicalChecks = 'Y' AND NOT @Version >= 10) OR (@PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y') BEGIN - SET @ErrorMessage = 'The value for the parameter @ExtendedLogicalChecks is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @ExtendedLogicalChecks is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @TabLock is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @TabLock is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) OR (@FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups)) OR (@FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP')) BEGIN - SET @ErrorMessage = 'The value for the parameter @FileGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FileGroups is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) OR (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) OR (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Objects is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Objects is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupReplicas is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupReplicas is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @TimeLimit < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LockTimeout < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LockMessageSeverity NOT IN(10,16) BEGIN - SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 BEGIN - SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = @Error GOTO Logging END @@ -828,9 +865,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -840,9 +878,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -852,9 +891,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -864,9 +904,10 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -877,9 +918,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -890,9 +932,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -901,9 +944,10 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -1125,8 +1169,9 @@ BEGIN BEGIN ROLLBACK TRANSACTION END - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -1373,9 +1418,10 @@ BEGIN AND NOT EXISTS (SELECT * FROM @tmpFileGroups WHERE FileGroupName = SelectedFileGroups.FileGroupName) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following file groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following file groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) @@ -1404,9 +1450,10 @@ BEGIN IF @CurrentFileGroupExists IS NULL SET @CurrentFileGroupExists = 0 END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + ' The file group ' + QUOTENAME(@CurrentFileGroupName) + ' in the database ' + QUOTENAME(@CurrentDatabaseName) + ' is locked. It could not be checked if the filegroup exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + ' The file group ' + QUOTENAME(@CurrentFileGroupName) + ' in the database ' + QUOTENAME(@CurrentDatabaseName) + ' is locked. It could not be checked if the filegroup exists.' ELSE '' END SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -1531,9 +1578,10 @@ BEGIN AND NOT EXISTS (SELECT * FROM @tmpObjects WHERE SchemaName = SelectedObjects.SchemaName AND ObjectName = SelectedObjects.ObjectName) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following objects do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following objects do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) @@ -1565,9 +1613,10 @@ BEGIN IF @CurrentObjectExists IS NULL SET @CurrentObjectExists = 0 END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + 'The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the object exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + 'The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the object exists.' ELSE '' END SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -1639,9 +1688,10 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END -- Update that the database is completed diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 407d1a1d..6180dc33 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-11 21:26:19 //-- + --// Version: 2019-01-12 12:45:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -251,9 +251,13 @@ BEGIN DECLARE @Error int DECLARE @ReturnCode int + DECLARE @EmptyLine nvarchar(max) + SET @Error = 0 SET @ReturnCode = 0 + SET @EmptyLine = CHAR(9) + SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) IF @Version >= 14 @@ -335,74 +339,85 @@ BEGIN SET @StartMessage = 'Version: ' + @VersionTimestamp RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' + SET @StartMessage = 'Source: https://ola.hallengren.com' RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @@TRANCOUNT <> 0 BEGIN - SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The transaction count is not 0.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 @@ -532,9 +547,10 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -628,23 +644,26 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -772,241 +791,275 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationLow is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FragmentationLow is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationMedium is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FragmentationMedium is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'High' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationHigh is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FragmentationHigh is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 >= @FragmentationLevel2 OR @FragmentationLevel1 IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationLevel1 is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FragmentationLevel1 is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 <= @FragmentationLevel1 OR @FragmentationLevel2 IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationLevel2 is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FragmentationLevel2 is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @MinNumberOfPages is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MinNumberOfPages is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MaxNumberOfPages < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxNumberOfPages is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MaxNumberOfPages is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @SortInTempdb is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @SortInTempdb is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @FillFactor is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FillFactor is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @PadIndex NOT IN('Y','N') BEGIN - SET @ErrorMessage = 'The value for the parameter @PadIndex is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @PadIndex is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LOBCompaction is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LOBCompaction is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN - SET @ErrorMessage = 'The value for the parameter @UpdateStatistics is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @UpdateStatistics is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @OnlyModifiedStatistics is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @OnlyModifiedStatistics is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @StatisticsModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @StatisticsModificationLevel is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @StatisticsSample is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @StatisticsSample is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL OR (@StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @StatisticsResample is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @StatisticsResample is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @PartitionLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @PartitionLevel is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @MSShippedObjects is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MSShippedObjects is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) OR (@Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes)) BEGIN - SET @ErrorMessage = 'The value for the parameter @Indexes is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Indexes is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @TimeLimit < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Delay < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @Delay is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Delay is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @WaitAtLowPriorityMaxDuration < 0 OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @WaitAtLowPriorityAbortAfterWait IS NULL) OR (@WaitAtLowPriorityMaxDuration IS NULL AND @WaitAtLowPriorityAbortAfterWait IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL OR (@Resumable = 'Y' AND NOT (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8))) BEGIN - SET @ErrorMessage = 'The value for the parameter @Resumable is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Resumable is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Resumable and @SortInTempdb.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You can only specify one of the parameters @Resumable and @SortInTempdb.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LockTimeout < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LockMessageSeverity NOT IN(10,16) BEGIN - SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 BEGIN - SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = @Error GOTO Logging END @@ -1022,9 +1075,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -1034,9 +1088,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -1046,9 +1101,10 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -1059,9 +1115,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -1225,8 +1282,9 @@ BEGIN BEGIN ROLLBACK TRANSACTION END - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -1555,9 +1613,10 @@ BEGIN AND NOT EXISTS (SELECT * FROM @tmpIndexesStatistics WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -1570,9 +1629,10 @@ BEGIN AND NOT EXISTS (SELECT * FROM @tmpIndexesStatistics WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName AND IndexName = SelectedIndexes.IndexName) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) @@ -1638,9 +1698,10 @@ BEGIN END END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index exists.' ELSE '' END SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -1671,9 +1732,10 @@ BEGIN END END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the statistics exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the statistics exists.' ELSE '' END SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -1713,9 +1775,10 @@ BEGIN IF @CurrentModificationCounter IS NULL SET @CurrentModificationCounter = 0 END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The rows and modification_counter could not be checked.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The rows and modification_counter could not be checked.' ELSE '' END SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -1742,9 +1805,10 @@ BEGIN EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamDatabaseID int, @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseID = @CurrentDatabaseID, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The page_count and avg_fragmentation_in_percent could not be checked.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The page_count and avg_fragmentation_in_percent could not be checked.' ELSE '' END SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -2196,8 +2260,9 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @Error = @@ERROR END diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 63040c07..8fa9535b 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-01-11 21:26:19 +Version: 2019-01-12 12:45:42 You can contact me by e-mail at ola@hallengren.com. @@ -38,13 +38,13 @@ SET @LogToTable = 'Y' -- Log commands to a table. IF IS_SRVROLEMEMBER('sysadmin') = 0 AND NOT (DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa') BEGIN - SET @ErrorMessage = 'You need to be a member of the SysAdmin server role to install the SQL Server Maintenance Solution.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You need to be a member of the SysAdmin server role to install the SQL Server Maintenance Solution.' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT END IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' RAISERROR(@ErrorMessage,16,1) WITH NOWAIT END @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-11 21:26:19 //-- + --// Version: 2019-01-12 12:45:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -148,39 +148,47 @@ BEGIN DECLARE @Error int DECLARE @ReturnCode int + DECLARE @EmptyLine nvarchar(max) + SET @Error = 0 SET @ReturnCode = 0 + SET @EmptyLine = CHAR(9) + ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 @@ -195,44 +203,50 @@ BEGIN IF @Command IS NULL OR @Command = '' BEGIN - SET @ErrorMessage = 'The value for the parameter @Command is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Command is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CommandType IS NULL OR @CommandType = '' OR LEN(@CommandType) > 60 BEGIN - SET @ErrorMessage = 'The value for the parameter @CommandType is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CommandType is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Mode NOT IN(1,2) OR @Mode IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Mode is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Mode is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 @@ -312,9 +326,11 @@ BEGIN SET @EndMessage = 'Duration: ' + CASE WHEN DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) > 0 THEN CAST(DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) AS nvarchar) + '.' ELSE '' END + CONVERT(nvarchar,@EndTimeSec - @StartTimeSec,108) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTimeSec,120) + CHAR(13) + CHAR(10) + ' ' + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTimeSec,120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + IF @LogToTable = 'Y' BEGIN UPDATE dbo.CommandLog @@ -409,7 +425,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-11 21:26:19 //-- + --// Version: 2019-01-12 12:45:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -574,9 +590,13 @@ BEGIN DECLARE @Error int DECLARE @ReturnCode int + DECLARE @EmptyLine nvarchar(max) + SET @Error = 0 SET @ReturnCode = 0 + SET @EmptyLine = CHAR(9) + SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) IF @Version >= 14 @@ -680,81 +700,93 @@ BEGIN SET @StartMessage = 'Version: ' + @VersionTimestamp RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' + SET @StartMessage = 'Source: https://ola.hallengren.com' RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @@TRANCOUNT <> 0 BEGIN - SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The transaction count is not 0.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @AmazonRDS = 1 BEGIN - SET @ErrorMessage = 'The stored procedure DatabaseBackup is not supported on Amazon RDS.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The stored procedure DatabaseBackup is not supported on Amazon RDS.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 @@ -885,9 +917,10 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -981,23 +1014,26 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -1012,9 +1048,10 @@ BEGIN ORDER BY DatabaseName ASC IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -1027,9 +1064,10 @@ BEGIN OPTION (RECOMPILE) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -1124,17 +1162,19 @@ BEGIN IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @DirectoryCheck = 0 END IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @DirectoryCheck = 0 END @@ -1158,9 +1198,10 @@ BEGIN IF NOT EXISTS (SELECT * FROM @DirectoryInfo WHERE FileExists = 0 AND FileIsADirectory = 1 AND ParentDirectoryExists = 1) BEGIN - SET @ErrorMessage = 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END UPDATE @Directories @@ -1242,18 +1283,20 @@ BEGIN OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @URL is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @URL is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath NOT LIKE 'https://%/%') OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -1341,467 +1384,533 @@ BEGIN IF @BackupType NOT IN ('FULL','DIFF','LOG') OR @BackupType IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @BackupType is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @BackupType is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF SERVERPROPERTY('EngineEdition') = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN - SET @ErrorMessage = 'SQL Database Managed Instance only supports COPY_ONLY full backups.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'SQL Database Managed Instance only supports COPY_ONLY full backups.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Verify is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Verify is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CleanupTime < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CleanupTime IS NOT NULL AND @HostPlatform = 'Linux' BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CleanupMode is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @Compress is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Compress is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CopyOnly NOT IN ('Y','N') OR @CopyOnly IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CopyOnly is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CopyOnly is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @ChangeBackupType is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @ChangeBackupType is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN - SET @ErrorMessage = 'The value for the parameter @BackupSoftware is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @BackupSoftware is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @BackupSoftware = 'LITESPEED' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_backup_database') BEGIN - SET @ErrorMessage = 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN - SET @ErrorMessage = 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @BackupSoftware = 'SQLSAFE' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_ss_backup') BEGIN - SET @ErrorMessage = 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'PC' AND [name] = 'emc_run_backup') BEGIN - SET @ErrorMessage = 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @CheckSum NOT IN ('Y','N') OR @CheckSum IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CheckSum is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CheckSum is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @BlockSize is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @BlockSize is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @BufferCount <= 0 OR @BufferCount > 2147483647 OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE') BEGIN - SET @ErrorMessage = 'The value for the parameter @BufferCount is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @BufferCount is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxTransferSize is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MaxTransferSize is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @NumberOfFiles is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @NumberOfFiles is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @CompressionLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CompressionLevel is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF LEN(@Description) > 255 OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) BEGIN - SET @ErrorMessage = 'The value for the parameter @Description is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Description is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) OR (@BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32)) OR (@BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32)) OR (@BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64)) BEGIN - SET @ErrorMessage = 'The value for the parameter @Threads is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Threads is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) OR @Throttle < 1 OR @Throttle > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @Throttle is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Throttle is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Encrypt is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Encrypt is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @EncryptionAlgorithm is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @EncryptionAlgorithm is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL) OR (@ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate)) BEGIN - SET @ErrorMessage = 'The value for the parameter @ServerCertificate is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @ServerCertificate is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL) OR (@ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey)) BEGIN - SET @ErrorMessage = 'The value for the parameter @ServerAsymmetricKey is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @ServerAsymmetricKey is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @EncryptionKey is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @EncryptionKey is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL OR (@ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG') BEGIN - SET @ErrorMessage = 'The value for the parameter @ReadWriteFileGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @ReadWriteFileGroups is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @OverrideBackupPreference NOT IN('Y','N') OR @OverrideBackupPreference IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @OverrideBackupPreference is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @OverrideBackupPreference is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL OR (@NoRecovery = 'Y' AND @BackupType <> 'LOG') OR (@NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE') BEGIN - SET @ErrorMessage = 'The value for the parameter @NoRecovery is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @NoRecovery is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@URL IS NOT NULL AND @Directory IS NOT NULL) OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@URL IS NOT NULL AND @Version < 11.03339) OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @URL is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @URL is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) BEGIN - SET @ErrorMessage = 'The value for the parameter @Credential is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Credential is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MirrorCleanupTime < 0 OR (@MirrorCleanupTime IS NOT NULL AND @MirrorDirectory IS NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorCleanupTime is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MirrorCleanupTime is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MirrorCleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @MirrorCleanupMode IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorCleanupMode is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MirrorCleanupMode is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @URL IS NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @AdaptiveCompression NOT IN('SIZE','SPEED') OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) BEGIN - SET @ErrorMessage = 'The value for the parameter @AdaptiveCompression is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @AdaptiveCompression is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@ModificationLevel IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN - SET @ErrorMessage = 'The value for the parameter @ModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @ModificationLevel is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN - SET @ErrorMessage = 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN - SET @ErrorMessage = 'The value for the parameter @TimeSinceLastLogBackup is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @TimeSinceLastLogBackup is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostHost is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostHost is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostUser is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostUser is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostDevicePath is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostDevicePath is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostLockboxPath is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DataDomainBoostLockboxPath is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DirectoryStructure = '' BEGIN - SET @ErrorMessage = 'The value for the parameter @DirectoryStructure is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DirectoryStructure is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @AvailabilityGroupDirectoryStructure = '' BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @FileName IS NULL OR @FileName = '' OR @FileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') OR @FileName LIKE '%{DirectorySeperator}%' OR @FileName LIKE '%/%' OR @FileName LIKE '%\%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileName is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FileName is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) OR @AvailabilityGroupFileName = '' OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' OR @AvailabilityGroupFileName LIKE '%/%' OR @AvailabilityGroupFileName LIKE '%\%' BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupFileName is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupFileName is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @FileExtensionFull LIKE '%.%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileExtensionFull is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FileExtensionFull is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @FileExtensionDiff LIKE '%.%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileExtensionDiff is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FileExtensionDiff is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @FileExtensionLog LIKE '%.%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileExtensionLog is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FileExtensionLog is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Init NOT IN('Y','N') OR @Init IS NULL OR (@Init = 'Y' AND @BackupType = 'LOG') OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Init is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Init is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 BEGIN - SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = @Error GOTO Logging END @@ -1817,9 +1926,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -1829,9 +1939,10 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -1840,9 +1951,10 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -2039,8 +2151,9 @@ BEGIN BEGIN ROLLBACK TRANSACTION END - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -2312,7 +2425,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - RAISERROR('',10,1) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) @@ -3429,9 +3542,10 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END -- Update that the database is completed @@ -3554,7 +3668,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-11 21:26:19 //-- + --// Version: 2019-01-12 12:45:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3693,9 +3807,13 @@ BEGIN DECLARE @Error int DECLARE @ReturnCode int + DECLARE @EmptyLine nvarchar(max) + SET @Error = 0 SET @ReturnCode = 0 + SET @EmptyLine = CHAR(9) + SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) IF @Version >= 14 @@ -3763,74 +3881,85 @@ BEGIN SET @StartMessage = 'Version: ' + @VersionTimestamp RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' + SET @StartMessage = 'Source: https://ola.hallengren.com' RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @@TRANCOUNT <> 0 BEGIN - SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The transaction count is not 0.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 @@ -3961,9 +4090,10 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -4057,23 +4187,26 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -4209,127 +4342,145 @@ BEGIN IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) OR EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) OR NOT EXISTS (SELECT * FROM @SelectedCheckCommands) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG'))) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE'))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CheckCommands is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @CheckCommands is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @PhysicalOnly is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @PhysicalOnly is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @NoIndex is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @NoIndex is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL OR (@ExtendedLogicalChecks = 'Y' AND NOT @Version >= 10) OR (@PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y') BEGIN - SET @ErrorMessage = 'The value for the parameter @ExtendedLogicalChecks is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @ExtendedLogicalChecks is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @TabLock is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @TabLock is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) OR (@FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups)) OR (@FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP')) BEGIN - SET @ErrorMessage = 'The value for the parameter @FileGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FileGroups is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) OR (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) OR (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Objects is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Objects is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupReplicas is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupReplicas is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @TimeLimit < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LockTimeout < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LockMessageSeverity NOT IN(10,16) BEGIN - SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 BEGIN - SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = @Error GOTO Logging END @@ -4345,9 +4496,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -4357,9 +4509,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -4369,9 +4522,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -4381,9 +4535,10 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -4394,9 +4549,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -4407,9 +4563,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -4418,9 +4575,10 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -4642,8 +4800,9 @@ BEGIN BEGIN ROLLBACK TRANSACTION END - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -4890,9 +5049,10 @@ BEGIN AND NOT EXISTS (SELECT * FROM @tmpFileGroups WHERE FileGroupName = SelectedFileGroups.FileGroupName) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following file groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following file groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) @@ -4921,9 +5081,10 @@ BEGIN IF @CurrentFileGroupExists IS NULL SET @CurrentFileGroupExists = 0 END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + ' The file group ' + QUOTENAME(@CurrentFileGroupName) + ' in the database ' + QUOTENAME(@CurrentDatabaseName) + ' is locked. It could not be checked if the filegroup exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + ' The file group ' + QUOTENAME(@CurrentFileGroupName) + ' in the database ' + QUOTENAME(@CurrentDatabaseName) + ' is locked. It could not be checked if the filegroup exists.' ELSE '' END SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -5048,9 +5209,10 @@ BEGIN AND NOT EXISTS (SELECT * FROM @tmpObjects WHERE SchemaName = SelectedObjects.SchemaName AND ObjectName = SelectedObjects.ObjectName) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following objects do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following objects do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) @@ -5082,9 +5244,10 @@ BEGIN IF @CurrentObjectExists IS NULL SET @CurrentObjectExists = 0 END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + 'The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the object exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ', ' + 'The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the object exists.' ELSE '' END SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -5156,9 +5319,10 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END -- Update that the database is completed @@ -5280,7 +5444,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-11 21:26:19 //-- + --// Version: 2019-01-12 12:45:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5480,9 +5644,13 @@ BEGIN DECLARE @Error int DECLARE @ReturnCode int + DECLARE @EmptyLine nvarchar(max) + SET @Error = 0 SET @ReturnCode = 0 + SET @EmptyLine = CHAR(9) + SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) IF @Version >= 14 @@ -5564,74 +5732,85 @@ BEGIN SET @StartMessage = 'Version: ' + @VersionTimestamp RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Source: https://ola.hallengren.com' + CHAR(13) + CHAR(10) + ' ' + SET @StartMessage = 'Source: https://ola.hallengren.com' RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @@TRANCOUNT <> 0 BEGIN - SET @ErrorMessage = 'The transaction count is not 0.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The transaction count is not 0.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 @@ -5761,9 +5940,10 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -5857,23 +6037,26 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -6001,241 +6184,275 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationLow is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FragmentationLow is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationMedium is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FragmentationMedium is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'High' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationHigh is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FragmentationHigh is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 >= @FragmentationLevel2 OR @FragmentationLevel1 IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationLevel1 is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FragmentationLevel1 is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 <= @FragmentationLevel1 OR @FragmentationLevel2 IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationLevel2 is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FragmentationLevel2 is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @MinNumberOfPages is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MinNumberOfPages is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MaxNumberOfPages < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxNumberOfPages is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MaxNumberOfPages is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @SortInTempdb is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @SortInTempdb is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @FillFactor is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @FillFactor is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @PadIndex NOT IN('Y','N') BEGIN - SET @ErrorMessage = 'The value for the parameter @PadIndex is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @PadIndex is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LOBCompaction is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LOBCompaction is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN - SET @ErrorMessage = 'The value for the parameter @UpdateStatistics is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @UpdateStatistics is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @OnlyModifiedStatistics is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @OnlyModifiedStatistics is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @StatisticsModificationLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @StatisticsModificationLevel is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @StatisticsSample is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @StatisticsSample is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL OR (@StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @StatisticsResample is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @StatisticsResample is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @PartitionLevel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @PartitionLevel is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @MSShippedObjects is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @MSShippedObjects is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) OR (@Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes)) BEGIN - SET @ErrorMessage = 'The value for the parameter @Indexes is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Indexes is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @TimeLimit < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Delay < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @Delay is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Delay is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @WaitAtLowPriorityMaxDuration < 0 OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @WaitAtLowPriorityAbortAfterWait IS NULL) OR (@WaitAtLowPriorityMaxDuration IS NULL AND @WaitAtLowPriorityAbortAfterWait IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL OR (@Resumable = 'Y' AND NOT (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8))) BEGIN - SET @ErrorMessage = 'The value for the parameter @Resumable is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Resumable is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Resumable and @SortInTempdb.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'You can only specify one of the parameters @Resumable and @SortInTempdb.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LockTimeout < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LockMessageSeverity NOT IN(10,16) BEGIN - SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Error <> 0 BEGIN - SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = @Error GOTO Logging END @@ -6251,9 +6468,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -6263,9 +6481,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -6275,9 +6494,10 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -6288,9 +6508,10 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END ---------------------------------------------------------------------------------------------------- @@ -6454,8 +6675,9 @@ BEGIN BEGIN ROLLBACK TRANSACTION END - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() GOTO Logging END CATCH @@ -6784,9 +7006,10 @@ BEGIN AND NOT EXISTS (SELECT * FROM @tmpIndexesStatistics WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END SET @ErrorMessage = '' @@ -6799,9 +7022,10 @@ BEGIN AND NOT EXISTS (SELECT * FROM @tmpIndexesStatistics WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName AND IndexName = SelectedIndexes.IndexName) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) @@ -6867,9 +7091,10 @@ BEGIN END END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the index exists.' ELSE '' END SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -6900,9 +7125,10 @@ BEGIN END END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the statistics exists.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. It could not be checked if the statistics exists.' ELSE '' END SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -6942,9 +7168,10 @@ BEGIN IF @CurrentModificationCounter IS NULL SET @CurrentModificationCounter = 0 END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The rows and modification_counter could not be checked.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The statistics ' + QUOTENAME(@CurrentStatisticsName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The rows and modification_counter could not be checked.' ELSE '' END SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -6971,9 +7198,10 @@ BEGIN EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamDatabaseID int, @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseID = @CurrentDatabaseID, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The page_count and avg_fragmentation_in_percent could not be checked.' ELSE '' END + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The page_count and avg_fragmentation_in_percent could not be checked.' ELSE '' END SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205,1222) THEN @LockMessageSeverity ELSE 16 END RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) BEGIN @@ -7425,8 +7653,9 @@ BEGIN IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + CHAR(13) + CHAR(10) + ' ' + SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @Error = @@ERROR END From 09378fe79230d894d8c83fcbd131e5837392d97d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 13 Jan 2019 13:54:23 +0100 Subject: [PATCH 095/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 10 +++++++++- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 18 +++++++++++++----- 5 files changed, 25 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index dd4bce35..f36a66b2 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-12 12:45:42 //-- + --// Version: 2019-01-13 13:51:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 74815bb7..9a17ca64 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-12 12:45:42 //-- + --// Version: 2019-01-13 13:51:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -826,6 +826,14 @@ BEGIN SET @DirectoryCheck = 0 END + IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) + BEGIN + SET @ErrorMessage = 'Mirrored backup to disk is only available in Enterprise and Developer Edition.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + IF @DirectoryCheck = 1 BEGIN WHILE (1 = 1) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index cd314b48..0e842215 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-12 12:45:42 //-- + --// Version: 2019-01-13 13:51:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 6180dc33..6e97e926 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-12 12:45:42 //-- + --// Version: 2019-01-13 13:51:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 8fa9535b..70b8e7bc 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-01-12 12:45:42 +Version: 2019-01-13 13:51:41 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-12 12:45:42 //-- + --// Version: 2019-01-13 13:51:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -425,7 +425,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-12 12:45:42 //-- + --// Version: 2019-01-13 13:51:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1178,6 +1178,14 @@ BEGIN SET @DirectoryCheck = 0 END + IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) + BEGIN + SET @ErrorMessage = 'Mirrored backup to disk is only available in Enterprise and Developer Edition.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + IF @DirectoryCheck = 1 BEGIN WHILE (1 = 1) @@ -3668,7 +3676,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-12 12:45:42 //-- + --// Version: 2019-01-13 13:51:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5444,7 +5452,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-12 12:45:42 //-- + --// Version: 2019-01-13 13:51:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 4aa2d988ff2c79ec8d9930b76dfcbb0f05ff7fa7 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 10 Feb 2019 10:45:51 +0100 Subject: [PATCH 096/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 4 +--- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 +++++------- 5 files changed, 9 insertions(+), 13 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index f36a66b2..4a0f13d7 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-13 13:51:41 //-- + --// Version: 2019-02-10 10:40:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 9a17ca64..9525ead8 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-13 13:51:41 //-- + --// Version: 2019-02-10 10:40:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2960,8 +2960,6 @@ BEGIN IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ' -O "READ_WRITE_FILEGROUPS"' - SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI=TRUE"' - SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_USE_DD=TRUE"' IF @DataDomainBoostHost IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_HOST=' + REPLACE(@DataDomainBoostHost,'''','''''') + '"' IF @DataDomainBoostUser IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_USER=' + REPLACE(@DataDomainBoostUser,'''','''''') + '"' IF @DataDomainBoostDevicePath IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DEVICE_PATH=' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '"' diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 0e842215..ad6cd31f 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-13 13:51:41 //-- + --// Version: 2019-02-10 10:40:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 6e97e926..f354fc18 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-13 13:51:41 //-- + --// Version: 2019-02-10 10:40:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 70b8e7bc..03dd3805 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-01-13 13:51:41 +Version: 2019-02-10 10:40:47 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-13 13:51:41 //-- + --// Version: 2019-02-10 10:40:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -425,7 +425,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-13 13:51:41 //-- + --// Version: 2019-02-10 10:40:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3312,8 +3312,6 @@ BEGIN IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ' -O "READ_WRITE_FILEGROUPS"' - SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI=TRUE"' - SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_USE_DD=TRUE"' IF @DataDomainBoostHost IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_HOST=' + REPLACE(@DataDomainBoostHost,'''','''''') + '"' IF @DataDomainBoostUser IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_USER=' + REPLACE(@DataDomainBoostUser,'''','''''') + '"' IF @DataDomainBoostDevicePath IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DEVICE_PATH=' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '"' @@ -3676,7 +3674,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-13 13:51:41 //-- + --// Version: 2019-02-10 10:40:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5452,7 +5450,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-01-13 13:51:41 //-- + --// Version: 2019-02-10 10:40:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 9ed3b94ccf01fbe350e91156ac76f33b2e17d0bf Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 28 Apr 2019 16:53:49 +0200 Subject: [PATCH 097/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 21 ++++++------ DatabaseIntegrityCheck.sql | 21 ++++++------ IndexOptimize.sql | 19 +++++------ MaintenanceSolution.sql | 65 ++++++++++++++++++++------------------ 5 files changed, 67 insertions(+), 61 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 4a0f13d7..c5d877d0 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-02-10 10:40:47 //-- + --// Version: 2019-04-28 16:40:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 9525ead8..737c39bc 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-02-10 10:40:47 //-- + --// Version: 2019-04-28 16:40:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -510,9 +510,11 @@ BEGIN FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) - SELECT availability_databases_cluster.database_name, availability_groups.name - FROM sys.availability_databases_cluster availability_databases_cluster - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id + SELECT databases.name, + availability_groups.name + FROM sys.databases databases + INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id END INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) @@ -1893,9 +1895,8 @@ BEGIN @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) FROM sys.databases databases - INNER JOIN sys.availability_databases_cluster availability_databases_cluster ON databases.group_database_id = availability_databases_cluster.group_database_id - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON availability_groups.group_id = dm_hadr_availability_replica_states.group_id AND databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id WHERE databases.name = @CurrentDatabaseName END @@ -2026,13 +2027,13 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN - SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole + SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Availability group backup preference: ' + @CurrentAvailabilityGroupBackupPreference + SET @DatabaseMessage = 'Availability group backup preference: ' + ISNULL(@CurrentAvailabilityGroupBackupPreference,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Is preferred backup replica: ' + CASE WHEN @CurrentIsPreferredBackupReplica = 1 THEN 'Yes' WHEN @CurrentIsPreferredBackupReplica = 0 THEN 'No' ELSE 'N/A' END diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index ad6cd31f..1400fc27 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-02-10 10:40:47 //-- + --// Version: 2019-04-28 16:40:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -404,9 +404,11 @@ BEGIN FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) - SELECT availability_databases_cluster.database_name, availability_groups.name - FROM sys.availability_databases_cluster availability_databases_cluster - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id + SELECT databases.name, + availability_groups.name + FROM sys.databases databases + INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id END INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], [Order], Selected, Completed) @@ -1253,9 +1255,8 @@ BEGIN @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) FROM sys.databases databases - INNER JOIN sys.availability_databases_cluster availability_databases_cluster ON databases.group_database_id = availability_databases_cluster.group_database_id - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON availability_groups.group_id = dm_hadr_availability_replica_states.group_id AND databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id WHERE databases.name = @CurrentDatabaseName END @@ -1304,15 +1305,15 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN - SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole + SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' BEGIN - SET @DatabaseMessage = 'Availability group backup preference: ' + @CurrentAvailabilityGroupBackupPreference + SET @DatabaseMessage = 'Availability group backup preference: ' + ISNULL(@CurrentAvailabilityGroupBackupPreference,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Is preferred backup replica: ' + CASE WHEN @CurrentIsPreferredBackupReplica = 1 THEN 'Yes' WHEN @CurrentIsPreferredBackupReplica = 0 THEN 'No' ELSE 'N/A' END diff --git a/IndexOptimize.sql b/IndexOptimize.sql index f354fc18..b955e1ac 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-02-10 10:40:47 //-- + --// Version: 2019-04-28 16:40:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,9 +493,11 @@ BEGIN FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) - SELECT availability_databases_cluster.database_name, availability_groups.name - FROM sys.availability_databases_cluster availability_databases_cluster - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id + SELECT databases.name, + availability_groups.name + FROM sys.databases databases + INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id END INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) @@ -1365,9 +1367,8 @@ BEGIN SELECT @CurrentAvailabilityGroup = availability_groups.name, @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc FROM sys.databases databases - INNER JOIN sys.availability_databases_cluster availability_databases_cluster ON databases.group_database_id = availability_databases_cluster.group_database_id - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON availability_groups.group_id = dm_hadr_availability_replica_states.group_id AND databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id WHERE databases.name = @CurrentDatabaseName END @@ -1411,10 +1412,10 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN - SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole + SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 03dd3805..e90c7743 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-02-10 10:40:47 +Version: 2019-04-28 16:40:00 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-02-10 10:40:47 //-- + --// Version: 2019-04-28 16:40:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -425,7 +425,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-02-10 10:40:47 //-- + --// Version: 2019-04-28 16:40:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -862,9 +862,11 @@ BEGIN FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) - SELECT availability_databases_cluster.database_name, availability_groups.name - FROM sys.availability_databases_cluster availability_databases_cluster - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id + SELECT databases.name, + availability_groups.name + FROM sys.databases databases + INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id END INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) @@ -2245,9 +2247,8 @@ BEGIN @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) FROM sys.databases databases - INNER JOIN sys.availability_databases_cluster availability_databases_cluster ON databases.group_database_id = availability_databases_cluster.group_database_id - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON availability_groups.group_id = dm_hadr_availability_replica_states.group_id AND databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id WHERE databases.name = @CurrentDatabaseName END @@ -2378,13 +2379,13 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN - SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole + SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Availability group backup preference: ' + @CurrentAvailabilityGroupBackupPreference + SET @DatabaseMessage = 'Availability group backup preference: ' + ISNULL(@CurrentAvailabilityGroupBackupPreference,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Is preferred backup replica: ' + CASE WHEN @CurrentIsPreferredBackupReplica = 1 THEN 'Yes' WHEN @CurrentIsPreferredBackupReplica = 0 THEN 'No' ELSE 'N/A' END @@ -3674,7 +3675,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-02-10 10:40:47 //-- + --// Version: 2019-04-28 16:40:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4041,9 +4042,11 @@ BEGIN FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) - SELECT availability_databases_cluster.database_name, availability_groups.name - FROM sys.availability_databases_cluster availability_databases_cluster - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id + SELECT databases.name, + availability_groups.name + FROM sys.databases databases + INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id END INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], [Order], Selected, Completed) @@ -4890,9 +4893,8 @@ BEGIN @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) FROM sys.databases databases - INNER JOIN sys.availability_databases_cluster availability_databases_cluster ON databases.group_database_id = availability_databases_cluster.group_database_id - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON availability_groups.group_id = dm_hadr_availability_replica_states.group_id AND databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id WHERE databases.name = @CurrentDatabaseName END @@ -4941,15 +4943,15 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN - SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole + SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' BEGIN - SET @DatabaseMessage = 'Availability group backup preference: ' + @CurrentAvailabilityGroupBackupPreference + SET @DatabaseMessage = 'Availability group backup preference: ' + ISNULL(@CurrentAvailabilityGroupBackupPreference,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Is preferred backup replica: ' + CASE WHEN @CurrentIsPreferredBackupReplica = 1 THEN 'Yes' WHEN @CurrentIsPreferredBackupReplica = 0 THEN 'No' ELSE 'N/A' END @@ -5450,7 +5452,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-02-10 10:40:47 //-- + --// Version: 2019-04-28 16:40:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5892,9 +5894,11 @@ BEGIN FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) - SELECT availability_databases_cluster.database_name, availability_groups.name - FROM sys.availability_databases_cluster availability_databases_cluster - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id + SELECT databases.name, + availability_groups.name + FROM sys.databases databases + INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id END INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) @@ -6764,9 +6768,8 @@ BEGIN SELECT @CurrentAvailabilityGroup = availability_groups.name, @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc FROM sys.databases databases - INNER JOIN sys.availability_databases_cluster availability_databases_cluster ON databases.group_database_id = availability_databases_cluster.group_database_id - INNER JOIN sys.availability_groups availability_groups ON availability_databases_cluster.group_id = availability_groups.group_id - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON availability_groups.group_id = dm_hadr_availability_replica_states.group_id AND databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id + INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id WHERE databases.name = @CurrentDatabaseName END @@ -6810,10 +6813,10 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN - SET @DatabaseMessage = 'Availability group: ' + @CurrentAvailabilityGroup + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Availability group role: ' + @CurrentAvailabilityGroupRole + SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END From b286009a31a8676e0ed5483f2a663e7d01860811 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 May 2019 22:13:17 +0200 Subject: [PATCH 098/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 13 +++++++------ DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 21 +++++++++++---------- 5 files changed, 21 insertions(+), 19 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index c5d877d0..a7cd4d47 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-04-28 16:40:00 //-- + --// Version: 2019-05-22 22:03:10 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 737c39bc..33eddbad 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-04-28 16:40:00 //-- + --// Version: 2019-05-22 22:03:10 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1482,8 +1482,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1491,8 +1491,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1925,7 +1925,7 @@ BEGIN WHERE database_id = @CurrentDatabaseID END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND @ChangeBackupType = 'Y' AND @ModificationLevel IS NOT NULL BEGIN SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_file_space_usage' @@ -2447,6 +2447,7 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',@NumberOfFiles) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),3))) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 1400fc27..e0adfe50 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-04-28 16:40:00 //-- + --// Version: 2019-05-22 22:03:10 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index b955e1ac..e6f723cf 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-04-28 16:40:00 //-- + --// Version: 2019-05-22 22:03:10 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index e90c7743..5646e7c3 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-04-28 16:40:00 +Version: 2019-05-22 22:03:10 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-04-28 16:40:00 //-- + --// Version: 2019-05-22 22:03:10 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -425,7 +425,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-04-28 16:40:00 //-- + --// Version: 2019-05-22 22:03:10 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1834,8 +1834,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1843,8 +1843,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -2277,7 +2277,7 @@ BEGIN WHERE database_id = @CurrentDatabaseID END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND @ChangeBackupType = 'Y' AND @ModificationLevel IS NOT NULL BEGIN SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_file_space_usage' @@ -2799,6 +2799,7 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',@NumberOfFiles) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),3))) @@ -3675,7 +3676,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-04-28 16:40:00 //-- + --// Version: 2019-05-22 22:03:10 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5452,7 +5453,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-04-28 16:40:00 //-- + --// Version: 2019-05-22 22:03:10 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 2b6c2acccd479a0c7320811209ddaa8fbeeca5a8 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 May 2019 22:35:55 +0200 Subject: [PATCH 099/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 3 ++- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 11 ++++++----- 5 files changed, 11 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index a7cd4d47..f2b49253 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:03:10 //-- + --// Version: 2019-05-22 22:32:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 33eddbad..3263f2d3 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:03:10 //-- + --// Version: 2019-05-22 22:32:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2337,6 +2337,7 @@ BEGIN IF @@SERVICENAME IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}','') IF @Description IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}','') IF @NumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileNumber}','') + IF @NumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}','') WHILE (@Updated = 1 OR @Updated IS NULL) BEGIN diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index e0adfe50..a86429bc 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:03:10 //-- + --// Version: 2019-05-22 22:32:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index e6f723cf..3591e295 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:03:10 //-- + --// Version: 2019-05-22 22:32:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 5646e7c3..3e02fb8e 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-05-22 22:03:10 +Version: 2019-05-22 22:32:33 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:03:10 //-- + --// Version: 2019-05-22 22:32:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -425,7 +425,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:03:10 //-- + --// Version: 2019-05-22 22:32:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2689,6 +2689,7 @@ BEGIN IF @@SERVICENAME IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}','') IF @Description IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}','') IF @NumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileNumber}','') + IF @NumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}','') WHILE (@Updated = 1 OR @Updated IS NULL) BEGIN @@ -3676,7 +3677,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:03:10 //-- + --// Version: 2019-05-22 22:32:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5453,7 +5454,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:03:10 //-- + --// Version: 2019-05-22 22:32:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 9b5e3cca90064f3b8cd0236b4b187159eaede110 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 7 Jun 2019 23:19:32 +0200 Subject: [PATCH 100/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 6 ++++-- DatabaseIntegrityCheck.sql | 6 ++++-- IndexOptimize.sql | 6 ++++-- MaintenanceSolution.sql | 30 ++++++++++++++++++------------ 5 files changed, 31 insertions(+), 19 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index f2b49253..aa768b1f 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:32:33 //-- + --// Version: 2019-06-07 22:53:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 3263f2d3..9cea2a22 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:32:33 //-- + --// Version: 2019-06-07 22:53:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2075,7 +2075,7 @@ BEGIN IF @CurrentBackupType = 'LOG' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) BEGIN - SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),@CurrentLastLogBackup,120),'N/A') + SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),NULLIF(@CurrentLastLogBackup,'1900-01-01'),120),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Log size since last log backup (MB): ' + ISNULL(CAST(@CurrentLogSizeSinceLastLogBackup AS nvarchar),'N/A') @@ -3277,6 +3277,8 @@ BEGIN SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + IF @ReturnCode <> 0 BEGIN RETURN @ReturnCode diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index a86429bc..c443cab3 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:32:33 //-- + --// Version: 2019-06-07 22:53:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1327,7 +1327,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - RAISERROR('',10,1) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) @@ -1751,6 +1751,8 @@ BEGIN SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + IF @ReturnCode <> 0 BEGIN RETURN @ReturnCode diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 3591e295..045c1fb6 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:32:33 //-- + --// Version: 2019-06-07 22:53:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1425,7 +1425,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - RAISERROR('',10,1) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) @@ -2308,6 +2308,8 @@ BEGIN SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + IF @ReturnCode <> 0 BEGIN RETURN @ReturnCode diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 3e02fb8e..703904a8 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-05-22 22:32:33 +Version: 2019-06-07 22:53:29 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:32:33 //-- + --// Version: 2019-06-07 22:53:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -425,7 +425,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:32:33 //-- + --// Version: 2019-06-07 22:53:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2427,7 +2427,7 @@ BEGIN IF @CurrentBackupType = 'LOG' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) BEGIN - SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),@CurrentLastLogBackup,120),'N/A') + SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),NULLIF(@CurrentLastLogBackup,'1900-01-01'),120),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Log size since last log backup (MB): ' + ISNULL(CAST(@CurrentLogSizeSinceLastLogBackup AS nvarchar),'N/A') @@ -3629,6 +3629,8 @@ BEGIN SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + IF @ReturnCode <> 0 BEGIN RETURN @ReturnCode @@ -3677,7 +3679,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:32:33 //-- + --// Version: 2019-06-07 22:53:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4967,7 +4969,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - RAISERROR('',10,1) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) @@ -5391,6 +5393,8 @@ BEGIN SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + IF @ReturnCode <> 0 BEGIN RETURN @ReturnCode @@ -5454,7 +5458,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-05-22 22:32:33 //-- + --// Version: 2019-06-07 22:53:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6828,7 +6832,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - RAISERROR('',10,1) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) @@ -7711,6 +7715,8 @@ BEGIN SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + IF @ReturnCode <> 0 BEGIN RETURN @ReturnCode @@ -7796,16 +7802,16 @@ BEGIN SET @TokenServer = '$' + '(ESCAPE_SQUOTE(SRVR))' SET @TokenJobID = '$' + '(ESCAPE_SQUOTE(JOBID))' SET @TokenStepID = '$' + '(ESCAPE_SQUOTE(STEPID))' - SET @TokenDate = '$' + '(ESCAPE_SQUOTE(STRTDT))' - SET @TokenTime = '$' + '(ESCAPE_SQUOTE(STRTTM))' + SET @TokenDate = '$' + '(ESCAPE_SQUOTE(DATE))' + SET @TokenTime = '$' + '(ESCAPE_SQUOTE(TIME))' END ELSE BEGIN SET @TokenServer = '$' + '(SRVR)' SET @TokenJobID = '$' + '(JOBID)' SET @TokenStepID = '$' + '(STEPID)' - SET @TokenDate = '$' + '(STRTDT)' - SET @TokenTime = '$' + '(STRTTM)' + SET @TokenDate = '$' + '(DATE)' + SET @TokenTime = '$' + '(TIME)' END IF @Version >= 13 From 8a0d49d9ac217ec74aa1b7bb9310df0f5233f59c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 9 Jun 2019 13:31:43 +0200 Subject: [PATCH 101/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 82 ++++++++++------- DatabaseIntegrityCheck.sql | 49 ++++++---- IndexOptimize.sql | 49 ++++++---- MaintenanceSolution.sql | 184 +++++++++++++++++++++++-------------- 5 files changed, 231 insertions(+), 135 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index aa768b1f..b66cfa76 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-07 22:53:29 //-- + --// Version: 2019-06-09 13:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 9cea2a22..42b967c8 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-07 22:53:29 //-- + --// Version: 2019-06-09 13:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -107,8 +107,17 @@ BEGIN DECLARE @CurrentRootDirectoryPath nvarchar(4000) DECLARE @CurrentDBID int - DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) + + DECLARE @CurrentDatabaseID int + DECLARE @CurrentUserAccess nvarchar(max) + DECLARE @CurrentIsReadOnly bit + DECLARE @CurrentDatabaseState nvarchar(max) + DECLARE @CurrentInStandby bit + DECLARE @CurrentRecoveryModel nvarchar(max) + + DECLARE @CurrentIsEncrypted bit + DECLARE @CurrentBackupType nvarchar(max) DECLARE @CurrentFileExtension nvarchar(max) DECLARE @CurrentFileNumber int @@ -133,8 +142,7 @@ BEGIN DECLARE @CurrentIsPreferredBackupReplica bit DECLARE @CurrentDatabaseMirroringRole nvarchar(max) DECLARE @CurrentLogShippingRole nvarchar(max) - DECLARE @CurrentIsEncrypted bit - DECLARE @CurrentIsReadOnly bit + DECLARE @CurrentBackupSetID int DECLARE @CurrentIsMirror bit DECLARE @CurrentLastLogBackup datetime @@ -1875,9 +1883,23 @@ BEGIN BREAK END - SET @CurrentDatabaseID = DB_ID(@CurrentDatabaseName) + SELECT @CurrentDatabaseID = database_id, + @CurrentUserAccess = user_access_desc, + @CurrentIsReadOnly = is_read_only, + @CurrentDatabaseState = state_desc, + @CurrentInStandby = is_in_standby, + @CurrentRecoveryModel = recovery_model_desc + FROM sys.databases + WHERE [name] = @CurrentDatabaseName + + IF @Version >= 10 + BEGIN + SET @CurrentCommand06 = 'SELECT @ParamIsEncrypted = is_encrypted FROM sys.databases WHERE name = @ParamDatabaseName' + + EXECUTE sp_executesql @statement = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT + END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' + IF @CurrentDatabaseState = 'ONLINE' BEGIN IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = @CurrentDatabaseID AND database_guid IS NOT NULL) BEGIN @@ -1918,14 +1940,14 @@ BEGIN SET @CurrentDifferentialBaseLSN = NULL END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' + IF @CurrentDatabaseState = 'ONLINE' BEGIN SELECT @CurrentLogLSN = last_log_backup_lsn FROM sys.database_recovery_status WHERE database_id = @CurrentDatabaseID END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND @ChangeBackupType = 'Y' AND @ModificationLevel IS NOT NULL + IF @CurrentDatabaseState = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND @ChangeBackupType = 'Y' AND @ModificationLevel IS NOT NULL BEGIN SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_file_space_usage' @@ -1936,7 +1958,7 @@ BEGIN IF @ChangeBackupType = 'Y' BEGIN - IF @CurrentBackupType = 'LOG' AND DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') <> 'SIMPLE' AND @CurrentLogLSN IS NULL AND @CurrentDatabaseName <> 'master' + IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND @CurrentDatabaseName <> 'master' BEGIN SET @CurrentBackupType = 'DIFF' END @@ -1946,7 +1968,7 @@ BEGIN END END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) + IF @CurrentDatabaseState = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) BEGIN SELECT @CurrentLastLogBackup = log_backup_time, @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb @@ -1984,33 +2006,22 @@ BEGIN SET @CurrentLogShippingRole = 'SECONDARY' END - SELECT @CurrentIsReadOnly = is_read_only - FROM sys.databases - WHERE name = @CurrentDatabaseName - - IF @Version >= 10 - BEGIN - SET @CurrentCommand06 = 'SELECT @ParamIsEncrypted = is_encrypted FROM sys.databases WHERE name = @ParamDatabaseName' - - EXECUTE sp_executesql @statement = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT - END - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentIsDatabaseAccessible IS NOT NULL @@ -2019,7 +2030,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Encrypted: ' + CASE WHEN @CurrentIsEncrypted = 1 THEN 'Yes' WHEN @CurrentIsEncrypted = 0 THEN 'No' ELSE 'N/A' END @@ -2084,10 +2095,11 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' + IF @CurrentDatabaseState = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) - AND DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 0 - AND NOT (@CurrentBackupType = 'LOG' AND (DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') = 'SIMPLE' OR @CurrentLogLSN IS NULL)) + AND NOT (@CurrentInStandby = 1) + AND NOT (@CurrentBackupType = 'LOG' AND @CurrentRecoveryModel = 'SIMPLE') + AND NOT (@CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL) AND NOT (@CurrentBackupType = 'DIFF' AND @CurrentDifferentialBaseLSN IS NULL) AND NOT (@CurrentBackupType IN('DIFF','LOG') AND @CurrentDatabaseName = 'master') AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupType = 'FULL' AND @CopyOnly = 'N' AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) @@ -3197,7 +3209,7 @@ BEGIN END END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' + IF @CurrentDatabaseState = 'SUSPECT' BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -3224,8 +3236,16 @@ BEGIN -- Clear variables SET @CurrentDBID = NULL - SET @CurrentDatabaseID = NULL SET @CurrentDatabaseName = NULL + + SET @CurrentDatabaseID = NULL + SET @CurrentUserAccess = NULL + SET @CurrentIsReadOnly = NULL + SET @CurrentDatabaseState = NULL + SET @CurrentInStandby = NULL + SET @CurrentRecoveryModel = NULL + SET @CurrentIsEncrypted = NULL + SET @CurrentBackupType = NULL SET @CurrentFileExtension = NULL SET @CurrentFileNumber = NULL @@ -3246,8 +3266,6 @@ BEGIN SET @CurrentIsPreferredBackupReplica = NULL SET @CurrentDatabaseMirroringRole = NULL SET @CurrentLogShippingRole = NULL - SET @CurrentIsEncrypted = NULL - SET @CurrentIsReadOnly = NULL SET @CurrentLastLogBackup = NULL SET @CurrentLogSizeSinceLastLogBackup = NULL SET @CurrentAllocatedExtentPageCount = NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index c443cab3..725baa1c 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-07 22:53:29 //-- + --// Version: 2019-06-09 13:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -62,15 +62,21 @@ BEGIN DECLARE @QueueStartTime datetime DECLARE @CurrentDBID int - DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) + + DECLARE @CurrentDatabaseID int + DECLARE @CurrentUserAccess nvarchar(max) + DECLARE @CurrentIsReadOnly bit + DECLARE @CurrentDatabaseState nvarchar(max) + DECLARE @CurrentInStandby bit + DECLARE @CurrentRecoveryModel nvarchar(max) + DECLARE @CurrentIsDatabaseAccessible bit DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) DECLARE @CurrentIsPreferredBackupReplica bit DECLARE @CurrentDatabaseMirroringRole nvarchar(max) - DECLARE @CurrentIsReadOnly bit DECLARE @CurrentFGID int DECLARE @CurrentFileGroupID int @@ -1235,9 +1241,16 @@ BEGIN BREAK END - SET @CurrentDatabaseID = DB_ID(@CurrentDatabaseName) + SELECT @CurrentDatabaseID = database_id, + @CurrentUserAccess = user_access_desc, + @CurrentIsReadOnly = is_read_only, + @CurrentDatabaseState = state_desc, + @CurrentInStandby = is_in_standby, + @CurrentRecoveryModel = recovery_model_desc + FROM sys.databases + WHERE [name] = @CurrentDatabaseName - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 + IF @CurrentDatabaseState = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 BEGIN IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = @CurrentDatabaseID AND database_guid IS NOT NULL) BEGIN @@ -1272,26 +1285,22 @@ BEGIN WHERE database_id = @CurrentDatabaseID END - SELECT @CurrentIsReadOnly = is_read_only - FROM sys.databases - WHERE name = @CurrentDatabaseName - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentIsDatabaseAccessible IS NOT NULL @@ -1300,7 +1309,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentAvailabilityGroup IS NOT NULL @@ -1329,7 +1338,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' + IF @CurrentDatabaseState = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR SERVERPROPERTY('EngineEdition') = 3) AND ((@AvailabilityGroupReplicas = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY') OR (@AvailabilityGroupReplicas = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY') OR (@AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' AND @CurrentIsPreferredBackupReplica = 1) OR @AvailabilityGroupReplicas = 'ALL' OR @CurrentAvailabilityGroupRole IS NULL) @@ -1687,7 +1696,7 @@ BEGIN END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' + IF @CurrentDatabaseState = 'SUSPECT' BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1714,15 +1723,21 @@ BEGIN -- Clear variables SET @CurrentDBID = NULL - SET @CurrentDatabaseID = NULL SET @CurrentDatabaseName = NULL + + SET @CurrentDatabaseID = NULL + SET @CurrentUserAccess = NULL + SET @CurrentIsReadOnly = NULL + SET @CurrentDatabaseState = NULL + SET @CurrentInStandby = NULL + SET @CurrentRecoveryModel = NULL + SET @CurrentIsDatabaseAccessible = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL SET @CurrentIsPreferredBackupReplica = NULL SET @CurrentDatabaseMirroringRole = NULL - SET @CurrentIsReadOnly = NULL SET @CurrentCommand01 = NULL SET @CurrentCommand02 = NULL diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 045c1fb6..ac608cdc 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-07 22:53:29 //-- + --// Version: 2019-06-09 13:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -82,13 +82,19 @@ BEGIN DECLARE @QueueStartTime datetime DECLARE @CurrentDBID int - DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) + + DECLARE @CurrentDatabaseID int + DECLARE @CurrentUserAccess nvarchar(max) + DECLARE @CurrentIsReadOnly bit + DECLARE @CurrentDatabaseState nvarchar(max) + DECLARE @CurrentInStandby bit + DECLARE @CurrentRecoveryModel nvarchar(max) + DECLARE @CurrentIsDatabaseAccessible bit DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentDatabaseMirroringRole nvarchar(max) - DECLARE @CurrentIsReadOnly bit DECLARE @CurrentCommand01 nvarchar(max) DECLARE @CurrentCommand02 nvarchar(max) @@ -1348,9 +1354,16 @@ BEGIN BREAK END - SET @CurrentDatabaseID = DB_ID(@CurrentDatabaseName) + SELECT @CurrentDatabaseID = database_id, + @CurrentUserAccess = user_access_desc, + @CurrentIsReadOnly = is_read_only, + @CurrentDatabaseState = state_desc, + @CurrentInStandby = is_in_standby, + @CurrentRecoveryModel = recovery_model_desc + FROM sys.databases + WHERE [name] = @CurrentDatabaseName - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 + IF @CurrentDatabaseState = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 BEGIN IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = @CurrentDatabaseID AND database_guid IS NOT NULL) BEGIN @@ -1379,26 +1392,22 @@ BEGIN WHERE database_id = @CurrentDatabaseID END - SELECT @CurrentIsReadOnly = is_read_only - FROM sys.databases - WHERE name = @CurrentDatabaseName - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentIsDatabaseAccessible IS NOT NULL @@ -1407,7 +1416,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentAvailabilityGroup IS NOT NULL @@ -1427,7 +1436,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' + IF @CurrentDatabaseState = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) AND DATABASEPROPERTYEX(@CurrentDatabaseName,'Updateability') = 'READ_WRITE' BEGIN @@ -2259,7 +2268,7 @@ BEGIN END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' + IF @CurrentDatabaseState = 'SUSPECT' BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -2286,13 +2295,19 @@ BEGIN -- Clear variables SET @CurrentDBID = NULL - SET @CurrentDatabaseID = NULL SET @CurrentDatabaseName = NULL + + SET @CurrentDatabaseID = NULL + SET @CurrentUserAccess = NULL + SET @CurrentIsReadOnly = NULL + SET @CurrentDatabaseState = NULL + SET @CurrentInStandby = NULL + SET @CurrentRecoveryModel = NULL + SET @CurrentIsDatabaseAccessible = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL SET @CurrentDatabaseMirroringRole = NULL - SET @CurrentIsReadOnly = NULL SET @CurrentCommand01 = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 703904a8..c5e965c4 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-06-07 22:53:29 +Version: 2019-06-09 13:18:25 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-07 22:53:29 //-- + --// Version: 2019-06-09 13:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -425,7 +425,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-07 22:53:29 //-- + --// Version: 2019-06-09 13:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -459,8 +459,17 @@ BEGIN DECLARE @CurrentRootDirectoryPath nvarchar(4000) DECLARE @CurrentDBID int - DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) + + DECLARE @CurrentDatabaseID int + DECLARE @CurrentUserAccess nvarchar(max) + DECLARE @CurrentIsReadOnly bit + DECLARE @CurrentDatabaseState nvarchar(max) + DECLARE @CurrentInStandby bit + DECLARE @CurrentRecoveryModel nvarchar(max) + + DECLARE @CurrentIsEncrypted bit + DECLARE @CurrentBackupType nvarchar(max) DECLARE @CurrentFileExtension nvarchar(max) DECLARE @CurrentFileNumber int @@ -485,8 +494,7 @@ BEGIN DECLARE @CurrentIsPreferredBackupReplica bit DECLARE @CurrentDatabaseMirroringRole nvarchar(max) DECLARE @CurrentLogShippingRole nvarchar(max) - DECLARE @CurrentIsEncrypted bit - DECLARE @CurrentIsReadOnly bit + DECLARE @CurrentBackupSetID int DECLARE @CurrentIsMirror bit DECLARE @CurrentLastLogBackup datetime @@ -2227,9 +2235,23 @@ BEGIN BREAK END - SET @CurrentDatabaseID = DB_ID(@CurrentDatabaseName) + SELECT @CurrentDatabaseID = database_id, + @CurrentUserAccess = user_access_desc, + @CurrentIsReadOnly = is_read_only, + @CurrentDatabaseState = state_desc, + @CurrentInStandby = is_in_standby, + @CurrentRecoveryModel = recovery_model_desc + FROM sys.databases + WHERE [name] = @CurrentDatabaseName - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' + IF @Version >= 10 + BEGIN + SET @CurrentCommand06 = 'SELECT @ParamIsEncrypted = is_encrypted FROM sys.databases WHERE name = @ParamDatabaseName' + + EXECUTE sp_executesql @statement = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT + END + + IF @CurrentDatabaseState = 'ONLINE' BEGIN IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = @CurrentDatabaseID AND database_guid IS NOT NULL) BEGIN @@ -2270,14 +2292,14 @@ BEGIN SET @CurrentDifferentialBaseLSN = NULL END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' + IF @CurrentDatabaseState = 'ONLINE' BEGIN SELECT @CurrentLogLSN = last_log_backup_lsn FROM sys.database_recovery_status WHERE database_id = @CurrentDatabaseID END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND @ChangeBackupType = 'Y' AND @ModificationLevel IS NOT NULL + IF @CurrentDatabaseState = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND @ChangeBackupType = 'Y' AND @ModificationLevel IS NOT NULL BEGIN SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_file_space_usage' @@ -2288,7 +2310,7 @@ BEGIN IF @ChangeBackupType = 'Y' BEGIN - IF @CurrentBackupType = 'LOG' AND DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') <> 'SIMPLE' AND @CurrentLogLSN IS NULL AND @CurrentDatabaseName <> 'master' + IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND @CurrentDatabaseName <> 'master' BEGIN SET @CurrentBackupType = 'DIFF' END @@ -2298,7 +2320,7 @@ BEGIN END END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) + IF @CurrentDatabaseState = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) BEGIN SELECT @CurrentLastLogBackup = log_backup_time, @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb @@ -2336,33 +2358,22 @@ BEGIN SET @CurrentLogShippingRole = 'SECONDARY' END - SELECT @CurrentIsReadOnly = is_read_only - FROM sys.databases - WHERE name = @CurrentDatabaseName - - IF @Version >= 10 - BEGIN - SET @CurrentCommand06 = 'SELECT @ParamIsEncrypted = is_encrypted FROM sys.databases WHERE name = @ParamDatabaseName' - - EXECUTE sp_executesql @statement = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT - END - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentIsDatabaseAccessible IS NOT NULL @@ -2371,7 +2382,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Encrypted: ' + CASE WHEN @CurrentIsEncrypted = 1 THEN 'Yes' WHEN @CurrentIsEncrypted = 0 THEN 'No' ELSE 'N/A' END @@ -2436,10 +2447,11 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' + IF @CurrentDatabaseState = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) - AND DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 0 - AND NOT (@CurrentBackupType = 'LOG' AND (DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') = 'SIMPLE' OR @CurrentLogLSN IS NULL)) + AND NOT (@CurrentInStandby = 1) + AND NOT (@CurrentBackupType = 'LOG' AND @CurrentRecoveryModel = 'SIMPLE') + AND NOT (@CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL) AND NOT (@CurrentBackupType = 'DIFF' AND @CurrentDifferentialBaseLSN IS NULL) AND NOT (@CurrentBackupType IN('DIFF','LOG') AND @CurrentDatabaseName = 'master') AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupType = 'FULL' AND @CopyOnly = 'N' AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) @@ -3549,7 +3561,7 @@ BEGIN END END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' + IF @CurrentDatabaseState = 'SUSPECT' BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -3576,8 +3588,16 @@ BEGIN -- Clear variables SET @CurrentDBID = NULL - SET @CurrentDatabaseID = NULL SET @CurrentDatabaseName = NULL + + SET @CurrentDatabaseID = NULL + SET @CurrentUserAccess = NULL + SET @CurrentIsReadOnly = NULL + SET @CurrentDatabaseState = NULL + SET @CurrentInStandby = NULL + SET @CurrentRecoveryModel = NULL + SET @CurrentIsEncrypted = NULL + SET @CurrentBackupType = NULL SET @CurrentFileExtension = NULL SET @CurrentFileNumber = NULL @@ -3598,8 +3618,6 @@ BEGIN SET @CurrentIsPreferredBackupReplica = NULL SET @CurrentDatabaseMirroringRole = NULL SET @CurrentLogShippingRole = NULL - SET @CurrentIsEncrypted = NULL - SET @CurrentIsReadOnly = NULL SET @CurrentLastLogBackup = NULL SET @CurrentLogSizeSinceLastLogBackup = NULL SET @CurrentAllocatedExtentPageCount = NULL @@ -3679,7 +3697,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-07 22:53:29 //-- + --// Version: 2019-06-09 13:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3704,15 +3722,21 @@ BEGIN DECLARE @QueueStartTime datetime DECLARE @CurrentDBID int - DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) + + DECLARE @CurrentDatabaseID int + DECLARE @CurrentUserAccess nvarchar(max) + DECLARE @CurrentIsReadOnly bit + DECLARE @CurrentDatabaseState nvarchar(max) + DECLARE @CurrentInStandby bit + DECLARE @CurrentRecoveryModel nvarchar(max) + DECLARE @CurrentIsDatabaseAccessible bit DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) DECLARE @CurrentIsPreferredBackupReplica bit DECLARE @CurrentDatabaseMirroringRole nvarchar(max) - DECLARE @CurrentIsReadOnly bit DECLARE @CurrentFGID int DECLARE @CurrentFileGroupID int @@ -4877,9 +4901,16 @@ BEGIN BREAK END - SET @CurrentDatabaseID = DB_ID(@CurrentDatabaseName) + SELECT @CurrentDatabaseID = database_id, + @CurrentUserAccess = user_access_desc, + @CurrentIsReadOnly = is_read_only, + @CurrentDatabaseState = state_desc, + @CurrentInStandby = is_in_standby, + @CurrentRecoveryModel = recovery_model_desc + FROM sys.databases + WHERE [name] = @CurrentDatabaseName - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 + IF @CurrentDatabaseState = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 BEGIN IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = @CurrentDatabaseID AND database_guid IS NOT NULL) BEGIN @@ -4914,26 +4945,22 @@ BEGIN WHERE database_id = @CurrentDatabaseID END - SELECT @CurrentIsReadOnly = is_read_only - FROM sys.databases - WHERE name = @CurrentDatabaseName - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentIsDatabaseAccessible IS NOT NULL @@ -4942,7 +4969,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentAvailabilityGroup IS NOT NULL @@ -4971,7 +4998,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' + IF @CurrentDatabaseState = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR SERVERPROPERTY('EngineEdition') = 3) AND ((@AvailabilityGroupReplicas = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY') OR (@AvailabilityGroupReplicas = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY') OR (@AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' AND @CurrentIsPreferredBackupReplica = 1) OR @AvailabilityGroupReplicas = 'ALL' OR @CurrentAvailabilityGroupRole IS NULL) @@ -5329,7 +5356,7 @@ BEGIN END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' + IF @CurrentDatabaseState = 'SUSPECT' BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -5356,15 +5383,21 @@ BEGIN -- Clear variables SET @CurrentDBID = NULL - SET @CurrentDatabaseID = NULL SET @CurrentDatabaseName = NULL + + SET @CurrentDatabaseID = NULL + SET @CurrentUserAccess = NULL + SET @CurrentIsReadOnly = NULL + SET @CurrentDatabaseState = NULL + SET @CurrentInStandby = NULL + SET @CurrentRecoveryModel = NULL + SET @CurrentIsDatabaseAccessible = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL SET @CurrentIsPreferredBackupReplica = NULL SET @CurrentDatabaseMirroringRole = NULL - SET @CurrentIsReadOnly = NULL SET @CurrentCommand01 = NULL SET @CurrentCommand02 = NULL @@ -5458,7 +5491,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-07 22:53:29 //-- + --// Version: 2019-06-09 13:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5489,13 +5522,19 @@ BEGIN DECLARE @QueueStartTime datetime DECLARE @CurrentDBID int - DECLARE @CurrentDatabaseID int DECLARE @CurrentDatabaseName nvarchar(max) + + DECLARE @CurrentDatabaseID int + DECLARE @CurrentUserAccess nvarchar(max) + DECLARE @CurrentIsReadOnly bit + DECLARE @CurrentDatabaseState nvarchar(max) + DECLARE @CurrentInStandby bit + DECLARE @CurrentRecoveryModel nvarchar(max) + DECLARE @CurrentIsDatabaseAccessible bit DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentDatabaseMirroringRole nvarchar(max) - DECLARE @CurrentIsReadOnly bit DECLARE @CurrentCommand01 nvarchar(max) DECLARE @CurrentCommand02 nvarchar(max) @@ -6755,9 +6794,16 @@ BEGIN BREAK END - SET @CurrentDatabaseID = DB_ID(@CurrentDatabaseName) + SELECT @CurrentDatabaseID = database_id, + @CurrentUserAccess = user_access_desc, + @CurrentIsReadOnly = is_read_only, + @CurrentDatabaseState = state_desc, + @CurrentInStandby = is_in_standby, + @CurrentRecoveryModel = recovery_model_desc + FROM sys.databases + WHERE [name] = @CurrentDatabaseName - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 + IF @CurrentDatabaseState = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 BEGIN IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = @CurrentDatabaseID AND database_guid IS NOT NULL) BEGIN @@ -6786,26 +6832,22 @@ BEGIN WHERE database_id = @CurrentDatabaseID END - SELECT @CurrentIsReadOnly = is_read_only - FROM sys.databases - WHERE name = @CurrentDatabaseName - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Status: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') AS nvarchar) + SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Standby: ' + CASE WHEN DATABASEPROPERTYEX(@CurrentDatabaseName,'IsInStandBy') = 1 THEN 'Yes' ELSE 'No' END + SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'User access: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'UserAccess') AS nvarchar) + SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentIsDatabaseAccessible IS NOT NULL @@ -6814,7 +6856,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Recovery model: ' + CAST(DATABASEPROPERTYEX(@CurrentDatabaseName,'Recovery') AS nvarchar) + SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentAvailabilityGroup IS NOT NULL @@ -6834,7 +6876,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'ONLINE' + IF @CurrentDatabaseState = 'ONLINE' AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) AND DATABASEPROPERTYEX(@CurrentDatabaseName,'Updateability') = 'READ_WRITE' BEGIN @@ -7666,7 +7708,7 @@ BEGIN END - IF DATABASEPROPERTYEX(@CurrentDatabaseName,'Status') = 'SUSPECT' + IF @CurrentDatabaseState = 'SUSPECT' BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -7693,13 +7735,19 @@ BEGIN -- Clear variables SET @CurrentDBID = NULL - SET @CurrentDatabaseID = NULL SET @CurrentDatabaseName = NULL + + SET @CurrentDatabaseID = NULL + SET @CurrentUserAccess = NULL + SET @CurrentIsReadOnly = NULL + SET @CurrentDatabaseState = NULL + SET @CurrentInStandby = NULL + SET @CurrentRecoveryModel = NULL + SET @CurrentIsDatabaseAccessible = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL SET @CurrentDatabaseMirroringRole = NULL - SET @CurrentIsReadOnly = NULL SET @CurrentCommand01 = NULL From 0736b110d4b2a1d6bd85d596f8aa619572819691 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 10 Jun 2019 22:00:39 +0200 Subject: [PATCH 102/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 8 ++++---- DatabaseIntegrityCheck.sql | 6 +++--- IndexOptimize.sql | 6 +++--- MaintenanceSolution.sql | 24 ++++++++++++------------ 5 files changed, 23 insertions(+), 23 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index b66cfa76..544d8934 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-09 13:18:25 //-- + --// Version: 2019-06-10 20:59:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 42b967c8..8a7a0a5a 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-09 13:18:25 //-- + --// Version: 2019-06-10 20:59:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -528,7 +528,7 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')) AS DatabaseNameFS, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + CASE WHEN name IN('master','msdb','model') OR is_distributor = 1 THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, 0 AS [Order], 0 AS Selected, @@ -2096,7 +2096,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF @CurrentDatabaseState = 'ONLINE' - AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) + AND NOT (@CurrentUserAccess = 'SINGLE_USER' AND @CurrentIsDatabaseAccessible = 0) AND NOT (@CurrentInStandby = 1) AND NOT (@CurrentBackupType = 'LOG' AND @CurrentRecoveryModel = 'SIMPLE') AND NOT (@CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL) @@ -2115,7 +2115,7 @@ BEGIN IF @CurrentBackupType = 'LOG' AND (@CleanupTime IS NOT NULL OR @MirrorCleanupTime IS NOT NULL) BEGIN - SELECT @CurrentLatestBackup = MAX(backup_finish_date) + SELECT @CurrentLatestBackup = MAX(backup_start_date) FROM msdb.dbo.backupset WHERE ([type] IN('D','I') OR database_backup_lsn < @CurrentDifferentialBaseLSN) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 725baa1c..ea5325cf 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-09 13:18:25 //-- + --// Version: 2019-06-10 20:59:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -419,7 +419,7 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], [Order], Selected, Completed) SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + CASE WHEN name IN('master','msdb','model') OR is_distributor = 1 THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], 0 AS [Order], @@ -1339,7 +1339,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF @CurrentDatabaseState = 'ONLINE' - AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) + AND NOT (@CurrentUserAccess = 'SINGLE_USER' AND @CurrentIsDatabaseAccessible = 0) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR SERVERPROPERTY('EngineEdition') = 3) AND ((@AvailabilityGroupReplicas = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY') OR (@AvailabilityGroupReplicas = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY') OR (@AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' AND @CurrentIsPreferredBackupReplica = 1) OR @AvailabilityGroupReplicas = 'ALL' OR @CurrentAvailabilityGroupRole IS NULL) AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') diff --git a/IndexOptimize.sql b/IndexOptimize.sql index ac608cdc..3ee99d84 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-09 13:18:25 //-- + --// Version: 2019-06-10 20:59:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -508,7 +508,7 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + CASE WHEN name IN('master','msdb','model') OR is_distributor = 1 THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, 0 AS [Order], 0 AS Selected, @@ -1437,7 +1437,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF @CurrentDatabaseState = 'ONLINE' - AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) + AND NOT (@CurrentUserAccess = 'SINGLE_USER' AND @CurrentIsDatabaseAccessible = 0) AND DATABASEPROPERTYEX(@CurrentDatabaseName,'Updateability') = 'READ_WRITE' BEGIN diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index c5e965c4..0d57ff9e 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-06-09 13:18:25 +Version: 2019-06-10 20:59:49 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-09 13:18:25 //-- + --// Version: 2019-06-10 20:59:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -425,7 +425,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-09 13:18:25 //-- + --// Version: 2019-06-10 20:59:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -880,7 +880,7 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')) AS DatabaseNameFS, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + CASE WHEN name IN('master','msdb','model') OR is_distributor = 1 THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, 0 AS [Order], 0 AS Selected, @@ -2448,7 +2448,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF @CurrentDatabaseState = 'ONLINE' - AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) + AND NOT (@CurrentUserAccess = 'SINGLE_USER' AND @CurrentIsDatabaseAccessible = 0) AND NOT (@CurrentInStandby = 1) AND NOT (@CurrentBackupType = 'LOG' AND @CurrentRecoveryModel = 'SIMPLE') AND NOT (@CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL) @@ -2467,7 +2467,7 @@ BEGIN IF @CurrentBackupType = 'LOG' AND (@CleanupTime IS NOT NULL OR @MirrorCleanupTime IS NOT NULL) BEGIN - SELECT @CurrentLatestBackup = MAX(backup_finish_date) + SELECT @CurrentLatestBackup = MAX(backup_start_date) FROM msdb.dbo.backupset WHERE ([type] IN('D','I') OR database_backup_lsn < @CurrentDifferentialBaseLSN) @@ -3697,7 +3697,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-09 13:18:25 //-- + --// Version: 2019-06-10 20:59:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4079,7 +4079,7 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], [Order], Selected, Completed) SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + CASE WHEN name IN('master','msdb','model') OR is_distributor = 1 THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot], 0 AS [Order], @@ -4999,7 +4999,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF @CurrentDatabaseState = 'ONLINE' - AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) + AND NOT (@CurrentUserAccess = 'SINGLE_USER' AND @CurrentIsDatabaseAccessible = 0) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR SERVERPROPERTY('EngineEdition') = 3) AND ((@AvailabilityGroupReplicas = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY') OR (@AvailabilityGroupReplicas = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY') OR (@AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' AND @CurrentIsPreferredBackupReplica = 1) OR @AvailabilityGroupReplicas = 'ALL' OR @CurrentAvailabilityGroupRole IS NULL) AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') @@ -5491,7 +5491,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-09 13:18:25 //-- + --// Version: 2019-06-10 20:59:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5948,7 +5948,7 @@ BEGIN INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) SELECT [name] AS DatabaseName, - CASE WHEN name IN('master','msdb','model') THEN 'S' ELSE 'U' END AS DatabaseType, + CASE WHEN name IN('master','msdb','model') OR is_distributor = 1 THEN 'S' ELSE 'U' END AS DatabaseType, NULL AS AvailabilityGroup, 0 AS [Order], 0 AS Selected, @@ -6877,7 +6877,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT IF @CurrentDatabaseState = 'ONLINE' - AND (@CurrentIsDatabaseAccessible = 1 OR @CurrentIsDatabaseAccessible IS NULL) + AND NOT (@CurrentUserAccess = 'SINGLE_USER' AND @CurrentIsDatabaseAccessible = 0) AND DATABASEPROPERTYEX(@CurrentDatabaseName,'Updateability') = 'READ_WRITE' BEGIN From baee68f5c59e2c7e4aad1682b66e88d9796519eb Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 14 Jun 2019 00:21:42 +0200 Subject: [PATCH 103/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 55 +++++++++++++++++++++++++++++---- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 63 ++++++++++++++++++++++++++++++++------ 5 files changed, 105 insertions(+), 19 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 544d8934..aeb9f52d 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-10 20:59:49 //-- + --// Version: 2019-06-14 00:05:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 8a7a0a5a..de51eba6 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-10 20:59:49 //-- + --// Version: 2019-06-14 00:05:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -818,7 +818,15 @@ BEGIN SET @DirectoryCheck = 1 - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux') OR (DirectoryPath = 'NUL' AND @HostPlatform = 'Windows')) + OR DirectoryPath IS NULL + OR LEFT(DirectoryPath,1) = ' ' + OR RIGHT(DirectoryPath,1) = ' ')) + OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) + OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) + OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath <> 'NUL')) + OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) BEGIN SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -827,7 +835,17 @@ BEGIN SET @DirectoryCheck = 0 END - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) + OR DirectoryPath IS NULL + OR LEFT(DirectoryPath,1) = ' ' + OR RIGHT(DirectoryPath,1) = ' ')) + OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) + OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) + OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) + OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) + OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) + OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -852,6 +870,7 @@ BEGIN @CurrentRootDirectoryPath = DirectoryPath FROM @Directories WHERE Completed = 0 + AND DirectoryPath <> 'NUL' ORDER BY ID ASC IF @@ROWCOUNT = 0 @@ -1072,6 +1091,14 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END + IF @Verify = 'Y' AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') + BEGIN + SET @ErrorMessage = 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + IF @CleanupTime < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported.' @@ -1096,6 +1123,14 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END + IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') + BEGIN + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' @@ -2319,7 +2354,7 @@ BEGIN INSERT INTO @CurrentDirectories (ID, DirectoryPath, Mirror, DirectoryNumber, CreateCompleted, CleanupCompleted) SELECT ROW_NUMBER() OVER (ORDER BY ID), - DirectoryPath + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END, + DirectoryPath + CASE WHEN DirectoryPath = 'NUL' THEN '' WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END, Mirror, ROW_NUMBER() OVER (PARTITION BY Mirror ORDER BY ID ASC), 0, @@ -2497,7 +2532,14 @@ BEGIN SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName + IF @CurrentDirectoryPath = 'NUL' + BEGIN + SET @CurrentFilePath = 'NUL' + END + ELSE + BEGIN + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName + END INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) SELECT 'DISK', @CurrentFilePath, 0 @@ -2604,6 +2646,7 @@ BEGIN -- Create directory IF @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + AND NOT EXISTS(SELECT * FROM @CurrentDirectories WHERE DirectoryPath = 'NUL') BEGIN WHILE (1 = 1) BEGIN @@ -2746,7 +2789,7 @@ BEGIN END -- Perform a backup - IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateOutput <> 0 OR CreateOutput IS NULL) OR @HostPlatform = 'Linux' + IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE DirectoryPath <> 'NUL' AND (CreateOutput <> 0 OR CreateOutput IS NULL)) OR @HostPlatform = 'Linux' BEGIN IF @BackupSoftware IS NULL BEGIN diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index ea5325cf..f3a3ac5a 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-10 20:59:49 //-- + --// Version: 2019-06-14 00:05:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 3ee99d84..12966236 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-10 20:59:49 //-- + --// Version: 2019-06-14 00:05:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 0d57ff9e..b144c525 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-06-10 20:59:49 +Version: 2019-06-14 00:05:34 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-10 20:59:49 //-- + --// Version: 2019-06-14 00:05:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -425,7 +425,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-10 20:59:49 //-- + --// Version: 2019-06-14 00:05:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1170,7 +1170,15 @@ BEGIN SET @DirectoryCheck = 1 - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux') OR (DirectoryPath = 'NUL' AND @HostPlatform = 'Windows')) + OR DirectoryPath IS NULL + OR LEFT(DirectoryPath,1) = ' ' + OR RIGHT(DirectoryPath,1) = ' ')) + OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) + OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) + OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath <> 'NUL')) + OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) BEGIN SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1179,7 +1187,17 @@ BEGIN SET @DirectoryCheck = 0 END - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) + OR DirectoryPath IS NULL + OR LEFT(DirectoryPath,1) = ' ' + OR RIGHT(DirectoryPath,1) = ' ')) + OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) + OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) + OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) + OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) + OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) + OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) BEGIN SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1204,6 +1222,7 @@ BEGIN @CurrentRootDirectoryPath = DirectoryPath FROM @Directories WHERE Completed = 0 + AND DirectoryPath <> 'NUL' ORDER BY ID ASC IF @@ROWCOUNT = 0 @@ -1424,6 +1443,14 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END + IF @Verify = 'Y' AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') + BEGIN + SET @ErrorMessage = 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + IF @CleanupTime < 0 BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported.' @@ -1448,6 +1475,14 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END + IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') + BEGIN + SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' @@ -2671,7 +2706,7 @@ BEGIN INSERT INTO @CurrentDirectories (ID, DirectoryPath, Mirror, DirectoryNumber, CreateCompleted, CleanupCompleted) SELECT ROW_NUMBER() OVER (ORDER BY ID), - DirectoryPath + CASE WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END, + DirectoryPath + CASE WHEN DirectoryPath = 'NUL' THEN '' WHEN @CurrentDirectoryStructure IS NOT NULL THEN @DirectorySeparator + @CurrentDirectoryStructure ELSE '' END, Mirror, ROW_NUMBER() OVER (PARTITION BY Mirror ORDER BY ID ASC), 0, @@ -2849,7 +2884,14 @@ BEGIN SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) - SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName + IF @CurrentDirectoryPath = 'NUL' + BEGIN + SET @CurrentFilePath = 'NUL' + END + ELSE + BEGIN + SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName + END INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) SELECT 'DISK', @CurrentFilePath, 0 @@ -2956,6 +2998,7 @@ BEGIN -- Create directory IF @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + AND NOT EXISTS(SELECT * FROM @CurrentDirectories WHERE DirectoryPath = 'NUL') BEGIN WHILE (1 = 1) BEGIN @@ -3098,7 +3141,7 @@ BEGIN END -- Perform a backup - IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateOutput <> 0 OR CreateOutput IS NULL) OR @HostPlatform = 'Linux' + IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE DirectoryPath <> 'NUL' AND (CreateOutput <> 0 OR CreateOutput IS NULL)) OR @HostPlatform = 'Linux' BEGIN IF @BackupSoftware IS NULL BEGIN @@ -3697,7 +3740,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-10 20:59:49 //-- + --// Version: 2019-06-14 00:05:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5491,7 +5534,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-10 20:59:49 //-- + --// Version: 2019-06-14 00:05:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 20bdfbef60da8b08eb62734099367fd35402a6ca Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 1 Dec 2019 21:27:41 +0100 Subject: [PATCH 104/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b3f2dbbe..e353a3e3 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ You can also download the objects as separate scripts: Note that you always need CommandExecute; DatabaseBackup, DatabaseIntegrityCheck, and IndexOptimize are using it. You need CommandLog if you are going to use the option to log commands to a table. -Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, Azure SQL Database, and Azure SQL Database Managed Instance +Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, SQL Server 2019, Azure SQL Database, and Azure SQL Database Managed Instance ## Documentation From 8518c6e4fa011c23a9d85f1e4e06a2cdf4ea9b02 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 1 Dec 2019 21:38:07 +0100 Subject: [PATCH 105/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 ++++++------ 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index aeb9f52d..ff8c864c 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-14 00:05:34 //-- + --// Version: 2019-12-01 21:32:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index de51eba6..2b098f3c 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,7 +73,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-14 00:05:34 //-- + --// Version: 2019-12-01 21:32:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index f3a3ac5a..90a0641e 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-14 00:05:34 //-- + --// Version: 2019-12-01 21:32:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 12966236..285020a1 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-14 00:05:34 //-- + --// Version: 2019-12-01 21:32:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index b144c525..86e5cdd0 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -1,6 +1,6 @@ /* -SQL Server Maintenance Solution - SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, and SQL Server 2017 +SQL Server Maintenance Solution - SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, and SQL Server 2019 Backup: https://ola.hallengren.com/sql-server-backup.html Integrity Check: https://ola.hallengren.com/sql-server-integrity-check.html @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-06-14 00:05:34 +Version: 2019-12-01 21:32:32 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-14 00:05:34 //-- + --// Version: 2019-12-01 21:32:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -425,7 +425,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-14 00:05:34 //-- + --// Version: 2019-12-01 21:32:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3740,7 +3740,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-14 00:05:34 //-- + --// Version: 2019-12-01 21:32:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5534,7 +5534,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-06-14 00:05:34 //-- + --// Version: 2019-12-01 21:32:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 301e1e13cb53c891383800c919b12f6ac75ae6be Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 26 Dec 2019 16:09:48 +0100 Subject: [PATCH 106/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 15 ++++++++++++++- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 23 ++++++++++++++++++----- 5 files changed, 35 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index ff8c864c..b1b9ac1e 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-01 21:32:32 //-- + --// Version: 2019-12-26 15:59:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 2b098f3c..fed31ea3 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -60,6 +60,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @FileExtensionDiff nvarchar(max) = NULL, @FileExtensionLog nvarchar(max) = NULL, @Init nvarchar(max) = 'N', +@Format nvarchar(max) = 'N', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -73,7 +74,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-01 21:32:32 //-- + --// Version: 2019-12-26 15:59:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -327,6 +328,7 @@ BEGIN SET @Parameters = @Parameters + ', @FileExtensionDiff = ' + ISNULL('''' + REPLACE(@FileExtensionDiff,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -1575,6 +1577,14 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END + IF @Format NOT IN('Y','N') OR @Format IS NULL OR (@Format = 'Y' AND @BackupType = 'LOG') OR (@Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + BEGIN + SET @ErrorMessage = 'The value for the parameter @Format is not supported.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' @@ -2841,6 +2851,7 @@ BEGIN IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', COPY_ONLY' IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 = @CurrentCommand03 + ', NORECOVERY' IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', INIT' + IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', FORMAT' IF @BlockSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar) IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@MaxTransferSize AS nvarchar) @@ -2892,6 +2903,7 @@ BEGIN IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @maxtransfersize = ' + CAST(@MaxTransferSize AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @threads = ' + CAST(@Threads AS nvarchar) IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @init = 1' + IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @format = 1' IF @Throttle IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @throttle = ' + CAST(@Throttle AS nvarchar) IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' @@ -2942,6 +2954,7 @@ BEGIN IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', COPY_ONLY' IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 = @CurrentCommand03 + ', NORECOVERY' IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', INIT' + IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', FORMAT' IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', COMPRESSION = ' + CAST(@CompressionLevel AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', THREADCOUNT = ' + CAST(@Threads AS nvarchar) IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@MaxTransferSize AS nvarchar) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 90a0641e..56de0053 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-01 21:32:32 //-- + --// Version: 2019-12-26 15:59:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 285020a1..68fbda10 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-01 21:32:32 //-- + --// Version: 2019-12-26 15:59:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 86e5cdd0..0c797c72 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-12-01 21:32:32 +Version: 2019-12-26 15:59:04 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-01 21:32:32 //-- + --// Version: 2019-12-26 15:59:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -412,6 +412,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @FileExtensionDiff nvarchar(max) = NULL, @FileExtensionLog nvarchar(max) = NULL, @Init nvarchar(max) = 'N', +@Format nvarchar(max) = 'N', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -425,7 +426,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-01 21:32:32 //-- + --// Version: 2019-12-26 15:59:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -679,6 +680,7 @@ BEGIN SET @Parameters = @Parameters + ', @FileExtensionDiff = ' + ISNULL('''' + REPLACE(@FileExtensionDiff,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -1927,6 +1929,14 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END + IF @Format NOT IN('Y','N') OR @Format IS NULL OR (@Format = 'Y' AND @BackupType = 'LOG') OR (@Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + BEGIN + SET @ErrorMessage = 'The value for the parameter @Format is not supported.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' @@ -3193,6 +3203,7 @@ BEGIN IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', COPY_ONLY' IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 = @CurrentCommand03 + ', NORECOVERY' IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', INIT' + IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', FORMAT' IF @BlockSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar) IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@MaxTransferSize AS nvarchar) @@ -3244,6 +3255,7 @@ BEGIN IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @maxtransfersize = ' + CAST(@MaxTransferSize AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @threads = ' + CAST(@Threads AS nvarchar) IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @init = 1' + IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @format = 1' IF @Throttle IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @throttle = ' + CAST(@Throttle AS nvarchar) IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' @@ -3294,6 +3306,7 @@ BEGIN IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', COPY_ONLY' IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 = @CurrentCommand03 + ', NORECOVERY' IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', INIT' + IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', FORMAT' IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', COMPRESSION = ' + CAST(@CompressionLevel AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', THREADCOUNT = ' + CAST(@Threads AS nvarchar) IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@MaxTransferSize AS nvarchar) @@ -3740,7 +3753,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-01 21:32:32 //-- + --// Version: 2019-12-26 15:59:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5534,7 +5547,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-01 21:32:32 //-- + --// Version: 2019-12-26 15:59:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 342a840da06bcd676b9a3461c2703aa5ce764813 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 26 Dec 2019 20:00:04 +0100 Subject: [PATCH 107/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 4 ++-- DatabaseIntegrityCheck.sql | 4 ++-- IndexOptimize.sql | 4 ++-- MaintenanceSolution.sql | 16 ++++++++-------- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index b1b9ac1e..ebe7916e 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 15:59:04 //-- + --// Version: 2019-12-26 19:56:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index fed31ea3..4fab40a2 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -74,7 +74,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 15:59:04 //-- + --// Version: 2019-12-26 19:56:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1685,7 +1685,7 @@ BEGIN IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') BEGIN UPDATE tmpDatabases - SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) + SET DatabaseSize = (SELECT SUM(CAST(size AS bigint)) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) FROM @tmpDatabases tmpDatabases END diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 56de0053..55e91e66 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 15:59:04 //-- + --// Version: 2019-12-26 19:56:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -965,7 +965,7 @@ BEGIN IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') BEGIN UPDATE tmpDatabases - SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) + SET DatabaseSize = (SELECT SUM(CAST(size AS bigint)) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) FROM @tmpDatabases tmpDatabases END diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 68fbda10..03da8769 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 15:59:04 //-- + --// Version: 2019-12-26 19:56:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1142,7 +1142,7 @@ BEGIN IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') BEGIN UPDATE tmpDatabases - SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) + SET DatabaseSize = (SELECT SUM(CAST(size AS bigint)) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) FROM @tmpDatabases tmpDatabases END diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 0c797c72..27b7f91f 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-12-26 15:59:04 +Version: 2019-12-26 19:56:44 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 15:59:04 //-- + --// Version: 2019-12-26 19:56:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -426,7 +426,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 15:59:04 //-- + --// Version: 2019-12-26 19:56:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2037,7 +2037,7 @@ BEGIN IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') BEGIN UPDATE tmpDatabases - SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) + SET DatabaseSize = (SELECT SUM(CAST(size AS bigint)) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) FROM @tmpDatabases tmpDatabases END @@ -3753,7 +3753,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 15:59:04 //-- + --// Version: 2019-12-26 19:56:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4681,7 +4681,7 @@ BEGIN IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') BEGIN UPDATE tmpDatabases - SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) + SET DatabaseSize = (SELECT SUM(CAST(size AS bigint)) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) FROM @tmpDatabases tmpDatabases END @@ -5547,7 +5547,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 15:59:04 //-- + --// Version: 2019-12-26 19:56:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6638,7 +6638,7 @@ BEGIN IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') BEGIN UPDATE tmpDatabases - SET DatabaseSize = (SELECT SUM(size) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) + SET DatabaseSize = (SELECT SUM(CAST(size AS bigint)) FROM sys.master_files WHERE [type] = 0 AND database_id = DB_ID(tmpDatabases.DatabaseName)) FROM @tmpDatabases tmpDatabases END From fee77b357662ad2708c7daa420622ef350f22034 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 29 Dec 2019 17:50:38 +0100 Subject: [PATCH 108/188] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index e353a3e3..ea148ae2 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ [![issues badge]][issues] [![bug_report badge]][bug_report] [![feature_request badge]][feature_request] +[![feature_request badge]][questions] ## Getting Started From 16f1a8ca280a1d6888faf2d9aeadef896d045273 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 29 Dec 2019 17:50:56 +0100 Subject: [PATCH 109/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ea148ae2..986de118 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![issues badge]][issues] [![bug_report badge]][bug_report] [![feature_request badge]][feature_request] -[![feature_request badge]][questions] +[![feature_request badge]][question] ## Getting Started From 51ff04a7b79ee80afbeaa3638bb73c196c9327a6 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 29 Dec 2019 17:51:51 +0100 Subject: [PATCH 110/188] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 986de118..db10851f 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![issues badge]][issues] [![bug_report badge]][bug_report] [![feature_request badge]][feature_request] -[![feature_request badge]][question] +[![question badge]][question] ## Getting Started @@ -45,3 +45,4 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [issues]:https://github.com/olahallengren/sql-server-maintenance-solution/issues [bug_report]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Abug_report [feature_request]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Afeature_request +[question]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Aquestion From b0b76e6437ca12a80b4d3c08b6c3e2eb181ea9ae Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 29 Dec 2019 17:52:54 +0100 Subject: [PATCH 111/188] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index db10851f..cad33bac 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [issues badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution.svg [bug_report badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/bug_report.svg [feature_request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/feature_request.svg +[question badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/question.svg [licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE [stars]:https://github.com/olahallengren/sql-server-maintenance-solution/stargazers From 2c7944187dce305286cfb042e1baaf4a60438b40 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 29 Dec 2019 23:17:02 +0100 Subject: [PATCH 112/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 42 ++++++++++++++-------- DatabaseIntegrityCheck.sql | 11 +++--- IndexOptimize.sql | 15 ++++---- MaintenanceSolution.sql | 72 +++++++++++++++++++++----------------- 5 files changed, 77 insertions(+), 65 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index ebe7916e..9580ad8c 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 19:56:44 //-- + --// Version: 2019-12-29 23:00:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 4fab40a2..8aac948d 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -61,6 +61,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @FileExtensionLog nvarchar(max) = NULL, @Init nvarchar(max) = 'N', @Format nvarchar(max) = 'N', +@ObjectLevelRecovery nvarchar(max) = 'N', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -74,7 +75,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 19:56:44 //-- + --// Version: 2019-12-29 23:00:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -110,7 +111,6 @@ BEGIN DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) - DECLARE @CurrentDatabaseID int DECLARE @CurrentUserAccess nvarchar(max) DECLARE @CurrentIsReadOnly bit DECLARE @CurrentDatabaseState nvarchar(max) @@ -120,6 +120,7 @@ BEGIN DECLARE @CurrentIsEncrypted bit DECLARE @CurrentBackupType nvarchar(max) + DECLARE @CurrentMaxTransferSize int DECLARE @CurrentFileExtension nvarchar(max) DECLARE @CurrentFileNumber int DECLARE @CurrentDifferentialBaseLSN numeric(25,0) @@ -329,6 +330,7 @@ BEGIN SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ObjectLevelRecovery = ' + ISNULL('''' + REPLACE(@ObjectLevelRecovery,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -1585,6 +1587,14 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END + IF @ObjectLevelRecovery NOT IN('Y','N') OR @ObjectLevelRecovery IS NULL OR (@ObjectLevelRecovery = 'Y' AND @BackupSoftware IS NULL) OR (@ObjectLevelRecovery = 'Y' AND @BackupSoftware <> 'LITESPEED') OR (@ObjectLevelRecovery = 'Y' AND @BackupType = 'LOG') + BEGIN + SET @ErrorMessage = 'The value for the parameter @ObjectLevelRecovery is not supported.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' @@ -1928,8 +1938,7 @@ BEGIN BREAK END - SELECT @CurrentDatabaseID = database_id, - @CurrentUserAccess = user_access_desc, + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @CurrentInStandby = is_in_standby, @@ -1944,9 +1953,11 @@ BEGIN EXECUTE sp_executesql @statement = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT END + SET @CurrentMaxTransferSize = @MaxTransferSize + IF @CurrentDatabaseState = 'ONLINE' BEGIN - IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = @CurrentDatabaseID AND database_guid IS NOT NULL) + IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) AND database_guid IS NOT NULL) BEGIN SET @CurrentIsDatabaseAccessible = 1 END @@ -1974,13 +1985,13 @@ BEGIN SELECT @CurrentDifferentialBaseLSN = differential_base_lsn FROM sys.master_files - WHERE database_id = @CurrentDatabaseID + WHERE database_id = DB_ID(@CurrentDatabaseName) AND [type] = 0 AND [file_id] = 1 -- Workaround for a bug in SQL Server 2005 IF @Version >= 9 AND @Version < 10 - AND EXISTS(SELECT * FROM sys.master_files WHERE database_id = @CurrentDatabaseID AND [type] = 0 AND [file_id] = 1 AND differential_base_lsn IS NOT NULL AND differential_base_guid IS NOT NULL AND differential_base_time IS NULL) + AND EXISTS(SELECT * FROM sys.master_files WHERE database_id = DB_ID(@CurrentDatabaseName) AND [type] = 0 AND [file_id] = 1 AND differential_base_lsn IS NOT NULL AND differential_base_guid IS NOT NULL AND differential_base_time IS NULL) BEGIN SET @CurrentDifferentialBaseLSN = NULL END @@ -1989,7 +2000,7 @@ BEGIN BEGIN SELECT @CurrentLogLSN = last_log_backup_lsn FROM sys.database_recovery_status - WHERE database_id = @CurrentDatabaseID + WHERE database_id = DB_ID(@CurrentDatabaseName) END IF @CurrentDatabaseState = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND @ChangeBackupType = 'Y' AND @ModificationLevel IS NOT NULL @@ -2017,7 +2028,7 @@ BEGIN BEGIN SELECT @CurrentLastLogBackup = log_backup_time, @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb - FROM sys.dm_db_log_stats (@CurrentDatabaseID) + FROM sys.dm_db_log_stats (DB_ID(@CurrentDatabaseName)) END IF @CurrentBackupType = 'DIFF' @@ -2039,7 +2050,7 @@ BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring - WHERE database_id = @CurrentDatabaseID + WHERE database_id = DB_ID(@CurrentDatabaseName) IF EXISTS (SELECT * FROM msdb.dbo.log_shipping_primary_databases WHERE primary_database = @CurrentDatabaseName) BEGIN @@ -2838,7 +2849,7 @@ BEGIN IF @Version >= 10 BEGIN - SET @CurrentCommand03 = @CurrentCommand03 + CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND @Version >= 13 AND @MaxTransferSize > 65536)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END + SET @CurrentCommand03 = @CurrentCommand03 + CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND @Version >= 13 AND @CurrentMaxTransferSize > 65536)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END END IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 = @CurrentCommand03 + ', DIFFERENTIAL' @@ -2854,7 +2865,7 @@ BEGIN IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', FORMAT' IF @BlockSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar) - IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@MaxTransferSize AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' IF @Encrypt = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', ENCRYPTION (ALGORITHM = ' + UPPER(@EncryptionAlgorithm) + ', ' IF @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + 'SERVER CERTIFICATE = ' + QUOTENAME(@ServerCertificate) @@ -2900,12 +2911,13 @@ BEGIN IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) IF @AdaptiveCompression IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @adaptivecompression = ''' + CASE WHEN @AdaptiveCompression = 'SIZE' THEN 'Size' WHEN @AdaptiveCompression = 'SPEED' THEN 'Speed' END + '''' IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @buffercount = ' + CAST(@BufferCount AS nvarchar) - IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @maxtransfersize = ' + CAST(@MaxTransferSize AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @maxtransfersize = ' + CAST(@CurrentMaxTransferSize AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @threads = ' + CAST(@Threads AS nvarchar) IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @init = 1' IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @format = 1' IF @Throttle IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @throttle = ' + CAST(@Throttle AS nvarchar) IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' + IF @ObjectLevelRecovery = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @olrmap = 1' IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @cryptlevel = ' + CASE WHEN @EncryptionAlgorithm = 'RC2_40' THEN '0' @@ -2957,7 +2969,7 @@ BEGIN IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', FORMAT' IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', COMPRESSION = ' + CAST(@CompressionLevel AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', THREADCOUNT = ' + CAST(@Threads AS nvarchar) - IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@MaxTransferSize AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', KEYSIZE = ' + CASE @@ -3294,7 +3306,6 @@ BEGIN SET @CurrentDBID = NULL SET @CurrentDatabaseName = NULL - SET @CurrentDatabaseID = NULL SET @CurrentUserAccess = NULL SET @CurrentIsReadOnly = NULL SET @CurrentDatabaseState = NULL @@ -3303,6 +3314,7 @@ BEGIN SET @CurrentIsEncrypted = NULL SET @CurrentBackupType = NULL + SET @CurrentMaxTransferSize = NULL SET @CurrentFileExtension = NULL SET @CurrentFileNumber = NULL SET @CurrentDifferentialBaseLSN = NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 55e91e66..5a511a29 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 19:56:44 //-- + --// Version: 2019-12-29 23:00:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -64,7 +64,6 @@ BEGIN DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) - DECLARE @CurrentDatabaseID int DECLARE @CurrentUserAccess nvarchar(max) DECLARE @CurrentIsReadOnly bit DECLARE @CurrentDatabaseState nvarchar(max) @@ -1241,8 +1240,7 @@ BEGIN BREAK END - SELECT @CurrentDatabaseID = database_id, - @CurrentUserAccess = user_access_desc, + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @CurrentInStandby = is_in_standby, @@ -1252,7 +1250,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 BEGIN - IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = @CurrentDatabaseID AND database_guid IS NOT NULL) + IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) AND database_guid IS NOT NULL) BEGIN SET @CurrentIsDatabaseAccessible = 1 END @@ -1282,7 +1280,7 @@ BEGIN BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring - WHERE database_id = @CurrentDatabaseID + WHERE database_id = DB_ID(@CurrentDatabaseName) END SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) @@ -1725,7 +1723,6 @@ BEGIN SET @CurrentDBID = NULL SET @CurrentDatabaseName = NULL - SET @CurrentDatabaseID = NULL SET @CurrentUserAccess = NULL SET @CurrentIsReadOnly = NULL SET @CurrentDatabaseState = NULL diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 03da8769..fc5c0a91 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 19:56:44 //-- + --// Version: 2019-12-29 23:00:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -84,7 +84,6 @@ BEGIN DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) - DECLARE @CurrentDatabaseID int DECLARE @CurrentUserAccess nvarchar(max) DECLARE @CurrentIsReadOnly bit DECLARE @CurrentDatabaseState nvarchar(max) @@ -1354,8 +1353,7 @@ BEGIN BREAK END - SELECT @CurrentDatabaseID = database_id, - @CurrentUserAccess = user_access_desc, + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @CurrentInStandby = is_in_standby, @@ -1365,7 +1363,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 BEGIN - IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = @CurrentDatabaseID AND database_guid IS NOT NULL) + IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) AND database_guid IS NOT NULL) BEGIN SET @CurrentIsDatabaseAccessible = 1 END @@ -1389,7 +1387,7 @@ BEGIN BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring - WHERE database_id = @CurrentDatabaseID + WHERE database_id = DB_ID(@CurrentDatabaseName) END SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) @@ -1809,10 +1807,10 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand05 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand05 = @CurrentCommand05 + 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(@ParamDatabaseID, @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + SET @CurrentCommand05 = @CurrentCommand05 + 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' BEGIN TRY - EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamDatabaseID int, @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseID = @CurrentDatabaseID, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT + EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT END TRY BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The page_count and avg_fragmentation_in_percent could not be checked.' ELSE '' END @@ -2297,7 +2295,6 @@ BEGIN SET @CurrentDBID = NULL SET @CurrentDatabaseName = NULL - SET @CurrentDatabaseID = NULL SET @CurrentUserAccess = NULL SET @CurrentIsReadOnly = NULL SET @CurrentDatabaseState = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 27b7f91f..c20ad79f 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-12-26 19:56:44 +Version: 2019-12-29 23:00:46 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 19:56:44 //-- + --// Version: 2019-12-29 23:00:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -413,6 +413,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @FileExtensionLog nvarchar(max) = NULL, @Init nvarchar(max) = 'N', @Format nvarchar(max) = 'N', +@ObjectLevelRecovery nvarchar(max) = 'N', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -426,7 +427,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 19:56:44 //-- + --// Version: 2019-12-29 23:00:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -462,7 +463,6 @@ BEGIN DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) - DECLARE @CurrentDatabaseID int DECLARE @CurrentUserAccess nvarchar(max) DECLARE @CurrentIsReadOnly bit DECLARE @CurrentDatabaseState nvarchar(max) @@ -472,6 +472,7 @@ BEGIN DECLARE @CurrentIsEncrypted bit DECLARE @CurrentBackupType nvarchar(max) + DECLARE @CurrentMaxTransferSize int DECLARE @CurrentFileExtension nvarchar(max) DECLARE @CurrentFileNumber int DECLARE @CurrentDifferentialBaseLSN numeric(25,0) @@ -681,6 +682,7 @@ BEGIN SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ObjectLevelRecovery = ' + ISNULL('''' + REPLACE(@ObjectLevelRecovery,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -1937,6 +1939,14 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END + IF @ObjectLevelRecovery NOT IN('Y','N') OR @ObjectLevelRecovery IS NULL OR (@ObjectLevelRecovery = 'Y' AND @BackupSoftware IS NULL) OR (@ObjectLevelRecovery = 'Y' AND @BackupSoftware <> 'LITESPEED') OR (@ObjectLevelRecovery = 'Y' AND @BackupType = 'LOG') + BEGIN + SET @ErrorMessage = 'The value for the parameter @ObjectLevelRecovery is not supported.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' @@ -2280,8 +2290,7 @@ BEGIN BREAK END - SELECT @CurrentDatabaseID = database_id, - @CurrentUserAccess = user_access_desc, + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @CurrentInStandby = is_in_standby, @@ -2296,9 +2305,11 @@ BEGIN EXECUTE sp_executesql @statement = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT END + SET @CurrentMaxTransferSize = @MaxTransferSize + IF @CurrentDatabaseState = 'ONLINE' BEGIN - IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = @CurrentDatabaseID AND database_guid IS NOT NULL) + IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) AND database_guid IS NOT NULL) BEGIN SET @CurrentIsDatabaseAccessible = 1 END @@ -2326,13 +2337,13 @@ BEGIN SELECT @CurrentDifferentialBaseLSN = differential_base_lsn FROM sys.master_files - WHERE database_id = @CurrentDatabaseID + WHERE database_id = DB_ID(@CurrentDatabaseName) AND [type] = 0 AND [file_id] = 1 -- Workaround for a bug in SQL Server 2005 IF @Version >= 9 AND @Version < 10 - AND EXISTS(SELECT * FROM sys.master_files WHERE database_id = @CurrentDatabaseID AND [type] = 0 AND [file_id] = 1 AND differential_base_lsn IS NOT NULL AND differential_base_guid IS NOT NULL AND differential_base_time IS NULL) + AND EXISTS(SELECT * FROM sys.master_files WHERE database_id = DB_ID(@CurrentDatabaseName) AND [type] = 0 AND [file_id] = 1 AND differential_base_lsn IS NOT NULL AND differential_base_guid IS NOT NULL AND differential_base_time IS NULL) BEGIN SET @CurrentDifferentialBaseLSN = NULL END @@ -2341,7 +2352,7 @@ BEGIN BEGIN SELECT @CurrentLogLSN = last_log_backup_lsn FROM sys.database_recovery_status - WHERE database_id = @CurrentDatabaseID + WHERE database_id = DB_ID(@CurrentDatabaseName) END IF @CurrentDatabaseState = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND @ChangeBackupType = 'Y' AND @ModificationLevel IS NOT NULL @@ -2369,7 +2380,7 @@ BEGIN BEGIN SELECT @CurrentLastLogBackup = log_backup_time, @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb - FROM sys.dm_db_log_stats (@CurrentDatabaseID) + FROM sys.dm_db_log_stats (DB_ID(@CurrentDatabaseName)) END IF @CurrentBackupType = 'DIFF' @@ -2391,7 +2402,7 @@ BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring - WHERE database_id = @CurrentDatabaseID + WHERE database_id = DB_ID(@CurrentDatabaseName) IF EXISTS (SELECT * FROM msdb.dbo.log_shipping_primary_databases WHERE primary_database = @CurrentDatabaseName) BEGIN @@ -3190,7 +3201,7 @@ BEGIN IF @Version >= 10 BEGIN - SET @CurrentCommand03 = @CurrentCommand03 + CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND @Version >= 13 AND @MaxTransferSize > 65536)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END + SET @CurrentCommand03 = @CurrentCommand03 + CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND @Version >= 13 AND @CurrentMaxTransferSize > 65536)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END END IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 = @CurrentCommand03 + ', DIFFERENTIAL' @@ -3206,7 +3217,7 @@ BEGIN IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', FORMAT' IF @BlockSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar) - IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@MaxTransferSize AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' IF @Encrypt = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', ENCRYPTION (ALGORITHM = ' + UPPER(@EncryptionAlgorithm) + ', ' IF @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + 'SERVER CERTIFICATE = ' + QUOTENAME(@ServerCertificate) @@ -3252,12 +3263,13 @@ BEGIN IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) IF @AdaptiveCompression IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @adaptivecompression = ''' + CASE WHEN @AdaptiveCompression = 'SIZE' THEN 'Size' WHEN @AdaptiveCompression = 'SPEED' THEN 'Speed' END + '''' IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @buffercount = ' + CAST(@BufferCount AS nvarchar) - IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @maxtransfersize = ' + CAST(@MaxTransferSize AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @maxtransfersize = ' + CAST(@CurrentMaxTransferSize AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @threads = ' + CAST(@Threads AS nvarchar) IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @init = 1' IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @format = 1' IF @Throttle IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @throttle = ' + CAST(@Throttle AS nvarchar) IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' + IF @ObjectLevelRecovery = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @olrmap = 1' IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @cryptlevel = ' + CASE WHEN @EncryptionAlgorithm = 'RC2_40' THEN '0' @@ -3309,7 +3321,7 @@ BEGIN IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', FORMAT' IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', COMPRESSION = ' + CAST(@CompressionLevel AS nvarchar) IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', THREADCOUNT = ' + CAST(@Threads AS nvarchar) - IF @MaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@MaxTransferSize AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', KEYSIZE = ' + CASE @@ -3646,7 +3658,6 @@ BEGIN SET @CurrentDBID = NULL SET @CurrentDatabaseName = NULL - SET @CurrentDatabaseID = NULL SET @CurrentUserAccess = NULL SET @CurrentIsReadOnly = NULL SET @CurrentDatabaseState = NULL @@ -3655,6 +3666,7 @@ BEGIN SET @CurrentIsEncrypted = NULL SET @CurrentBackupType = NULL + SET @CurrentMaxTransferSize = NULL SET @CurrentFileExtension = NULL SET @CurrentFileNumber = NULL SET @CurrentDifferentialBaseLSN = NULL @@ -3753,7 +3765,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 19:56:44 //-- + --// Version: 2019-12-29 23:00:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3780,7 +3792,6 @@ BEGIN DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) - DECLARE @CurrentDatabaseID int DECLARE @CurrentUserAccess nvarchar(max) DECLARE @CurrentIsReadOnly bit DECLARE @CurrentDatabaseState nvarchar(max) @@ -4957,8 +4968,7 @@ BEGIN BREAK END - SELECT @CurrentDatabaseID = database_id, - @CurrentUserAccess = user_access_desc, + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @CurrentInStandby = is_in_standby, @@ -4968,7 +4978,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 BEGIN - IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = @CurrentDatabaseID AND database_guid IS NOT NULL) + IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) AND database_guid IS NOT NULL) BEGIN SET @CurrentIsDatabaseAccessible = 1 END @@ -4998,7 +5008,7 @@ BEGIN BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring - WHERE database_id = @CurrentDatabaseID + WHERE database_id = DB_ID(@CurrentDatabaseName) END SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) @@ -5441,7 +5451,6 @@ BEGIN SET @CurrentDBID = NULL SET @CurrentDatabaseName = NULL - SET @CurrentDatabaseID = NULL SET @CurrentUserAccess = NULL SET @CurrentIsReadOnly = NULL SET @CurrentDatabaseState = NULL @@ -5547,7 +5556,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-26 19:56:44 //-- + --// Version: 2019-12-29 23:00:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5580,7 +5589,6 @@ BEGIN DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) - DECLARE @CurrentDatabaseID int DECLARE @CurrentUserAccess nvarchar(max) DECLARE @CurrentIsReadOnly bit DECLARE @CurrentDatabaseState nvarchar(max) @@ -6850,8 +6858,7 @@ BEGIN BREAK END - SELECT @CurrentDatabaseID = database_id, - @CurrentUserAccess = user_access_desc, + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @CurrentInStandby = is_in_standby, @@ -6861,7 +6868,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 BEGIN - IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = @CurrentDatabaseID AND database_guid IS NOT NULL) + IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) AND database_guid IS NOT NULL) BEGIN SET @CurrentIsDatabaseAccessible = 1 END @@ -6885,7 +6892,7 @@ BEGIN BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring - WHERE database_id = @CurrentDatabaseID + WHERE database_id = DB_ID(@CurrentDatabaseName) END SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) @@ -7305,10 +7312,10 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand05 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand05 = @CurrentCommand05 + 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(@ParamDatabaseID, @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + SET @CurrentCommand05 = @CurrentCommand05 + 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' BEGIN TRY - EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamDatabaseID int, @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseID = @CurrentDatabaseID, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT + EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT END TRY BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The page_count and avg_fragmentation_in_percent could not be checked.' ELSE '' END @@ -7793,7 +7800,6 @@ BEGIN SET @CurrentDBID = NULL SET @CurrentDatabaseName = NULL - SET @CurrentDatabaseID = NULL SET @CurrentUserAccess = NULL SET @CurrentIsReadOnly = NULL SET @CurrentDatabaseState = NULL From af511c8e34b02d0a45e67e77396c3a919b9d6df8 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 29 Dec 2019 23:34:59 +0100 Subject: [PATCH 113/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 10 +++++----- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 18 +++++++++--------- 5 files changed, 17 insertions(+), 17 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 9580ad8c..5ba9e3eb 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:00:46 //-- + --// Version: 2019-12-29 23:27:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 8aac948d..5d6c776e 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -61,7 +61,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @FileExtensionLog nvarchar(max) = NULL, @Init nvarchar(max) = 'N', @Format nvarchar(max) = 'N', -@ObjectLevelRecovery nvarchar(max) = 'N', +@ObjectLevelRecoveryMap nvarchar(max) = 'N', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -75,7 +75,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:00:46 //-- + --// Version: 2019-12-29 23:27:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -330,7 +330,7 @@ BEGIN SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ObjectLevelRecovery = ' + ISNULL('''' + REPLACE(@ObjectLevelRecovery,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ObjectLevelRecoveryMap = ' + ISNULL('''' + REPLACE(@ObjectLevelRecoveryMap,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -1587,7 +1587,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF @ObjectLevelRecovery NOT IN('Y','N') OR @ObjectLevelRecovery IS NULL OR (@ObjectLevelRecovery = 'Y' AND @BackupSoftware IS NULL) OR (@ObjectLevelRecovery = 'Y' AND @BackupSoftware <> 'LITESPEED') OR (@ObjectLevelRecovery = 'Y' AND @BackupType = 'LOG') + IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL) OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED') OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @ObjectLevelRecovery is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -2917,7 +2917,7 @@ BEGIN IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @format = 1' IF @Throttle IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @throttle = ' + CAST(@Throttle AS nvarchar) IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' - IF @ObjectLevelRecovery = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @olrmap = 1' + IF @ObjectLevelRecoveryMap = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @olrmap = 1' IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @cryptlevel = ' + CASE WHEN @EncryptionAlgorithm = 'RC2_40' THEN '0' diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 5a511a29..405030f4 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:00:46 //-- + --// Version: 2019-12-29 23:27:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index fc5c0a91..1ca2d0cb 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:00:46 //-- + --// Version: 2019-12-29 23:27:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index c20ad79f..c04cb6b1 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-12-29 23:00:46 +Version: 2019-12-29 23:27:44 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:00:46 //-- + --// Version: 2019-12-29 23:27:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -413,7 +413,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @FileExtensionLog nvarchar(max) = NULL, @Init nvarchar(max) = 'N', @Format nvarchar(max) = 'N', -@ObjectLevelRecovery nvarchar(max) = 'N', +@ObjectLevelRecoveryMap nvarchar(max) = 'N', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -427,7 +427,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:00:46 //-- + --// Version: 2019-12-29 23:27:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -682,7 +682,7 @@ BEGIN SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ObjectLevelRecovery = ' + ISNULL('''' + REPLACE(@ObjectLevelRecovery,'''','''''') + '''','NULL') + SET @Parameters = @Parameters + ', @ObjectLevelRecoveryMap = ' + ISNULL('''' + REPLACE(@ObjectLevelRecoveryMap,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -1939,7 +1939,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF @ObjectLevelRecovery NOT IN('Y','N') OR @ObjectLevelRecovery IS NULL OR (@ObjectLevelRecovery = 'Y' AND @BackupSoftware IS NULL) OR (@ObjectLevelRecovery = 'Y' AND @BackupSoftware <> 'LITESPEED') OR (@ObjectLevelRecovery = 'Y' AND @BackupType = 'LOG') + IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL) OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED') OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG') BEGIN SET @ErrorMessage = 'The value for the parameter @ObjectLevelRecovery is not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -3269,7 +3269,7 @@ BEGIN IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @format = 1' IF @Throttle IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @throttle = ' + CAST(@Throttle AS nvarchar) IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' - IF @ObjectLevelRecovery = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @olrmap = 1' + IF @ObjectLevelRecoveryMap = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @olrmap = 1' IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @cryptlevel = ' + CASE WHEN @EncryptionAlgorithm = 'RC2_40' THEN '0' @@ -3765,7 +3765,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:00:46 //-- + --// Version: 2019-12-29 23:27:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5556,7 +5556,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:00:46 //-- + --// Version: 2019-12-29 23:27:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 4ca4bddd0cf92ef215d3bcb2512a7a41f880496d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 30 Dec 2019 17:22:17 +0100 Subject: [PATCH 114/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 7 +++++-- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 15 +++++++++------ 5 files changed, 17 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 5ba9e3eb..1107c67c 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:27:44 //-- + --// Version: 2019-12-30 17:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 5d6c776e..a76178fe 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -75,7 +75,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:27:44 //-- + --// Version: 2019-12-30 17:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1953,7 +1953,10 @@ BEGIN EXECUTE sp_executesql @statement = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT END - SET @CurrentMaxTransferSize = @MaxTransferSize + SELECT @CurrentMaxTransferSize = CASE + WHEN @MaxTransferSize IS NOT NULL THEN @MaxTransferSize + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND @Version >= 13.04446 THEN 65537 + END IF @CurrentDatabaseState = 'ONLINE' BEGIN diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 405030f4..c77f3289 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:27:44 //-- + --// Version: 2019-12-30 17:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 1ca2d0cb..f694c8e2 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:27:44 //-- + --// Version: 2019-12-30 17:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index c04cb6b1..003d9446 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-12-29 23:27:44 +Version: 2019-12-30 17:18:25 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:27:44 //-- + --// Version: 2019-12-30 17:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -427,7 +427,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:27:44 //-- + --// Version: 2019-12-30 17:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2305,7 +2305,10 @@ BEGIN EXECUTE sp_executesql @statement = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT END - SET @CurrentMaxTransferSize = @MaxTransferSize + SELECT @CurrentMaxTransferSize = CASE + WHEN @MaxTransferSize IS NOT NULL THEN @MaxTransferSize + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND @Version >= 13.04446 THEN 65537 + END IF @CurrentDatabaseState = 'ONLINE' BEGIN @@ -3765,7 +3768,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:27:44 //-- + --// Version: 2019-12-30 17:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5556,7 +5559,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-29 23:27:44 //-- + --// Version: 2019-12-30 17:18:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 05d05d093204f6984c0b0f2a44f16b2da855992d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 15:54:13 +0100 Subject: [PATCH 115/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 4 ++-- DatabaseIntegrityCheck.sql | 4 ++-- IndexOptimize.sql | 4 ++-- MaintenanceSolution.sql | 16 ++++++++-------- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 1107c67c..c1e85590 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -34,7 +34,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-30 17:18:25 //-- + --// Version: 2019-12-31 15:48:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index a76178fe..731c5fe0 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -75,7 +75,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-30 17:18:25 //-- + --// Version: 2019-12-31 15:48:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1803,7 +1803,7 @@ BEGIN BEGIN TRANSACTION SELECT @QueueID = QueueID - FROM dbo.[Queue] WITH (UPDLOCK, TABLOCK) + FROM dbo.[Queue] WITH (UPDLOCK, HOLDLOCK) WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName AND [Parameters] = @Parameters diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index c77f3289..c604460b 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-30 17:18:25 //-- + --// Version: 2019-12-31 15:48:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1107,7 +1107,7 @@ BEGIN BEGIN TRANSACTION SELECT @QueueID = QueueID - FROM dbo.[Queue] WITH (UPDLOCK, TABLOCK) + FROM dbo.[Queue] WITH (UPDLOCK, HOLDLOCK) WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName AND [Parameters] = @Parameters diff --git a/IndexOptimize.sql b/IndexOptimize.sql index f694c8e2..0617905d 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-30 17:18:25 //-- + --// Version: 2019-12-31 15:48:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1220,7 +1220,7 @@ BEGIN BEGIN TRANSACTION SELECT @QueueID = QueueID - FROM dbo.[Queue] WITH (UPDLOCK, TABLOCK) + FROM dbo.[Queue] WITH (UPDLOCK, HOLDLOCK) WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName AND [Parameters] = @Parameters diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 003d9446..2ad101d5 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-12-30 17:18:25 +Version: 2019-12-31 15:48:33 You can contact me by e-mail at ola@hallengren.com. @@ -126,7 +126,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-30 17:18:25 //-- + --// Version: 2019-12-31 15:48:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -427,7 +427,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-30 17:18:25 //-- + --// Version: 2019-12-31 15:48:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2155,7 +2155,7 @@ BEGIN BEGIN TRANSACTION SELECT @QueueID = QueueID - FROM dbo.[Queue] WITH (UPDLOCK, TABLOCK) + FROM dbo.[Queue] WITH (UPDLOCK, HOLDLOCK) WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName AND [Parameters] = @Parameters @@ -3768,7 +3768,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-30 17:18:25 //-- + --// Version: 2019-12-31 15:48:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4838,7 +4838,7 @@ BEGIN BEGIN TRANSACTION SELECT @QueueID = QueueID - FROM dbo.[Queue] WITH (UPDLOCK, TABLOCK) + FROM dbo.[Queue] WITH (UPDLOCK, HOLDLOCK) WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName AND [Parameters] = @Parameters @@ -5559,7 +5559,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-30 17:18:25 //-- + --// Version: 2019-12-31 15:48:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6728,7 +6728,7 @@ BEGIN BEGIN TRANSACTION SELECT @QueueID = QueueID - FROM dbo.[Queue] WITH (UPDLOCK, TABLOCK) + FROM dbo.[Queue] WITH (UPDLOCK, HOLDLOCK) WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName AND [Parameters] = @Parameters From 2d8c933e573cd223a7f57fe8c71c6b4c1650fd22 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 15:54:36 +0100 Subject: [PATCH 116/188] Add files via upload From 8b8871eca8c915d936de5bb3376c4054c364b348 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 18:43:15 +0100 Subject: [PATCH 117/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cad33bac..ac5a591e 100644 --- a/README.md +++ b/README.md @@ -46,4 +46,4 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [issues]:https://github.com/olahallengren/sql-server-maintenance-solution/issues [bug_report]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Abug_report [feature_request]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Afeature_request -[question]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Aquestion +[question]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3AQuestion From 326a6a41d820742f1567eed9b3f5483df33bb97d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 18:44:22 +0100 Subject: [PATCH 118/188] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ac5a591e..19607b80 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![issues badge]][issues] [![bug_report badge]][bug_report] [![feature_request badge]][feature_request] -[![question badge]][question] +[![Question badge]][Question] ## Getting Started @@ -46,4 +46,4 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [issues]:https://github.com/olahallengren/sql-server-maintenance-solution/issues [bug_report]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Abug_report [feature_request]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Afeature_request -[question]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3AQuestion +[Question]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3AQuestion From d360367dc01a3fdd2acb5c83c1dca9c94232a92d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 18:47:52 +0100 Subject: [PATCH 119/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 19607b80..bae21938 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![licence badge]][licence] [![stars badge]][stars] [![forks badge]][forks] -[![issues badge]][issues] +[![issues badgee]][issues] [![bug_report badge]][bug_report] [![feature_request badge]][feature_request] [![Question badge]][Question] From a9493624e96cae50f74a49854d95e40e03aa5b4a Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 18:49:16 +0100 Subject: [PATCH 120/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bae21938..19607b80 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ [![licence badge]][licence] [![stars badge]][stars] [![forks badge]][forks] -[![issues badgee]][issues] +[![issues badge]][issues] [![bug_report badge]][bug_report] [![feature_request badge]][feature_request] [![Question badge]][Question] From 82365577a3968f9e630a6fb14179e030823de45e Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 18:49:35 +0100 Subject: [PATCH 121/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 19607b80..01f3a249 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [issues badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution.svg [bug_report badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/bug_report.svg [feature_request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/feature_request.svg -[question badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/question.svg +[Question badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Question.svg [licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE [stars]:https://github.com/olahallengren/sql-server-maintenance-solution/stargazers From d76e5c793e566e3ebe0d2f47e9b20077766f8947 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 18:52:05 +0100 Subject: [PATCH 122/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 01f3a249..4714bad0 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [forks badge]:https://img.shields.io/github/forks/olahallengren/sql-server-maintenance-solution.svg [issues badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution.svg [bug_report badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/bug_report.svg -[feature_request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/feature_request.svg +[feature_request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Feature-Request.svg [Question badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Question.svg [licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE From 7db6081037d709e737d7ecfc2c6f3121ddf45080 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 18:53:00 +0100 Subject: [PATCH 123/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4714bad0..9a1a5212 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [forks badge]:https://img.shields.io/github/forks/olahallengren/sql-server-maintenance-solution.svg [issues badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution.svg [bug_report badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/bug_report.svg -[feature_request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Feature-Request.svg +[Feature Request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Feature-Request.svg [Question badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Question.svg [licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE From 994b93d3ea5ce1443a5dd455d2798d4d82d5655e Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 18:56:47 +0100 Subject: [PATCH 124/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9a1a5212..f191a713 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [forks badge]:https://img.shields.io/github/forks/olahallengren/sql-server-maintenance-solution.svg [issues badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution.svg [bug_report badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/bug_report.svg -[Feature Request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Feature-Request.svg +[Feature Request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Feature Request.svg [Question badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Question.svg [licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE From aef7acc990065fc8aa4c6e9b0414041cbac8cd36 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 18:58:18 +0100 Subject: [PATCH 125/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f191a713..01f3a249 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [forks badge]:https://img.shields.io/github/forks/olahallengren/sql-server-maintenance-solution.svg [issues badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution.svg [bug_report badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/bug_report.svg -[Feature Request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Feature Request.svg +[feature_request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/feature_request.svg [Question badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Question.svg [licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE From 73573bb10652e13f640d18cdaccfebb030d14f17 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 18:59:39 +0100 Subject: [PATCH 126/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 01f3a249..ee21d3d6 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [forks badge]:https://img.shields.io/github/forks/olahallengren/sql-server-maintenance-solution.svg [issues badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution.svg [bug_report badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/bug_report.svg -[feature_request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/feature_request.svg +[feature_request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Question.svg [Question badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Question.svg [licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE From 904cdf6e9a3785b69bf9506caac3498e70281977 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 19:02:23 +0100 Subject: [PATCH 127/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ee21d3d6..07853739 100644 --- a/README.md +++ b/README.md @@ -45,5 +45,5 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [forks]:https://github.com/olahallengren/sql-server-maintenance-solution/network [issues]:https://github.com/olahallengren/sql-server-maintenance-solution/issues [bug_report]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Abug_report -[feature_request]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Afeature_request +[feature_request]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3AFeature%20Request [Question]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3AQuestion From 84b7ef33f2ff3db9640d0f82eab8763586a17204 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 19:03:03 +0100 Subject: [PATCH 128/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 07853739..75d69f81 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [forks badge]:https://img.shields.io/github/forks/olahallengren/sql-server-maintenance-solution.svg [issues badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution.svg [bug_report badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/bug_report.svg -[feature_request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Question.svg +[feature_request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Feature%20Request.svg [Question badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Question.svg [licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE From 345fbe9f5c746ccae62f04d694383bf7ac95b4a9 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 19:05:04 +0100 Subject: [PATCH 129/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 75d69f81..307de941 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [stars badge]:https://img.shields.io/github/stars/olahallengren/sql-server-maintenance-solution.svg [forks badge]:https://img.shields.io/github/forks/olahallengren/sql-server-maintenance-solution.svg [issues badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution.svg -[bug_report badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/bug_report.svg +[bug_report badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Bug%20Report.svg [feature_request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Feature%20Request.svg [Question badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Question.svg From cf2648244ec0bbca390aafc1c0da964799e5e0d8 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 19:11:34 +0100 Subject: [PATCH 130/188] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 307de941..fa9d12e8 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,6 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [stars]:https://github.com/olahallengren/sql-server-maintenance-solution/stargazers [forks]:https://github.com/olahallengren/sql-server-maintenance-solution/network [issues]:https://github.com/olahallengren/sql-server-maintenance-solution/issues -[bug_report]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3Abug_report -[feature_request]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3AFeature%20Request +[bug_report]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3A%22Bug+Report%22 +[feature_request]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3A%22Feature+Request%22 [Question]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3AQuestion From 5951959f4d7b8741481cffe5aa7524b8c85d4c97 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 23:36:58 +0100 Subject: [PATCH 131/188] Add files via upload --- CommandExecute.sql | 22 ++++++-- DatabaseBackup.sql | 48 ++++++++--------- DatabaseIntegrityCheck.sql | 18 +++---- IndexOptimize.sql | 12 ++--- MaintenanceSolution.sql | 102 +++++++++++++++++++++---------------- 5 files changed, 117 insertions(+), 85 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index c1e85590..1e6815a3 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -9,6 +9,7 @@ END GO ALTER PROCEDURE [dbo].[CommandExecute] +@DatabaseContext nvarchar(max), @Command nvarchar(max), @CommandType nvarchar(max), @Mode int, @@ -34,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 15:48:33 //-- + --// Version: 2019-12-31 23:31:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -45,6 +46,8 @@ BEGIN DECLARE @ErrorMessageOriginal nvarchar(max) DECLARE @Severity int + DECLARE @sp_executesql nvarchar(max) + DECLARE @StartTime datetime DECLARE @EndTime datetime @@ -58,6 +61,8 @@ BEGIN DECLARE @EmptyLine nvarchar(max) + SET @sp_executesql = QUOTENAME(@DatabaseContext) + '.sys.sp_executesql' + SET @Error = 0 SET @ReturnCode = 0 @@ -109,6 +114,14 @@ BEGIN --// Check input parameters //-- ---------------------------------------------------------------------------------------------------- + IF @DatabaseContext IS NULL OR NOT EXISTS (SELECT * FROM sys.databases WHERE name = @DatabaseContext) + BEGIN + SET @ErrorMessage = 'The value for the parameter @DatabaseContext is not supported.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + IF @Command IS NULL OR @Command = '' BEGIN SET @ErrorMessage = 'The value for the parameter @Command is not supported.' @@ -173,6 +186,9 @@ BEGIN SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTimeSec,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Database context: ' + QUOTENAME(@DatabaseContext) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Command: ' + @Command RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -196,7 +212,7 @@ BEGIN IF @Mode = 1 AND @Execute = 'Y' BEGIN - EXECUTE(@Command) + EXECUTE @sp_executesql @Command SET @Error = @@ERROR SET @ReturnCode = @Error END @@ -204,7 +220,7 @@ BEGIN IF @Mode = 2 AND @Execute = 'Y' BEGIN BEGIN TRY - EXECUTE(@Command) + EXECUTE @sp_executesql @Command END TRY BEGIN CATCH SET @Error = ERROR_NUMBER() diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 731c5fe0..6ea44732 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -75,7 +75,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 15:48:33 //-- + --// Version: 2019-12-31 23:31:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -401,7 +401,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') + IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -2686,8 +2686,8 @@ BEGIN END SET @CurrentCommandType01 = 'xp_create_subdir' - SET @CurrentCommand01 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_create_subdir N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''' IF @ReturnCode <> 0 RAISERROR(''Error creating directory.'', 16, 1)' - EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + SET @CurrentCommand01 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_create_subdir N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''' IF @ReturnCode <> 0 RAISERROR(''Error creating directory.'', 16, 1)' + EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput01 = @Error IF @CurrentCommandOutput01 <> 0 SET @ReturnCode = @CurrentCommandOutput01 @@ -2766,31 +2766,31 @@ BEGIN BEGIN SET @CurrentCommandType02 = 'xp_delete_file' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' + SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' BEGIN SET @CurrentCommandType02 = 'xp_slssqlmaint' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN SET @CurrentCommandType02 = 'sqbutility' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' + SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN SET @CurrentCommandType02 = 'xp_ss_delete' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END - EXECUTE @CurrentCommandOutput02 = [dbo].[CommandExecute] @Command = @CurrentCommand02, @CommandType = @CurrentCommandType02, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput02 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand02, @CommandType = @CurrentCommandType02, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput02 = @Error IF @CurrentCommandOutput02 <> 0 SET @ReturnCode = @CurrentCommandOutput02 @@ -2885,8 +2885,8 @@ BEGIN END SELECT @CurrentCommand03 = CASE - WHEN @CurrentBackupType IN('DIFF','FULL') THEN 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_backup_database @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' - WHEN @CurrentBackupType = 'LOG' THEN 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_backup_log @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' + WHEN @CurrentBackupType IN('DIFF','FULL') THEN 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_backup_database @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' + WHEN @CurrentBackupType = 'LOG' THEN 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_backup_log @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' END SELECT @CurrentCommand03 = @CurrentCommand03 + ', @filename = N''' + REPLACE(FilePath,'''','''''') + '''' @@ -2981,14 +2981,14 @@ BEGIN END IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand03,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLBackup backup.'', 16, 1)' + SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand03,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLBackup backup.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN SET @CurrentCommandType03 = 'xp_ss_backup' - SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_ss_backup @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' + SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_backup @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' SELECT @CurrentCommand03 = @CurrentCommand03 + ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles @@ -3022,7 +3022,7 @@ BEGIN BEGIN SET @CurrentCommandType03 = 'emc_run_backup' - SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.emc_run_backup ''' + SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.emc_run_backup ''' SET @CurrentCommand03 = @CurrentCommand03 + ' -c ' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar) END @@ -3061,7 +3061,7 @@ BEGIN SET @CurrentCommand03 = @CurrentCommand03 + ' IF @ReturnCode <> 0 RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' END - EXECUTE @CurrentCommandOutput03 = [dbo].[CommandExecute] @Command = @CurrentCommand03, @CommandType = @CurrentCommandType03, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput03 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand03, @CommandType = @CurrentCommandType03, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput03 = @Error IF @CurrentCommandOutput03 <> 0 SET @ReturnCode = @CurrentCommandOutput03 @@ -3104,7 +3104,7 @@ BEGIN BEGIN SET @CurrentCommandType04 = 'xp_restore_verifyonly' - SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_restore_verifyonly' + SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_restore_verifyonly' SELECT @CurrentCommand04 = @CurrentCommand04 + ' @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @NumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles @@ -3136,14 +3136,14 @@ BEGIN IF @CheckSum = 'N' SET @CurrentCommand04 = @CurrentCommand04 + 'NO_CHECKSUM' IF @EncryptionKey IS NOT NULL SET @CurrentCommand04 = @CurrentCommand04 + ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand04,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLBackup backup.'', 16, 1)' + SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand04,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLBackup backup.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN SET @CurrentCommandType04 = 'xp_ss_verify' - SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_ss_verify @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' + SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_verify @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' SELECT @CurrentCommand04 = @CurrentCommand04 + ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles @@ -3153,7 +3153,7 @@ BEGIN SET @CurrentCommand04 = @CurrentCommand04 + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' END - EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput04 = @Error IF @CurrentCommandOutput04 <> 0 SET @ReturnCode = @CurrentCommandOutput04 @@ -3233,31 +3233,31 @@ BEGIN BEGIN SET @CurrentCommandType05 = 'xp_delete_file' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' + SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' BEGIN SET @CurrentCommandType05 = 'xp_slssqlmaint' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN SET @CurrentCommandType05 = 'sqbutility' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' + SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN SET @CurrentCommandType05 = 'xp_ss_delete' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END - EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput05 = @Error IF @CurrentCommandOutput05 <> 0 SET @ReturnCode = @CurrentCommandOutput05 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index c604460b..0bff4efe 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 15:48:33 //-- + --// Version: 2019-12-31 23:31:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -296,7 +296,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') + IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1360,7 +1360,7 @@ BEGIN IF @TabLock = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', TABLOCK' IF @MaxDOP IS NOT NULL SET @CurrentCommand01 = @CurrentCommand01 + ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) - EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput01 = @Error IF @CurrentCommandOutput01 <> 0 SET @ReturnCode = @CurrentCommandOutput01 @@ -1475,14 +1475,14 @@ BEGIN SET @CurrentCommand04 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand04 = @CurrentCommand04 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) + SET @CurrentCommand04 = @CurrentCommand04 + 'DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) IF @NoIndex = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + ', NOINDEX' SET @CurrentCommand04 = @CurrentCommand04 + ') WITH NO_INFOMSGS, ALL_ERRORMSGS' IF @PhysicalOnly = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + ', PHYSICAL_ONLY' IF @TabLock = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + ', TABLOCK' IF @MaxDOP IS NOT NULL SET @CurrentCommand04 = @CurrentCommand04 + ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) - EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput04 = @Error IF @CurrentCommandOutput04 <> 0 SET @ReturnCode = @CurrentCommandOutput04 @@ -1519,7 +1519,7 @@ BEGIN SET @CurrentCommand05 = @CurrentCommand05 + ') WITH NO_INFOMSGS, ALL_ERRORMSGS' IF @TabLock = 'Y' SET @CurrentCommand05 = @CurrentCommand05 + ', TABLOCK' - EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput05 = @Error IF @CurrentCommandOutput05 <> 0 SET @ReturnCode = @CurrentCommandOutput05 @@ -1638,7 +1638,7 @@ BEGIN SET @CurrentCommand08 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand08 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand08 = @CurrentCommand08 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; DBCC CHECKTABLE (''' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + '''' + SET @CurrentCommand08 = @CurrentCommand08 + 'DBCC CHECKTABLE (''' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + '''' IF @NoIndex = 'Y' SET @CurrentCommand08 = @CurrentCommand08 + ', NOINDEX' SET @CurrentCommand08 = @CurrentCommand08 + ') WITH NO_INFOMSGS, ALL_ERRORMSGS' IF @PhysicalOnly = 'N' SET @CurrentCommand08 = @CurrentCommand08 + ', DATA_PURITY' @@ -1647,7 +1647,7 @@ BEGIN IF @TabLock = 'Y' SET @CurrentCommand08 = @CurrentCommand08 + ', TABLOCK' IF @MaxDOP IS NOT NULL SET @CurrentCommand08 = @CurrentCommand08 + ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) - EXECUTE @CurrentCommandOutput08 = [dbo].[CommandExecute] @Command = @CurrentCommand08, @CommandType = @CurrentCommandType08, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput08 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand08, @CommandType = @CurrentCommandType08, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput08 = @Error IF @CurrentCommandOutput08 <> 0 SET @ReturnCode = @CurrentCommandOutput08 @@ -1686,7 +1686,7 @@ BEGIN SET @CurrentCommand09 = @CurrentCommand09 + 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) SET @CurrentCommand09 = @CurrentCommand09 + ') WITH NO_INFOMSGS' - EXECUTE @CurrentCommandOutput09 = [dbo].[CommandExecute] @Command = @CurrentCommand09, @CommandType = @CurrentCommandType09, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput09 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand09, @CommandType = @CurrentCommandType09, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput09 = @Error IF @CurrentCommandOutput09 <> 0 SET @ReturnCode = @CurrentCommandOutput09 diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 0617905d..03352875 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 15:48:33 //-- + --// Version: 2019-12-31 23:31:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -385,7 +385,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') + IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1987,7 +1987,7 @@ BEGIN SET @CurrentCommand06 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand06 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand06 = @CurrentCommand06 + 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + SET @CurrentCommand06 = @CurrentCommand06 + 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) IF @CurrentResumableIndexOperation = 1 SET @CurrentCommand06 = @CurrentCommand06 + ' RESUME' IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' REBUILD' IF @CurrentAction IN('INDEX_REORGANIZE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' REORGANIZE' @@ -2092,7 +2092,7 @@ BEGIN IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand06 = @CurrentCommand06 + @CurrentAlterIndexWithClause - EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment06, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo06, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment06, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo06, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput06 = @Error IF @CurrentCommandOutput06 <> 0 SET @ReturnCode = @CurrentCommandOutput06 @@ -2112,7 +2112,7 @@ BEGIN SET @CurrentCommand07 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand07 = @CurrentCommand07 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) + SET @CurrentCommand07 = @CurrentCommand07 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) BEGIN @@ -2175,7 +2175,7 @@ BEGIN IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' - EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput07 = @Error IF @CurrentCommandOutput07 <> 0 SET @ReturnCode = @CurrentCommandOutput07 diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 2ad101d5..f7578ead 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-12-31 15:48:33 +Version: 2019-12-31 23:31:36 You can contact me by e-mail at ola@hallengren.com. @@ -101,6 +101,7 @@ END GO ALTER PROCEDURE [dbo].[CommandExecute] +@DatabaseContext nvarchar(max), @Command nvarchar(max), @CommandType nvarchar(max), @Mode int, @@ -126,7 +127,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 15:48:33 //-- + --// Version: 2019-12-31 23:31:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -137,6 +138,8 @@ BEGIN DECLARE @ErrorMessageOriginal nvarchar(max) DECLARE @Severity int + DECLARE @sp_executesql nvarchar(max) + DECLARE @StartTime datetime DECLARE @EndTime datetime @@ -150,6 +153,8 @@ BEGIN DECLARE @EmptyLine nvarchar(max) + SET @sp_executesql = QUOTENAME(@DatabaseContext) + '.sys.sp_executesql' + SET @Error = 0 SET @ReturnCode = 0 @@ -201,6 +206,14 @@ BEGIN --// Check input parameters //-- ---------------------------------------------------------------------------------------------------- + IF @DatabaseContext IS NULL OR NOT EXISTS (SELECT * FROM sys.databases WHERE name = @DatabaseContext) + BEGIN + SET @ErrorMessage = 'The value for the parameter @DatabaseContext is not supported.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + IF @Command IS NULL OR @Command = '' BEGIN SET @ErrorMessage = 'The value for the parameter @Command is not supported.' @@ -265,6 +278,9 @@ BEGIN SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTimeSec,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Database context: ' + QUOTENAME(@DatabaseContext) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Command: ' + @Command RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -288,7 +304,7 @@ BEGIN IF @Mode = 1 AND @Execute = 'Y' BEGIN - EXECUTE(@Command) + EXECUTE @sp_executesql @Command SET @Error = @@ERROR SET @ReturnCode = @Error END @@ -296,7 +312,7 @@ BEGIN IF @Mode = 2 AND @Execute = 'Y' BEGIN BEGIN TRY - EXECUTE(@Command) + EXECUTE @sp_executesql @Command END TRY BEGIN CATCH SET @Error = ERROR_NUMBER() @@ -427,7 +443,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 15:48:33 //-- + --// Version: 2019-12-31 23:31:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -753,7 +769,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') + IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -3038,8 +3054,8 @@ BEGIN END SET @CurrentCommandType01 = 'xp_create_subdir' - SET @CurrentCommand01 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_create_subdir N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''' IF @ReturnCode <> 0 RAISERROR(''Error creating directory.'', 16, 1)' - EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + SET @CurrentCommand01 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_create_subdir N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''' IF @ReturnCode <> 0 RAISERROR(''Error creating directory.'', 16, 1)' + EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput01 = @Error IF @CurrentCommandOutput01 <> 0 SET @ReturnCode = @CurrentCommandOutput01 @@ -3118,31 +3134,31 @@ BEGIN BEGIN SET @CurrentCommandType02 = 'xp_delete_file' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' + SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' BEGIN SET @CurrentCommandType02 = 'xp_slssqlmaint' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN SET @CurrentCommandType02 = 'sqbutility' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' + SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN SET @CurrentCommandType02 = 'xp_ss_delete' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END - EXECUTE @CurrentCommandOutput02 = [dbo].[CommandExecute] @Command = @CurrentCommand02, @CommandType = @CurrentCommandType02, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput02 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand02, @CommandType = @CurrentCommandType02, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput02 = @Error IF @CurrentCommandOutput02 <> 0 SET @ReturnCode = @CurrentCommandOutput02 @@ -3237,8 +3253,8 @@ BEGIN END SELECT @CurrentCommand03 = CASE - WHEN @CurrentBackupType IN('DIFF','FULL') THEN 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_backup_database @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' - WHEN @CurrentBackupType = 'LOG' THEN 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_backup_log @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' + WHEN @CurrentBackupType IN('DIFF','FULL') THEN 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_backup_database @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' + WHEN @CurrentBackupType = 'LOG' THEN 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_backup_log @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' END SELECT @CurrentCommand03 = @CurrentCommand03 + ', @filename = N''' + REPLACE(FilePath,'''','''''') + '''' @@ -3333,14 +3349,14 @@ BEGIN END IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand03,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLBackup backup.'', 16, 1)' + SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand03,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLBackup backup.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN SET @CurrentCommandType03 = 'xp_ss_backup' - SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_ss_backup @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' + SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_backup @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' SELECT @CurrentCommand03 = @CurrentCommand03 + ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles @@ -3374,7 +3390,7 @@ BEGIN BEGIN SET @CurrentCommandType03 = 'emc_run_backup' - SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.emc_run_backup ''' + SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.emc_run_backup ''' SET @CurrentCommand03 = @CurrentCommand03 + ' -c ' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar) END @@ -3413,7 +3429,7 @@ BEGIN SET @CurrentCommand03 = @CurrentCommand03 + ' IF @ReturnCode <> 0 RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' END - EXECUTE @CurrentCommandOutput03 = [dbo].[CommandExecute] @Command = @CurrentCommand03, @CommandType = @CurrentCommandType03, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput03 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand03, @CommandType = @CurrentCommandType03, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput03 = @Error IF @CurrentCommandOutput03 <> 0 SET @ReturnCode = @CurrentCommandOutput03 @@ -3456,7 +3472,7 @@ BEGIN BEGIN SET @CurrentCommandType04 = 'xp_restore_verifyonly' - SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_restore_verifyonly' + SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_restore_verifyonly' SELECT @CurrentCommand04 = @CurrentCommand04 + ' @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @NumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles @@ -3488,14 +3504,14 @@ BEGIN IF @CheckSum = 'N' SET @CurrentCommand04 = @CurrentCommand04 + 'NO_CHECKSUM' IF @EncryptionKey IS NOT NULL SET @CurrentCommand04 = @CurrentCommand04 + ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand04,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLBackup backup.'', 16, 1)' + SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand04,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLBackup backup.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN SET @CurrentCommandType04 = 'xp_ss_verify' - SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_ss_verify @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' + SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_verify @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' SELECT @CurrentCommand04 = @CurrentCommand04 + ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles @@ -3505,7 +3521,7 @@ BEGIN SET @CurrentCommand04 = @CurrentCommand04 + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' END - EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput04 = @Error IF @CurrentCommandOutput04 <> 0 SET @ReturnCode = @CurrentCommandOutput04 @@ -3585,31 +3601,31 @@ BEGIN BEGIN SET @CurrentCommandType05 = 'xp_delete_file' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' + SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' BEGIN SET @CurrentCommandType05 = 'xp_slssqlmaint' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN SET @CurrentCommandType05 = 'sqbutility' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' + SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN SET @CurrentCommandType05 = 'xp_ss_delete' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = [master].dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END - EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput05 = @Error IF @CurrentCommandOutput05 <> 0 SET @ReturnCode = @CurrentCommandOutput05 @@ -3768,7 +3784,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 15:48:33 //-- + --// Version: 2019-12-31 23:31:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4027,7 +4043,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') + IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -5091,7 +5107,7 @@ BEGIN IF @TabLock = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', TABLOCK' IF @MaxDOP IS NOT NULL SET @CurrentCommand01 = @CurrentCommand01 + ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) - EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput01 = @Error IF @CurrentCommandOutput01 <> 0 SET @ReturnCode = @CurrentCommandOutput01 @@ -5206,14 +5222,14 @@ BEGIN SET @CurrentCommand04 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand04 = @CurrentCommand04 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) + SET @CurrentCommand04 = @CurrentCommand04 + 'DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) IF @NoIndex = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + ', NOINDEX' SET @CurrentCommand04 = @CurrentCommand04 + ') WITH NO_INFOMSGS, ALL_ERRORMSGS' IF @PhysicalOnly = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + ', PHYSICAL_ONLY' IF @TabLock = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + ', TABLOCK' IF @MaxDOP IS NOT NULL SET @CurrentCommand04 = @CurrentCommand04 + ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) - EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput04 = @Error IF @CurrentCommandOutput04 <> 0 SET @ReturnCode = @CurrentCommandOutput04 @@ -5250,7 +5266,7 @@ BEGIN SET @CurrentCommand05 = @CurrentCommand05 + ') WITH NO_INFOMSGS, ALL_ERRORMSGS' IF @TabLock = 'Y' SET @CurrentCommand05 = @CurrentCommand05 + ', TABLOCK' - EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput05 = @Error IF @CurrentCommandOutput05 <> 0 SET @ReturnCode = @CurrentCommandOutput05 @@ -5369,7 +5385,7 @@ BEGIN SET @CurrentCommand08 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand08 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand08 = @CurrentCommand08 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; DBCC CHECKTABLE (''' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + '''' + SET @CurrentCommand08 = @CurrentCommand08 + 'DBCC CHECKTABLE (''' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + '''' IF @NoIndex = 'Y' SET @CurrentCommand08 = @CurrentCommand08 + ', NOINDEX' SET @CurrentCommand08 = @CurrentCommand08 + ') WITH NO_INFOMSGS, ALL_ERRORMSGS' IF @PhysicalOnly = 'N' SET @CurrentCommand08 = @CurrentCommand08 + ', DATA_PURITY' @@ -5378,7 +5394,7 @@ BEGIN IF @TabLock = 'Y' SET @CurrentCommand08 = @CurrentCommand08 + ', TABLOCK' IF @MaxDOP IS NOT NULL SET @CurrentCommand08 = @CurrentCommand08 + ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) - EXECUTE @CurrentCommandOutput08 = [dbo].[CommandExecute] @Command = @CurrentCommand08, @CommandType = @CurrentCommandType08, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput08 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand08, @CommandType = @CurrentCommandType08, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput08 = @Error IF @CurrentCommandOutput08 <> 0 SET @ReturnCode = @CurrentCommandOutput08 @@ -5417,7 +5433,7 @@ BEGIN SET @CurrentCommand09 = @CurrentCommand09 + 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) SET @CurrentCommand09 = @CurrentCommand09 + ') WITH NO_INFOMSGS' - EXECUTE @CurrentCommandOutput09 = [dbo].[CommandExecute] @Command = @CurrentCommand09, @CommandType = @CurrentCommandType09, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput09 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand09, @CommandType = @CurrentCommandType09, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput09 = @Error IF @CurrentCommandOutput09 <> 0 SET @ReturnCode = @CurrentCommandOutput09 @@ -5559,7 +5575,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 15:48:33 //-- + --// Version: 2019-12-31 23:31:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5893,7 +5909,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@LockMessageSeverity%') + IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -7495,7 +7511,7 @@ BEGIN SET @CurrentCommand06 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand06 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand06 = @CurrentCommand06 + 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + SET @CurrentCommand06 = @CurrentCommand06 + 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) IF @CurrentResumableIndexOperation = 1 SET @CurrentCommand06 = @CurrentCommand06 + ' RESUME' IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' REBUILD' IF @CurrentAction IN('INDEX_REORGANIZE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' REORGANIZE' @@ -7600,7 +7616,7 @@ BEGIN IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand06 = @CurrentCommand06 + @CurrentAlterIndexWithClause - EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment06, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo06, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment06, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo06, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput06 = @Error IF @CurrentCommandOutput06 <> 0 SET @ReturnCode = @CurrentCommandOutput06 @@ -7620,7 +7636,7 @@ BEGIN SET @CurrentCommand07 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand07 = @CurrentCommand07 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) + SET @CurrentCommand07 = @CurrentCommand07 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) BEGIN @@ -7683,7 +7699,7 @@ BEGIN IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' - EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput07 = @Error IF @CurrentCommandOutput07 <> 0 SET @ReturnCode = @CurrentCommandOutput07 From 681311d7d249d6c392f5ab450ec2df7c05b444e1 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 23:43:09 +0100 Subject: [PATCH 132/188] Update README.md --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index fa9d12e8..52888e9d 100644 --- a/README.md +++ b/README.md @@ -3,9 +3,9 @@ [![stars badge]][stars] [![forks badge]][forks] [![issues badge]][issues] -[![bug_report badge]][bug_report] -[![feature_request badge]][feature_request] -[![Question badge]][Question] +[![bug report badge]][bug_report] +[![feature request badge]][feature request] +[![question badge]][question] ## Getting Started @@ -36,14 +36,14 @@ Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Se [stars badge]:https://img.shields.io/github/stars/olahallengren/sql-server-maintenance-solution.svg [forks badge]:https://img.shields.io/github/forks/olahallengren/sql-server-maintenance-solution.svg [issues badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution.svg -[bug_report badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Bug%20Report.svg -[feature_request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Feature%20Request.svg -[Question badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Question.svg +[bug report badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Bug%20Report.svg +[feature request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Feature%20Request.svg +[question badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Question.svg [licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE [stars]:https://github.com/olahallengren/sql-server-maintenance-solution/stargazers [forks]:https://github.com/olahallengren/sql-server-maintenance-solution/network [issues]:https://github.com/olahallengren/sql-server-maintenance-solution/issues -[bug_report]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3A%22Bug+Report%22 -[feature_request]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3A%22Feature+Request%22 -[Question]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3AQuestion +[bug report]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3A%22Bug+Report%22 +[feature request]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3A%22Feature+Request%22 +[question]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3AQuestion From 77058e7cee09a6461611419b80acdb1a3312880a Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 31 Dec 2019 23:43:46 +0100 Subject: [PATCH 133/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 52888e9d..74829d81 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![stars badge]][stars] [![forks badge]][forks] [![issues badge]][issues] -[![bug report badge]][bug_report] +[![bug report badge]][bug report] [![feature request badge]][feature request] [![question badge]][question] From deffce8a7cb24253fd7a36d66d2b8630e3e4181a Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 1 Jan 2020 01:22:37 +0100 Subject: [PATCH 134/188] Update LICENSE --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index ff0e0f4a..a4ea749a 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2019 Ola Hallengren +Copyright (c) 2020 Ola Hallengren Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From 714606af0b1e4dda0bb036cd7c60e6503b32cfc9 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 1 Jan 2020 22:37:06 +0100 Subject: [PATCH 135/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 6 ++++-- IndexOptimize.sql | 14 ++++++++++---- MaintenanceSolution.sql | 26 +++++++++++++++++--------- 5 files changed, 33 insertions(+), 17 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 1e6815a3..4b7bb3b9 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 23:31:36 //-- + --// Version: 2020-01-01 22:34:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 6ea44732..f8f28151 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -75,7 +75,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 23:31:36 //-- + --// Version: 2020-01-01 22:34:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 0bff4efe..35d75745 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 23:31:36 //-- + --// Version: 2020-01-01 22:34:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -688,12 +688,14 @@ BEGIN INSERT INTO @SelectedObjects (DatabaseName, SchemaName, ObjectName, StartPosition, Selected) SELECT DatabaseName, SchemaName, ObjectName, StartPosition, Selected FROM Objects4 - OPTION (MAXRECURSION 0); + OPTION (MAXRECURSION 0) ---------------------------------------------------------------------------------------------------- --// Select check commands //-- ---------------------------------------------------------------------------------------------------- + SET @CheckCommands = REPLACE(@CheckCommands,', ',','); + WITH CheckCommands (StartPosition, EndPosition, CheckCommand) AS ( SELECT 1 AS StartPosition, diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 03352875..73c626cd 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 23:31:36 //-- + --// Version: 2020-01-01 22:34:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -725,12 +725,14 @@ BEGIN INSERT INTO @SelectedIndexes (DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected) SELECT DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected FROM Indexes4 - OPTION (MAXRECURSION 0); + OPTION (MAXRECURSION 0) ---------------------------------------------------------------------------------------------------- --// Select actions //-- ---------------------------------------------------------------------------------------------------- + SET @FragmentationLow = REPLACE(@FragmentationLow,', ',','); + WITH FragmentationLow (StartPosition, EndPosition, [Action]) AS ( SELECT 1 AS StartPosition, @@ -749,7 +751,9 @@ BEGIN ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS [Priority], [Action] FROM FragmentationLow - OPTION (MAXRECURSION 0); + OPTION (MAXRECURSION 0) + + SET @FragmentationMedium = REPLACE(@FragmentationMedium,', ',','); WITH FragmentationMedium (StartPosition, EndPosition, [Action]) AS ( @@ -769,7 +773,9 @@ BEGIN ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS [Priority], [Action] FROM FragmentationMedium - OPTION (MAXRECURSION 0); + OPTION (MAXRECURSION 0) + + SET @FragmentationHigh = REPLACE(@FragmentationHigh,', ',','); WITH FragmentationHigh (StartPosition, EndPosition, [Action]) AS ( diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index f7578ead..f6c7bd78 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2019-12-31 23:31:36 +Version: 2020-01-01 22:34:07 You can contact me by e-mail at ola@hallengren.com. @@ -127,7 +127,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 23:31:36 //-- + --// Version: 2020-01-01 22:34:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -443,7 +443,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 23:31:36 //-- + --// Version: 2020-01-01 22:34:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3784,7 +3784,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 23:31:36 //-- + --// Version: 2020-01-01 22:34:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4435,12 +4435,14 @@ BEGIN INSERT INTO @SelectedObjects (DatabaseName, SchemaName, ObjectName, StartPosition, Selected) SELECT DatabaseName, SchemaName, ObjectName, StartPosition, Selected FROM Objects4 - OPTION (MAXRECURSION 0); + OPTION (MAXRECURSION 0) ---------------------------------------------------------------------------------------------------- --// Select check commands //-- ---------------------------------------------------------------------------------------------------- + SET @CheckCommands = REPLACE(@CheckCommands,', ',','); + WITH CheckCommands (StartPosition, EndPosition, CheckCommand) AS ( SELECT 1 AS StartPosition, @@ -5575,7 +5577,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2019-12-31 23:31:36 //-- + --// Version: 2020-01-01 22:34:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6249,12 +6251,14 @@ BEGIN INSERT INTO @SelectedIndexes (DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected) SELECT DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected FROM Indexes4 - OPTION (MAXRECURSION 0); + OPTION (MAXRECURSION 0) ---------------------------------------------------------------------------------------------------- --// Select actions //-- ---------------------------------------------------------------------------------------------------- + SET @FragmentationLow = REPLACE(@FragmentationLow,', ',','); + WITH FragmentationLow (StartPosition, EndPosition, [Action]) AS ( SELECT 1 AS StartPosition, @@ -6273,7 +6277,9 @@ BEGIN ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS [Priority], [Action] FROM FragmentationLow - OPTION (MAXRECURSION 0); + OPTION (MAXRECURSION 0) + + SET @FragmentationMedium = REPLACE(@FragmentationMedium,', ',','); WITH FragmentationMedium (StartPosition, EndPosition, [Action]) AS ( @@ -6293,7 +6299,9 @@ BEGIN ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS [Priority], [Action] FROM FragmentationMedium - OPTION (MAXRECURSION 0); + OPTION (MAXRECURSION 0) + + SET @FragmentationHigh = REPLACE(@FragmentationHigh,', ',','); WITH FragmentationHigh (StartPosition, EndPosition, [Action]) AS ( From 2ef77e9b375e677862496f4026a46232c704dc25 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 2 Jan 2020 20:50:38 +0100 Subject: [PATCH 136/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 83 ++++++++++++++++++---------------- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 91 +++++++++++++++++++++----------------- 5 files changed, 99 insertions(+), 81 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 4b7bb3b9..ade51b69 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-01 22:34:07 //-- + --// Version: 2020-01-02 20:43:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index f8f28151..3f01ff88 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -75,7 +75,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-01 22:34:07 //-- + --// Version: 2020-01-02 20:43:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -116,11 +116,13 @@ BEGIN DECLARE @CurrentDatabaseState nvarchar(max) DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) + DECLARE @CurrentDatabaseSize bigint DECLARE @CurrentIsEncrypted bit DECLARE @CurrentBackupType nvarchar(max) DECLARE @CurrentMaxTransferSize int + DECLARE @CurrentNumberOfFiles int DECLARE @CurrentFileExtension nvarchar(max) DECLARE @CurrentFileNumber int DECLARE @CurrentDifferentialBaseLSN numeric(25,0) @@ -1511,8 +1513,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1520,8 +1522,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1529,8 +1531,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1538,8 +1540,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1942,7 +1944,8 @@ BEGIN @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @CurrentInStandby = is_in_standby, - @CurrentRecoveryModel = recovery_model_desc + @CurrentRecoveryModel = recovery_model_desc, + @CurrentDatabaseSize = (SELECT SUM(CAST(size AS bigint)) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) FROM sys.databases WHERE [name] = @CurrentDatabaseName @@ -2051,6 +2054,8 @@ BEGIN END END + SET @CurrentNumberOfFiles = @NumberOfFiles + SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring WHERE database_id = DB_ID(@CurrentDatabaseName) @@ -2372,6 +2377,7 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,@CurrentDate) AS nvarchar),6)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),3))) END @@ -2407,8 +2413,8 @@ BEGIN IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}','') IF @@SERVICENAME IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}','') IF @Description IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}','') - IF @NumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileNumber}','') - IF @NumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}','') + IF @CurrentNumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileNumber}','') + IF @CurrentNumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}','') WHILE (@Updated = 1 OR @Updated IS NULL) BEGIN @@ -2519,7 +2525,8 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',@NumberOfFiles) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,@CurrentDate) AS nvarchar),6)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',@CurrentNumberOfFiles) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),3))) @@ -2528,7 +2535,7 @@ BEGIN WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) WHEN EXISTS (SELECT * FROM @CurrentURLs) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentURLs) END - + LEN(REPLACE(REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '1' WHEN @NumberOfFiles >= 10 THEN '01' ELSE '' END)) + + LEN(REPLACE(REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN '1' WHEN @CurrentNumberOfFiles >= 10 THEN '01' ELSE '' END)) -- The maximum length of a backup device is 259 characters IF @CurrentMaxFilePathLength > 259 @@ -2544,17 +2551,17 @@ BEGIN BEGIN SET @CurrentFileNumber = 0 - WHILE @CurrentFileNumber < @NumberOfFiles + WHILE @CurrentFileNumber < @CurrentNumberOfFiles BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 SELECT @CurrentDirectoryPath = DirectoryPath FROM @CurrentDirectories - WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 0) + 1 - AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 0) + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 0) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 0) AND Mirror = 0 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) IF @CurrentDirectoryPath = 'NUL' BEGIN @@ -2581,17 +2588,17 @@ BEGIN BEGIN SET @CurrentFileNumber = 0 - WHILE @CurrentFileNumber < @NumberOfFiles + WHILE @CurrentFileNumber < @CurrentNumberOfFiles BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 SELECT @CurrentDirectoryPath = DirectoryPath FROM @CurrentDirectories - WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) + 1 - AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) AND Mirror = 1 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -2611,17 +2618,17 @@ BEGIN BEGIN SET @CurrentFileNumber = 0 - WHILE @CurrentFileNumber < @NumberOfFiles + WHILE @CurrentFileNumber < @CurrentNumberOfFiles BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 SELECT @CurrentDirectoryPath = DirectoryPath FROM @CurrentURLs - WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + 1 - AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) AND Mirror = 0 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -2641,17 +2648,17 @@ BEGIN BEGIN SET @CurrentFileNumber = 0 - WHILE @CurrentFileNumber < @NumberOfFiles + WHILE @CurrentFileNumber < @CurrentNumberOfFiles BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 SELECT @CurrentDirectoryPath = DirectoryPath FROM @CurrentURLs - WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + 1 - AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) AND Mirror = 1 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -2831,7 +2838,7 @@ BEGIN SET @CurrentCommand03 = @CurrentCommand03 + ' TO' - SELECT @CurrentCommand03 = @CurrentCommand03 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @NumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand03 = @CurrentCommand03 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC @@ -2840,7 +2847,7 @@ BEGIN BEGIN SET @CurrentCommand03 = @CurrentCommand03 + ' MIRROR TO' - SELECT @CurrentCommand03 = @CurrentCommand03 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @NumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand03 = @CurrentCommand03 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 1 ORDER BY FilePath ASC @@ -2951,7 +2958,7 @@ BEGIN SET @CurrentCommand03 = @CurrentCommand03 + ' TO' - SELECT @CurrentCommand03 = @CurrentCommand03 + ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @NumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand03 = @CurrentCommand03 + ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC @@ -3038,7 +3045,7 @@ BEGIN IF @CheckSum = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ' -k' - SET @CurrentCommand03 = @CurrentCommand03 + ' -S ' + CAST(@NumberOfFiles AS nvarchar) + SET @CurrentCommand03 = @CurrentCommand03 + ' -S ' + CAST(@CurrentNumberOfFiles AS nvarchar) IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -b "' + REPLACE(@Description,'''','''''') + '"' @@ -3089,7 +3096,7 @@ BEGIN SET @CurrentCommand04 = 'RESTORE VERIFYONLY FROM' - SELECT @CurrentCommand04 = @CurrentCommand04 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @NumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand04 = @CurrentCommand04 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC @@ -3106,7 +3113,7 @@ BEGIN SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_restore_verifyonly' - SELECT @CurrentCommand04 = @CurrentCommand04 + ' @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @NumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand04 = @CurrentCommand04 + ' @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC @@ -3126,7 +3133,7 @@ BEGIN SET @CurrentCommand04 = 'RESTORE VERIFYONLY FROM' - SELECT @CurrentCommand04 = @CurrentCommand04 + ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @NumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand04 = @CurrentCommand04 + ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC @@ -3315,9 +3322,11 @@ BEGIN SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL SET @CurrentIsEncrypted = NULL + SET @CurrentDatabaseSize = NULL SET @CurrentBackupType = NULL SET @CurrentMaxTransferSize = NULL + SET @CurrentNumberOfFiles = NULL SET @CurrentFileExtension = NULL SET @CurrentFileNumber = NULL SET @CurrentDifferentialBaseLSN = NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 35d75745..b49fbad8 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-01 22:34:07 //-- + --// Version: 2020-01-02 20:43:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 73c626cd..84c3bf42 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-01 22:34:07 //-- + --// Version: 2020-01-02 20:43:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index f6c7bd78..f0966d58 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-01 22:34:07 +Version: 2020-01-02 20:43:38 You can contact me by e-mail at ola@hallengren.com. @@ -127,7 +127,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-01 22:34:07 //-- + --// Version: 2020-01-02 20:43:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -443,7 +443,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-01 22:34:07 //-- + --// Version: 2020-01-02 20:43:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -484,11 +484,13 @@ BEGIN DECLARE @CurrentDatabaseState nvarchar(max) DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) + DECLARE @CurrentDatabaseSize bigint DECLARE @CurrentIsEncrypted bit DECLARE @CurrentBackupType nvarchar(max) DECLARE @CurrentMaxTransferSize int + DECLARE @CurrentNumberOfFiles int DECLARE @CurrentFileExtension nvarchar(max) DECLARE @CurrentFileNumber int DECLARE @CurrentDifferentialBaseLSN numeric(25,0) @@ -1879,8 +1881,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1888,8 +1890,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1897,8 +1899,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1906,8 +1908,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -2310,7 +2312,8 @@ BEGIN @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @CurrentInStandby = is_in_standby, - @CurrentRecoveryModel = recovery_model_desc + @CurrentRecoveryModel = recovery_model_desc, + @CurrentDatabaseSize = (SELECT SUM(CAST(size AS bigint)) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) FROM sys.databases WHERE [name] = @CurrentDatabaseName @@ -2419,6 +2422,8 @@ BEGIN END END + SET @CurrentNumberOfFiles = @NumberOfFiles + SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring WHERE database_id = DB_ID(@CurrentDatabaseName) @@ -2740,6 +2745,7 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,@CurrentDate) AS nvarchar),6)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),3))) END @@ -2775,8 +2781,8 @@ BEGIN IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}','') IF @@SERVICENAME IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}','') IF @Description IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}','') - IF @NumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileNumber}','') - IF @NumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}','') + IF @CurrentNumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileNumber}','') + IF @CurrentNumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}','') WHILE (@Updated = 1 OR @Updated IS NULL) BEGIN @@ -2887,7 +2893,8 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',@NumberOfFiles) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,@CurrentDate) AS nvarchar),6)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',@CurrentNumberOfFiles) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),3))) @@ -2896,7 +2903,7 @@ BEGIN WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) WHEN EXISTS (SELECT * FROM @CurrentURLs) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentURLs) END - + LEN(REPLACE(REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN '1' WHEN @NumberOfFiles >= 10 THEN '01' ELSE '' END)) + + LEN(REPLACE(REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN '1' WHEN @CurrentNumberOfFiles >= 10 THEN '01' ELSE '' END)) -- The maximum length of a backup device is 259 characters IF @CurrentMaxFilePathLength > 259 @@ -2912,17 +2919,17 @@ BEGIN BEGIN SET @CurrentFileNumber = 0 - WHILE @CurrentFileNumber < @NumberOfFiles + WHILE @CurrentFileNumber < @CurrentNumberOfFiles BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 SELECT @CurrentDirectoryPath = DirectoryPath FROM @CurrentDirectories - WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 0) + 1 - AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 0) + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 0) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 0) AND Mirror = 0 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) IF @CurrentDirectoryPath = 'NUL' BEGIN @@ -2949,17 +2956,17 @@ BEGIN BEGIN SET @CurrentFileNumber = 0 - WHILE @CurrentFileNumber < @NumberOfFiles + WHILE @CurrentFileNumber < @CurrentNumberOfFiles BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 SELECT @CurrentDirectoryPath = DirectoryPath FROM @CurrentDirectories - WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) + 1 - AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) AND Mirror = 1 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -2979,17 +2986,17 @@ BEGIN BEGIN SET @CurrentFileNumber = 0 - WHILE @CurrentFileNumber < @NumberOfFiles + WHILE @CurrentFileNumber < @CurrentNumberOfFiles BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 SELECT @CurrentDirectoryPath = DirectoryPath FROM @CurrentURLs - WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + 1 - AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) AND Mirror = 0 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -3009,17 +3016,17 @@ BEGIN BEGIN SET @CurrentFileNumber = 0 - WHILE @CurrentFileNumber < @NumberOfFiles + WHILE @CurrentFileNumber < @CurrentNumberOfFiles BEGIN SET @CurrentFileNumber = @CurrentFileNumber + 1 SELECT @CurrentDirectoryPath = DirectoryPath FROM @CurrentURLs - WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + 1 - AND @CurrentFileNumber <= DirectoryNumber * (SELECT @NumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) AND Mirror = 1 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @NumberOfFiles > 1 AND @NumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @NumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -3199,7 +3206,7 @@ BEGIN SET @CurrentCommand03 = @CurrentCommand03 + ' TO' - SELECT @CurrentCommand03 = @CurrentCommand03 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @NumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand03 = @CurrentCommand03 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC @@ -3208,7 +3215,7 @@ BEGIN BEGIN SET @CurrentCommand03 = @CurrentCommand03 + ' MIRROR TO' - SELECT @CurrentCommand03 = @CurrentCommand03 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @NumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand03 = @CurrentCommand03 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 1 ORDER BY FilePath ASC @@ -3319,7 +3326,7 @@ BEGIN SET @CurrentCommand03 = @CurrentCommand03 + ' TO' - SELECT @CurrentCommand03 = @CurrentCommand03 + ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @NumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand03 = @CurrentCommand03 + ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC @@ -3406,7 +3413,7 @@ BEGIN IF @CheckSum = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ' -k' - SET @CurrentCommand03 = @CurrentCommand03 + ' -S ' + CAST(@NumberOfFiles AS nvarchar) + SET @CurrentCommand03 = @CurrentCommand03 + ' -S ' + CAST(@CurrentNumberOfFiles AS nvarchar) IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -b "' + REPLACE(@Description,'''','''''') + '"' @@ -3457,7 +3464,7 @@ BEGIN SET @CurrentCommand04 = 'RESTORE VERIFYONLY FROM' - SELECT @CurrentCommand04 = @CurrentCommand04 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @NumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand04 = @CurrentCommand04 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC @@ -3474,7 +3481,7 @@ BEGIN SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_restore_verifyonly' - SELECT @CurrentCommand04 = @CurrentCommand04 + ' @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @NumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand04 = @CurrentCommand04 + ' @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC @@ -3494,7 +3501,7 @@ BEGIN SET @CurrentCommand04 = 'RESTORE VERIFYONLY FROM' - SELECT @CurrentCommand04 = @CurrentCommand04 + ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @NumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand04 = @CurrentCommand04 + ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC @@ -3683,9 +3690,11 @@ BEGIN SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL SET @CurrentIsEncrypted = NULL + SET @CurrentDatabaseSize = NULL SET @CurrentBackupType = NULL SET @CurrentMaxTransferSize = NULL + SET @CurrentNumberOfFiles = NULL SET @CurrentFileExtension = NULL SET @CurrentFileNumber = NULL SET @CurrentDifferentialBaseLSN = NULL @@ -3784,7 +3793,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-01 22:34:07 //-- + --// Version: 2020-01-02 20:43:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5577,7 +5586,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-01 22:34:07 //-- + --// Version: 2020-01-02 20:43:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 5feff6814979c8e67a769fdc1f655f87ed302729 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 2 Jan 2020 20:51:29 +0100 Subject: [PATCH 137/188] Add files via upload From 4089608e81e539dfe50daa51dc6dbb353c6c94ee Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 2 Jan 2020 20:52:21 +0100 Subject: [PATCH 138/188] Add files via upload From 292242a8bf4cb1cc72253a54e4f38f29c8c79119 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 3 Jan 2020 23:11:33 +0100 Subject: [PATCH 139/188] Add files via upload --- CommandExecute.sql | 6 +-- DatabaseBackup.sql | 32 +++++++------- DatabaseIntegrityCheck.sql | 24 +++++++---- IndexOptimize.sql | 22 +++++----- MaintenanceSolution.sql | 86 ++++++++++++++++++++++---------------- 5 files changed, 97 insertions(+), 73 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index ade51b69..24490725 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-02 20:43:38 //-- + --// Version: 2020-01-03 23:04:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -212,7 +212,7 @@ BEGIN IF @Mode = 1 AND @Execute = 'Y' BEGIN - EXECUTE @sp_executesql @Command + EXECUTE @sp_executesql @stmt = @Command SET @Error = @@ERROR SET @ReturnCode = @Error END @@ -220,7 +220,7 @@ BEGIN IF @Mode = 2 AND @Execute = 'Y' BEGIN BEGIN TRY - EXECUTE @sp_executesql @Command + EXECUTE @sp_executesql @stmt = @Command END TRY BEGIN CATCH SET @Error = ERROR_NUMBER() diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 3f01ff88..907c829d 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -75,7 +75,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-02 20:43:38 //-- + --// Version: 2020-01-03 23:04:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -111,6 +111,8 @@ BEGIN DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) + DECLARE @CurrentDatabase_sp_executesql nvarchar(max) + DECLARE @CurrentUserAccess nvarchar(max) DECLARE @CurrentIsReadOnly bit DECLARE @CurrentDatabaseState nvarchar(max) @@ -1513,8 +1515,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1522,8 +1524,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1531,8 +1533,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1540,8 +1542,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1940,6 +1942,8 @@ BEGIN BREAK END + SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @@ -1953,7 +1957,7 @@ BEGIN BEGIN SET @CurrentCommand06 = 'SELECT @ParamIsEncrypted = is_encrypted FROM sys.databases WHERE name = @ParamDatabaseName' - EXECUTE sp_executesql @statement = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT + EXECUTE sp_executesql @stmt = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT END SELECT @CurrentMaxTransferSize = CASE @@ -2011,9 +2015,9 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND @ChangeBackupType = 'Y' AND @ModificationLevel IS NOT NULL BEGIN - SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_file_space_usage' + SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' - EXECUTE sp_executesql @statement = @CurrentCommand07, @params = N'@ParamAllocatedExtentPageCount bigint OUTPUT, @ParamModifiedExtentPageCount bigint OUTPUT', @ParamAllocatedExtentPageCount = @CurrentAllocatedExtentPageCount OUTPUT, @ParamModifiedExtentPageCount = @CurrentModifiedExtentPageCount OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand07, @params = N'@ParamAllocatedExtentPageCount bigint OUTPUT, @ParamModifiedExtentPageCount bigint OUTPUT', @ParamAllocatedExtentPageCount = @CurrentAllocatedExtentPageCount OUTPUT, @ParamModifiedExtentPageCount = @CurrentModifiedExtentPageCount OUTPUT END SET @CurrentBackupType = @BackupType @@ -2377,7 +2381,6 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,@CurrentDate) AS nvarchar),6)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),3))) END @@ -2525,7 +2528,6 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,@CurrentDate) AS nvarchar),6)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',@CurrentNumberOfFiles) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) @@ -3316,6 +3318,8 @@ BEGIN SET @CurrentDBID = NULL SET @CurrentDatabaseName = NULL + SET @CurrentDatabase_sp_executesql = NULL + SET @CurrentUserAccess = NULL SET @CurrentIsReadOnly = NULL SET @CurrentDatabaseState = NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index b49fbad8..603cfc8c 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-02 20:43:38 //-- + --// Version: 2020-01-03 23:04:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -64,6 +64,8 @@ BEGIN DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) + DECLARE @CurrentDatabase_sp_executesql nvarchar(max) + DECLARE @CurrentUserAccess nvarchar(max) DECLARE @CurrentIsReadOnly bit DECLARE @CurrentDatabaseState nvarchar(max) @@ -1242,6 +1244,8 @@ BEGIN BREAK END + SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @@ -1371,10 +1375,10 @@ BEGIN -- Check filegroups IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommand02 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' + SET @CurrentCommand02 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' INSERT INTO @tmpFileGroups (FileGroupID, FileGroupName, [Order], Selected, Completed) - EXECUTE sp_executesql @statement = @CurrentCommand02 + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand02 SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -1452,10 +1456,10 @@ BEGIN -- Does the filegroup exist? SET @CurrentCommand03 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups WHERE [type] <> ''FX'' AND filegroups.data_space_id = @ParamFileGroupID AND filegroups.[name] = @ParamFileGroupName) BEGIN SET @ParamFileGroupExists = 1 END' + SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM sys.filegroups filegroups WHERE [type] <> ''FX'' AND filegroups.data_space_id = @ParamFileGroupID AND filegroups.[name] = @ParamFileGroupName) BEGIN SET @ParamFileGroupExists = 1 END' BEGIN TRY - EXECUTE sp_executesql @statement = @CurrentCommand03, @params = N'@ParamFileGroupID int, @ParamFileGroupName sysname, @ParamFileGroupExists bit OUTPUT', @ParamFileGroupID = @CurrentFileGroupID, @ParamFileGroupName = @CurrentFileGroupName, @ParamFileGroupExists = @CurrentFileGroupExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand03, @params = N'@ParamFileGroupID int, @ParamFileGroupName sysname, @ParamFileGroupExists bit OUTPUT', @ParamFileGroupID = @CurrentFileGroupID, @ParamFileGroupName = @CurrentFileGroupName, @ParamFileGroupExists = @CurrentFileGroupExists OUTPUT IF @CurrentFileGroupExists IS NULL SET @CurrentFileGroupExists = 0 END TRY @@ -1530,10 +1534,10 @@ BEGIN -- Check objects IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommand06 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' + SET @CurrentCommand06 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, [Order], Selected, Completed) - EXECUTE sp_executesql @statement = @CurrentCommand06 + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand06 SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -1615,10 +1619,10 @@ BEGIN -- Does the object exist? SET @CurrentCommand07 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand07 = @CurrentCommand07 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType) BEGIN SET @ParamObjectExists = 1 END' + SET @CurrentCommand07 = @CurrentCommand07 + 'IF EXISTS(SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType) BEGIN SET @ParamObjectExists = 1 END' BEGIN TRY - EXECUTE sp_executesql @statement = @CurrentCommand07, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamObjectExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamObjectExists = @CurrentObjectExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand07, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamObjectExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamObjectExists = @CurrentObjectExists OUTPUT IF @CurrentObjectExists IS NULL SET @CurrentObjectExists = 0 END TRY @@ -1725,6 +1729,8 @@ BEGIN SET @CurrentDBID = NULL SET @CurrentDatabaseName = NULL + SET @CurrentDatabase_sp_executesql = NULL + SET @CurrentUserAccess = NULL SET @CurrentIsReadOnly = NULL SET @CurrentDatabaseState = NULL diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 84c3bf42..62255738 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-02 20:43:38 //-- + --// Version: 2020-01-03 23:04:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -84,6 +84,8 @@ BEGIN DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) + DECLARE @CurrentDatabase_sp_executesql nvarchar(max) + DECLARE @CurrentUserAccess nvarchar(max) DECLARE @CurrentIsReadOnly bit DECLARE @CurrentDatabaseState nvarchar(max) @@ -1359,6 +1361,8 @@ BEGIN BREAK END + SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @@ -1449,7 +1453,6 @@ BEGIN IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + 'USE ' + QUOTENAME(@CurrentDatabaseName) + ';' + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, IsComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + ' FROM (' @@ -1564,7 +1567,7 @@ BEGIN SET @CurrentCommand01 = @CurrentCommand01 + ') IndexesStatistics' INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, IsComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) - EXECUTE sp_executesql @statement = @CurrentCommand01 + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand01 SET @Error = @@ERROR IF @Error <> 0 BEGIN @@ -1697,13 +1700,12 @@ BEGIN SET @CurrentCommand02 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand02 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand02 = @CurrentCommand02 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' IF @CurrentIsPartition = 0 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' IF @CurrentIsPartition = 1 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' BEGIN TRY - EXECUTE sp_executesql @statement = @CurrentCommand02, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand02, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT IF @CurrentIndexExists IS NULL BEGIN @@ -1732,12 +1734,11 @@ BEGIN SET @CurrentCommand03 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand03 = @CurrentCommand03 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM sys.stats stats INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' BEGIN TRY - EXECUTE sp_executesql @statement = @CurrentCommand03, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand03, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT IF @CurrentStatisticsExists IS NULL BEGIN @@ -1766,7 +1767,6 @@ BEGIN SET @CurrentCommand04 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand04 = @CurrentCommand04 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN @@ -1783,7 +1783,7 @@ BEGIN END BEGIN TRY - EXECUTE sp_executesql @statement = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT IF @CurrentRowCount IS NULL SET @CurrentRowCount = 0 IF @CurrentModificationCounter IS NULL SET @CurrentModificationCounter = 0 @@ -1816,7 +1816,7 @@ BEGIN SET @CurrentCommand05 = @CurrentCommand05 + 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' BEGIN TRY - EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT + EXECUTE sp_executesql @stmt = @CurrentCommand05, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT END TRY BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The page_count and avg_fragmentation_in_percent could not be checked.' ELSE '' END @@ -2301,6 +2301,8 @@ BEGIN SET @CurrentDBID = NULL SET @CurrentDatabaseName = NULL + SET @CurrentDatabase_sp_executesql = NULL + SET @CurrentUserAccess = NULL SET @CurrentIsReadOnly = NULL SET @CurrentDatabaseState = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index f0966d58..3b16f772 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-02 20:43:38 +Version: 2020-01-03 23:04:49 You can contact me by e-mail at ola@hallengren.com. @@ -127,7 +127,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-02 20:43:38 //-- + --// Version: 2020-01-03 23:04:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -304,7 +304,7 @@ BEGIN IF @Mode = 1 AND @Execute = 'Y' BEGIN - EXECUTE @sp_executesql @Command + EXECUTE @sp_executesql @stmt = @Command SET @Error = @@ERROR SET @ReturnCode = @Error END @@ -312,7 +312,7 @@ BEGIN IF @Mode = 2 AND @Execute = 'Y' BEGIN BEGIN TRY - EXECUTE @sp_executesql @Command + EXECUTE @sp_executesql @stmt = @Command END TRY BEGIN CATCH SET @Error = ERROR_NUMBER() @@ -443,7 +443,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-02 20:43:38 //-- + --// Version: 2020-01-03 23:04:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -479,6 +479,8 @@ BEGIN DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) + DECLARE @CurrentDatabase_sp_executesql nvarchar(max) + DECLARE @CurrentUserAccess nvarchar(max) DECLARE @CurrentIsReadOnly bit DECLARE @CurrentDatabaseState nvarchar(max) @@ -1881,8 +1883,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1890,8 +1892,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1899,8 +1901,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -1908,8 +1910,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT @@ -2308,6 +2310,8 @@ BEGIN BREAK END + SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @@ -2321,7 +2325,7 @@ BEGIN BEGIN SET @CurrentCommand06 = 'SELECT @ParamIsEncrypted = is_encrypted FROM sys.databases WHERE name = @ParamDatabaseName' - EXECUTE sp_executesql @statement = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT + EXECUTE sp_executesql @stmt = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT END SELECT @CurrentMaxTransferSize = CASE @@ -2379,9 +2383,9 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND @ChangeBackupType = 'Y' AND @ModificationLevel IS NOT NULL BEGIN - SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.dm_db_file_space_usage' + SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' - EXECUTE sp_executesql @statement = @CurrentCommand07, @params = N'@ParamAllocatedExtentPageCount bigint OUTPUT, @ParamModifiedExtentPageCount bigint OUTPUT', @ParamAllocatedExtentPageCount = @CurrentAllocatedExtentPageCount OUTPUT, @ParamModifiedExtentPageCount = @CurrentModifiedExtentPageCount OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand07, @params = N'@ParamAllocatedExtentPageCount bigint OUTPUT, @ParamModifiedExtentPageCount bigint OUTPUT', @ParamAllocatedExtentPageCount = @CurrentAllocatedExtentPageCount OUTPUT, @ParamModifiedExtentPageCount = @CurrentModifiedExtentPageCount OUTPUT END SET @CurrentBackupType = @BackupType @@ -2745,7 +2749,6 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,@CurrentDate) AS nvarchar),6)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),3))) END @@ -2893,7 +2896,6 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,@CurrentDate) AS nvarchar),6)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',@CurrentNumberOfFiles) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) @@ -3684,6 +3686,8 @@ BEGIN SET @CurrentDBID = NULL SET @CurrentDatabaseName = NULL + SET @CurrentDatabase_sp_executesql = NULL + SET @CurrentUserAccess = NULL SET @CurrentIsReadOnly = NULL SET @CurrentDatabaseState = NULL @@ -3793,7 +3797,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-02 20:43:38 //-- + --// Version: 2020-01-03 23:04:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3820,6 +3824,8 @@ BEGIN DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) + DECLARE @CurrentDatabase_sp_executesql nvarchar(max) + DECLARE @CurrentUserAccess nvarchar(max) DECLARE @CurrentIsReadOnly bit DECLARE @CurrentDatabaseState nvarchar(max) @@ -4998,6 +5004,8 @@ BEGIN BREAK END + SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @@ -5127,10 +5135,10 @@ BEGIN -- Check filegroups IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommand02 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' + SET @CurrentCommand02 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' INSERT INTO @tmpFileGroups (FileGroupID, FileGroupName, [Order], Selected, Completed) - EXECUTE sp_executesql @statement = @CurrentCommand02 + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand02 SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -5208,10 +5216,10 @@ BEGIN -- Does the filegroup exist? SET @CurrentCommand03 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.filegroups filegroups WHERE [type] <> ''FX'' AND filegroups.data_space_id = @ParamFileGroupID AND filegroups.[name] = @ParamFileGroupName) BEGIN SET @ParamFileGroupExists = 1 END' + SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM sys.filegroups filegroups WHERE [type] <> ''FX'' AND filegroups.data_space_id = @ParamFileGroupID AND filegroups.[name] = @ParamFileGroupName) BEGIN SET @ParamFileGroupExists = 1 END' BEGIN TRY - EXECUTE sp_executesql @statement = @CurrentCommand03, @params = N'@ParamFileGroupID int, @ParamFileGroupName sysname, @ParamFileGroupExists bit OUTPUT', @ParamFileGroupID = @CurrentFileGroupID, @ParamFileGroupName = @CurrentFileGroupName, @ParamFileGroupExists = @CurrentFileGroupExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand03, @params = N'@ParamFileGroupID int, @ParamFileGroupName sysname, @ParamFileGroupExists bit OUTPUT', @ParamFileGroupID = @CurrentFileGroupID, @ParamFileGroupName = @CurrentFileGroupName, @ParamFileGroupExists = @CurrentFileGroupExists OUTPUT IF @CurrentFileGroupExists IS NULL SET @CurrentFileGroupExists = 0 END TRY @@ -5286,10 +5294,10 @@ BEGIN -- Check objects IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommand06 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' + SET @CurrentCommand06 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, [Order], Selected, Completed) - EXECUTE sp_executesql @statement = @CurrentCommand06 + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand06 SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -5371,10 +5379,10 @@ BEGIN -- Does the object exist? SET @CurrentCommand07 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand07 = @CurrentCommand07 + 'IF EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.objects objects INNER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN ' + QUOTENAME(@CurrentDatabaseName) + '.sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM ' + QUOTENAME(@CurrentDatabaseName) + '.sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType) BEGIN SET @ParamObjectExists = 1 END' + SET @CurrentCommand07 = @CurrentCommand07 + 'IF EXISTS(SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType) BEGIN SET @ParamObjectExists = 1 END' BEGIN TRY - EXECUTE sp_executesql @statement = @CurrentCommand07, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamObjectExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamObjectExists = @CurrentObjectExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand07, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamObjectExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamObjectExists = @CurrentObjectExists OUTPUT IF @CurrentObjectExists IS NULL SET @CurrentObjectExists = 0 END TRY @@ -5481,6 +5489,8 @@ BEGIN SET @CurrentDBID = NULL SET @CurrentDatabaseName = NULL + SET @CurrentDatabase_sp_executesql = NULL + SET @CurrentUserAccess = NULL SET @CurrentIsReadOnly = NULL SET @CurrentDatabaseState = NULL @@ -5586,7 +5596,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-02 20:43:38 //-- + --// Version: 2020-01-03 23:04:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5619,6 +5629,8 @@ BEGIN DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) + DECLARE @CurrentDatabase_sp_executesql nvarchar(max) + DECLARE @CurrentUserAccess nvarchar(max) DECLARE @CurrentIsReadOnly bit DECLARE @CurrentDatabaseState nvarchar(max) @@ -6894,6 +6906,8 @@ BEGIN BREAK END + SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @@ -6984,7 +6998,6 @@ BEGIN IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + 'USE ' + QUOTENAME(@CurrentDatabaseName) + ';' + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, IsComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + ' FROM (' @@ -7099,7 +7112,7 @@ BEGIN SET @CurrentCommand01 = @CurrentCommand01 + ') IndexesStatistics' INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, IsComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) - EXECUTE sp_executesql @statement = @CurrentCommand01 + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand01 SET @Error = @@ERROR IF @Error <> 0 BEGIN @@ -7232,13 +7245,12 @@ BEGIN SET @CurrentCommand02 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand02 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand02 = @CurrentCommand02 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' IF @CurrentIsPartition = 0 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' IF @CurrentIsPartition = 1 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' BEGIN TRY - EXECUTE sp_executesql @statement = @CurrentCommand02, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand02, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT IF @CurrentIndexExists IS NULL BEGIN @@ -7267,12 +7279,11 @@ BEGIN SET @CurrentCommand03 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand03 = @CurrentCommand03 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM sys.stats stats INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' BEGIN TRY - EXECUTE sp_executesql @statement = @CurrentCommand03, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand03, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT IF @CurrentStatisticsExists IS NULL BEGIN @@ -7301,7 +7312,6 @@ BEGIN SET @CurrentCommand04 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand04 = @CurrentCommand04 + 'USE ' + QUOTENAME(@CurrentDatabaseName) + '; ' IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN @@ -7318,7 +7328,7 @@ BEGIN END BEGIN TRY - EXECUTE sp_executesql @statement = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT IF @CurrentRowCount IS NULL SET @CurrentRowCount = 0 IF @CurrentModificationCounter IS NULL SET @CurrentModificationCounter = 0 @@ -7351,7 +7361,7 @@ BEGIN SET @CurrentCommand05 = @CurrentCommand05 + 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' BEGIN TRY - EXECUTE sp_executesql @statement = @CurrentCommand05, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT + EXECUTE sp_executesql @stmt = @CurrentCommand05, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT END TRY BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The page_count and avg_fragmentation_in_percent could not be checked.' ELSE '' END @@ -7836,6 +7846,8 @@ BEGIN SET @CurrentDBID = NULL SET @CurrentDatabaseName = NULL + SET @CurrentDatabase_sp_executesql = NULL + SET @CurrentUserAccess = NULL SET @CurrentIsReadOnly = NULL SET @CurrentDatabaseState = NULL From 4997bf99a46702f2699bf2e3a6e6602247e6f3d0 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 5 Jan 2020 15:30:27 +0100 Subject: [PATCH 140/188] Add files via upload --- CommandExecute.sql | 137 +-- CommandLog.sql | 4 +- DatabaseBackup.sql | 1086 ++++++++---------- DatabaseIntegrityCheck.sql | 428 +++---- IndexOptimize.sql | 532 ++++----- MaintenanceSolution.sql | 2218 +++++++++++++++--------------------- Queue.sql | 2 +- QueueDatabase.sql | 4 +- 8 files changed, 1842 insertions(+), 2569 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 24490725..af7b60d7 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-03 23:04:49 //-- + --// Version: 2020-01-05 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -46,27 +46,22 @@ BEGIN DECLARE @ErrorMessageOriginal nvarchar(max) DECLARE @Severity int - DECLARE @sp_executesql nvarchar(max) + DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, + [Message] nvarchar(max)) - DECLARE @StartTime datetime - DECLARE @EndTime datetime + DECLARE @CurrentMessage nvarchar(max) - DECLARE @StartTimeSec datetime - DECLARE @EndTimeSec datetime + DECLARE @sp_executesql nvarchar(max) = QUOTENAME(@DatabaseContext) + '.sys.sp_executesql' - DECLARE @ID int - - DECLARE @Error int - DECLARE @ReturnCode int - - DECLARE @EmptyLine nvarchar(max) + DECLARE @StartTime datetime2 + DECLARE @EndTime datetime2 - SET @sp_executesql = QUOTENAME(@DatabaseContext) + '.sys.sp_executesql' + DECLARE @ID int - SET @Error = 0 - SET @ReturnCode = 0 + DECLARE @Error int = 0 + DECLARE @ReturnCode int = 0 - SET @EmptyLine = CHAR(9) + DECLARE @EmptyLine nvarchar(max) = CHAR(9) ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- @@ -74,40 +69,26 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - END - - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO ReturnCode + INSERT INTO @Errors ([Message]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' END ---------------------------------------------------------------------------------------------------- @@ -116,63 +97,71 @@ BEGIN IF @DatabaseContext IS NULL OR NOT EXISTS (SELECT * FROM sys.databases WHERE name = @DatabaseContext) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabaseContext is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabaseContext is not supported.' END IF @Command IS NULL OR @Command = '' BEGIN - SET @ErrorMessage = 'The value for the parameter @Command is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Command is not supported.' END IF @CommandType IS NULL OR @CommandType = '' OR LEN(@CommandType) > 60 BEGIN - SET @ErrorMessage = 'The value for the parameter @CommandType is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CommandType is not supported.' END IF @Mode NOT IN(1,2) OR @Mode IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Mode is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Mode is not supported.' END IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.' END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LogToTable is not supported.' END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Execute is not supported.' + END + + ---------------------------------------------------------------------------------------------------- + --// Raise errors //-- + ---------------------------------------------------------------------------------------------------- + + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + + OPEN ErrorCursor + + FETCH ErrorCursor INTO @CurrentMessage + + WHILE @@FETCH_STATUS = 0 + BEGIN + RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT + + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage END - IF @Error <> 0 + CLOSE ErrorCursor + + DEALLOCATE ErrorCursor + + IF EXISTS (SELECT * FROM @Errors) BEGIN - SET @ReturnCode = @Error + SET @ReturnCode = 50000 GOTO ReturnCode END @@ -180,10 +169,9 @@ BEGIN --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartTime = GETDATE() - SET @StartTimeSec = CONVERT(datetime,CONVERT(nvarchar,@StartTime,120),120) + SET @StartTime = SYSDATETIME() - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTimeSec,120) + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Database context: ' + QUOTENAME(@DatabaseContext) @@ -241,16 +229,15 @@ BEGIN --// Log completing information //-- ---------------------------------------------------------------------------------------------------- - SET @EndTime = GETDATE() - SET @EndTimeSec = CONVERT(datetime,CONVERT(varchar,@EndTime,120),120) + SET @EndTime = SYSDATETIME() SET @EndMessage = 'Outcome: ' + CASE WHEN @Execute = 'N' THEN 'Not Executed' WHEN @Error = 0 THEN 'Succeeded' ELSE 'Failed' END RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT - SET @EndMessage = 'Duration: ' + CASE WHEN DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) > 0 THEN CAST(DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) AS nvarchar) + '.' ELSE '' END + CONVERT(nvarchar,@EndTimeSec - @StartTimeSec,108) + 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) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTimeSec,120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTime,120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT diff --git a/CommandLog.sql b/CommandLog.sql index 241a4cde..98071d35 100644 --- a/CommandLog.sql +++ b/CommandLog.sql @@ -17,8 +17,8 @@ CREATE TABLE [dbo].[CommandLog]( [ExtendedInfo] [xml] NULL, [Command] [nvarchar](max) NOT NULL, [CommandType] [nvarchar](60) NOT NULL, - [StartTime] [datetime] NOT NULL, - [EndTime] [datetime] NULL, + [StartTime] [datetime2](7) NOT NULL, + [EndTime] [datetime2](7) NULL, [ErrorNumber] [int] NULL, [ErrorMessage] [nvarchar](max) NULL, CONSTRAINT [PK_CommandLog] PRIMARY KEY CLUSTERED diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 907c829d..534d6583 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -75,7 +75,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-03 23:04:49 //-- + --// Version: 2020-01-05 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -85,16 +85,14 @@ BEGIN DECLARE @DatabaseMessage nvarchar(max) DECLARE @ErrorMessage nvarchar(max) - DECLARE @StartTime datetime - DECLARE @SchemaName nvarchar(max) - DECLARE @ObjectName nvarchar(max) - DECLARE @VersionTimestamp nvarchar(max) + DECLARE @StartTime datetime2 = SYSDATETIME() + DECLARE @SchemaName nvarchar(max) = OBJECT_SCHEMA_NAME(@@PROCID) + DECLARE @ObjectName nvarchar(max) = OBJECT_NAME(@@PROCID) + DECLARE @VersionTimestamp nvarchar(max) = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) DECLARE @Parameters nvarchar(max) - DECLARE @Version numeric(18,10) DECLARE @HostPlatform nvarchar(max) DECLARE @DirectorySeparator nvarchar(max) - DECLARE @AmazonRDS bit DECLARE @Updated bit @@ -103,7 +101,7 @@ BEGIN DECLARE @DefaultDirectory nvarchar(4000) DECLARE @QueueID int - DECLARE @QueueStartTime datetime + DECLARE @QueueStartTime datetime2 DECLARE @CurrentRootDirectoryID int DECLARE @CurrentRootDirectoryPath nvarchar(4000) @@ -130,7 +128,7 @@ BEGIN DECLARE @CurrentDifferentialBaseLSN numeric(25,0) DECLARE @CurrentDifferentialBaseIsSnapshot bit DECLARE @CurrentLogLSN numeric(25,0) - DECLARE @CurrentLatestBackup datetime + DECLARE @CurrentLatestBackup datetime2 DECLARE @CurrentDatabaseNameFS nvarchar(max) DECLARE @CurrentDirectoryStructure nvarchar(max) DECLARE @CurrentDatabaseFileName nvarchar(max) @@ -139,8 +137,8 @@ BEGIN DECLARE @CurrentDirectoryID int DECLARE @CurrentDirectoryPath nvarchar(max) DECLARE @CurrentFilePath nvarchar(max) - DECLARE @CurrentDate datetime - DECLARE @CurrentCleanupDate datetime + DECLARE @CurrentDate datetime2 + DECLARE @CurrentCleanupDate datetime2 DECLARE @CurrentIsDatabaseAccessible bit DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) @@ -151,7 +149,7 @@ BEGIN DECLARE @CurrentBackupSetID int DECLARE @CurrentIsMirror bit - DECLARE @CurrentLastLogBackup datetime + DECLARE @CurrentLastLogBackup datetime2 DECLARE @CurrentLogSizeSinceLastLogBackup float DECLARE @CurrentAllocatedExtentPageCount bigint DECLARE @CurrentModifiedExtentPageCount bigint @@ -161,7 +159,6 @@ BEGIN DECLARE @CurrentCommand03 nvarchar(max) DECLARE @CurrentCommand04 nvarchar(max) DECLARE @CurrentCommand05 nvarchar(max) - DECLARE @CurrentCommand06 nvarchar(max) DECLARE @CurrentCommand07 nvarchar(max) DECLARE @CurrentCommandOutput01 int @@ -176,6 +173,11 @@ BEGIN DECLARE @CurrentCommandType04 nvarchar(max) DECLARE @CurrentCommandType05 nvarchar(max) + DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, + [Message] nvarchar(max)) + + DECLARE @CurrentMessage nvarchar(max) + DECLARE @Directories TABLE (ID int PRIMARY KEY, DirectoryPath nvarchar(max), Mirror bit, @@ -229,7 +231,7 @@ BEGIN DirectoryPath nvarchar(max), Mirror bit, DirectoryNumber int, - CleanupDate datetime, + CleanupDate datetime2, CleanupMode nvarchar(max), CreateCompleted bit, CleanupCompleted bit, @@ -245,21 +247,15 @@ BEGIN FilePath nvarchar(max), Mirror bit) - DECLARE @CurrentCleanupDates TABLE (CleanupDate datetime, Mirror bit) - - DECLARE @DirectoryCheck bit - - DECLARE @Error int - DECLARE @ReturnCode int - - DECLARE @EmptyLine nvarchar(max) + DECLARE @CurrentCleanupDates TABLE (CleanupDate datetime2, + Mirror bit) - SET @Error = 0 - SET @ReturnCode = 0 + DECLARE @Error int = 0 + DECLARE @ReturnCode int = 0 - SET @EmptyLine = CHAR(9) + DECLARE @EmptyLine nvarchar(max) = CHAR(9) - SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) + DECLARE @Version numeric(18,10) = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) IF @Version >= 14 BEGIN @@ -271,74 +267,69 @@ BEGIN SET @HostPlatform = 'Windows' END - SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartTime = GETDATE() - SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) - SET @ObjectName = OBJECT_NAME(@@PROCID) - SET @VersionTimestamp = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) - SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @BackupType = ' + ISNULL('''' + REPLACE(@BackupType,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Verify = ' + ISNULL('''' + REPLACE(@Verify,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @CleanupMode = ' + ISNULL('''' + REPLACE(@CleanupMode,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Compress = ' + ISNULL('''' + REPLACE(@Compress,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @CopyOnly = ' + ISNULL('''' + REPLACE(@CopyOnly,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ChangeBackupType = ' + ISNULL('''' + REPLACE(@ChangeBackupType,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @BackupSoftware = ' + ISNULL('''' + REPLACE(@BackupSoftware,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @CheckSum = ' + ISNULL('''' + REPLACE(@CheckSum,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @BlockSize = ' + ISNULL(CAST(@BlockSize AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @CompressionLevel = ' + ISNULL(CAST(@CompressionLevel AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @Encrypt = ' + ISNULL('''' + REPLACE(@Encrypt,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @EncryptionAlgorithm = ' + ISNULL('''' + REPLACE(@EncryptionAlgorithm,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ServerCertificate = ' + ISNULL('''' + REPLACE(@ServerCertificate,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ServerAsymmetricKey = ' + ISNULL('''' + REPLACE(@ServerAsymmetricKey,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @EncryptionKey = ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ReadWriteFileGroups = ' + ISNULL('''' + REPLACE(@ReadWriteFileGroups,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @OverrideBackupPreference = ' + ISNULL('''' + REPLACE(@OverrideBackupPreference,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @NoRecovery = ' + ISNULL('''' + REPLACE(@NoRecovery,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @URL = ' + ISNULL('''' + REPLACE(@URL,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Credential = ' + ISNULL('''' + REPLACE(@Credential,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @MirrorDirectory = ' + ISNULL('''' + REPLACE(@MirrorDirectory,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @MirrorCleanupTime = ' + ISNULL(CAST(@MirrorCleanupTime AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @MirrorCleanupMode = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @MirrorURL = ' + ISNULL('''' + REPLACE(@MirrorURL,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ModificationLevel = ' + ISNULL(CAST(@ModificationLevel AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @DataDomainBoostHost = ' + ISNULL('''' + REPLACE(@DataDomainBoostHost,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DataDomainBoostUser = ' + ISNULL('''' + REPLACE(@DataDomainBoostUser,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DataDomainBoostDevicePath = ' + ISNULL('''' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DataDomainBoostLockboxPath = ' + ISNULL('''' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DirectoryStructure = ' + ISNULL('''' + REPLACE(@DirectoryStructure,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @AvailabilityGroupDirectoryStructure = ' + ISNULL('''' + REPLACE(@AvailabilityGroupDirectoryStructure,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FileName = ' + ISNULL('''' + REPLACE(@FileName,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @AvailabilityGroupFileName = ' + ISNULL('''' + REPLACE(@AvailabilityGroupFileName,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FileExtensionFull = ' + ISNULL('''' + REPLACE(@FileExtensionFull,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FileExtensionDiff = ' + ISNULL('''' + REPLACE(@FileExtensionDiff,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ObjectLevelRecoveryMap = ' + ISNULL('''' + REPLACE(@ObjectLevelRecoveryMap,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @Parameters += ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL') + SET @Parameters += ', @BackupType = ' + ISNULL('''' + REPLACE(@BackupType,'''','''''') + '''','NULL') + SET @Parameters += ', @Verify = ' + ISNULL('''' + REPLACE(@Verify,'''','''''') + '''','NULL') + SET @Parameters += ', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') + SET @Parameters += ', @CleanupMode = ' + ISNULL('''' + REPLACE(@CleanupMode,'''','''''') + '''','NULL') + SET @Parameters += ', @Compress = ' + ISNULL('''' + REPLACE(@Compress,'''','''''') + '''','NULL') + SET @Parameters += ', @CopyOnly = ' + ISNULL('''' + REPLACE(@CopyOnly,'''','''''') + '''','NULL') + SET @Parameters += ', @ChangeBackupType = ' + ISNULL('''' + REPLACE(@ChangeBackupType,'''','''''') + '''','NULL') + SET @Parameters += ', @BackupSoftware = ' + ISNULL('''' + REPLACE(@BackupSoftware,'''','''''') + '''','NULL') + SET @Parameters += ', @CheckSum = ' + ISNULL('''' + REPLACE(@CheckSum,'''','''''') + '''','NULL') + SET @Parameters += ', @BlockSize = ' + ISNULL(CAST(@BlockSize AS nvarchar),'NULL') + SET @Parameters += ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar),'NULL') + SET @Parameters += ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar),'NULL') + SET @Parameters += ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar),'NULL') + SET @Parameters += ', @CompressionLevel = ' + ISNULL(CAST(@CompressionLevel AS nvarchar),'NULL') + SET @Parameters += ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL') + SET @Parameters += ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar),'NULL') + SET @Parameters += ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar),'NULL') + SET @Parameters += ', @Encrypt = ' + ISNULL('''' + REPLACE(@Encrypt,'''','''''') + '''','NULL') + SET @Parameters += ', @EncryptionAlgorithm = ' + ISNULL('''' + REPLACE(@EncryptionAlgorithm,'''','''''') + '''','NULL') + SET @Parameters += ', @ServerCertificate = ' + ISNULL('''' + REPLACE(@ServerCertificate,'''','''''') + '''','NULL') + SET @Parameters += ', @ServerAsymmetricKey = ' + ISNULL('''' + REPLACE(@ServerAsymmetricKey,'''','''''') + '''','NULL') + SET @Parameters += ', @EncryptionKey = ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + SET @Parameters += ', @ReadWriteFileGroups = ' + ISNULL('''' + REPLACE(@ReadWriteFileGroups,'''','''''') + '''','NULL') + SET @Parameters += ', @OverrideBackupPreference = ' + ISNULL('''' + REPLACE(@OverrideBackupPreference,'''','''''') + '''','NULL') + SET @Parameters += ', @NoRecovery = ' + ISNULL('''' + REPLACE(@NoRecovery,'''','''''') + '''','NULL') + SET @Parameters += ', @URL = ' + ISNULL('''' + REPLACE(@URL,'''','''''') + '''','NULL') + SET @Parameters += ', @Credential = ' + ISNULL('''' + REPLACE(@Credential,'''','''''') + '''','NULL') + SET @Parameters += ', @MirrorDirectory = ' + ISNULL('''' + REPLACE(@MirrorDirectory,'''','''''') + '''','NULL') + SET @Parameters += ', @MirrorCleanupTime = ' + ISNULL(CAST(@MirrorCleanupTime AS nvarchar),'NULL') + SET @Parameters += ', @MirrorCleanupMode = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode,'''','''''') + '''','NULL') + SET @Parameters += ', @MirrorURL = ' + ISNULL('''' + REPLACE(@MirrorURL,'''','''''') + '''','NULL') + SET @Parameters += ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') + SET @Parameters += ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') + SET @Parameters += ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL') + SET @Parameters += ', @ModificationLevel = ' + ISNULL(CAST(@ModificationLevel AS nvarchar),'NULL') + SET @Parameters += ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar),'NULL') + SET @Parameters += ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar),'NULL') + SET @Parameters += ', @DataDomainBoostHost = ' + ISNULL('''' + REPLACE(@DataDomainBoostHost,'''','''''') + '''','NULL') + SET @Parameters += ', @DataDomainBoostUser = ' + ISNULL('''' + REPLACE(@DataDomainBoostUser,'''','''''') + '''','NULL') + SET @Parameters += ', @DataDomainBoostDevicePath = ' + ISNULL('''' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '''','NULL') + SET @Parameters += ', @DataDomainBoostLockboxPath = ' + ISNULL('''' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '''','NULL') + SET @Parameters += ', @DirectoryStructure = ' + ISNULL('''' + REPLACE(@DirectoryStructure,'''','''''') + '''','NULL') + SET @Parameters += ', @AvailabilityGroupDirectoryStructure = ' + ISNULL('''' + REPLACE(@AvailabilityGroupDirectoryStructure,'''','''''') + '''','NULL') + SET @Parameters += ', @FileName = ' + ISNULL('''' + REPLACE(@FileName,'''','''''') + '''','NULL') + SET @Parameters += ', @AvailabilityGroupFileName = ' + ISNULL('''' + REPLACE(@AvailabilityGroupFileName,'''','''''') + '''','NULL') + SET @Parameters += ', @FileExtensionFull = ' + ISNULL('''' + REPLACE(@FileExtensionFull,'''','''''') + '''','NULL') + SET @Parameters += ', @FileExtensionDiff = ' + ISNULL('''' + REPLACE(@FileExtensionDiff,'''','''''') + '''','NULL') + SET @Parameters += ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') + SET @Parameters += ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') + SET @Parameters += ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') + SET @Parameters += ', @ObjectLevelRecoveryMap = ' + ISNULL('''' + REPLACE(@ObjectLevelRecoveryMap,'''','''''') + '''','NULL') + SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') + SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') + SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') + SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -375,88 +366,62 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' END IF @@TRANCOUNT <> 0 BEGIN - SET @ErrorMessage = 'The transaction count is not 0.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The transaction count is not 0.' END IF @AmazonRDS = 1 BEGIN - SET @ErrorMessage = 'The stored procedure DatabaseBackup is not supported on Amazon RDS.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - END - - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO Logging + INSERT INTO @Errors ([Message]) + SELECT 'The stored procedure DatabaseBackup is not supported on Amazon RDS.' END ---------------------------------------------------------------------------------------------------- @@ -583,10 +548,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Databases is not supported.' END ---------------------------------------------------------------------------------------------------- @@ -680,26 +643,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.' END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' END ---------------------------------------------------------------------------------------------------- @@ -714,10 +671,8 @@ BEGIN ORDER BY DatabaseName ASC IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -730,10 +685,8 @@ BEGIN OPTION (RECOMPILE) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END ---------------------------------------------------------------------------------------------------- @@ -824,8 +777,6 @@ BEGIN --// Check directories //-- ---------------------------------------------------------------------------------------------------- - SET @DirectoryCheck = 1 - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux') OR (DirectoryPath = 'NUL' AND @HostPlatform = 'Windows')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' @@ -836,11 +787,8 @@ BEGIN OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath <> 'NUL')) OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) BEGIN - SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - SET @DirectoryCheck = 0 + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Directory is not supported.' END IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) @@ -855,22 +803,17 @@ BEGIN OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - SET @DirectoryCheck = 0 + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.' END IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) BEGIN - SET @ErrorMessage = 'Mirrored backup to disk is only available in Enterprise and Developer Edition.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'Mirrored backup to disk is only available in Enterprise and Developer Edition.' END - IF @DirectoryCheck = 1 + IF NOT EXISTS (SELECT * FROM @Errors WHERE [Message] IN('The value for the parameter @Directory is not supported.','The value for the parameter @MirrorDirectory is not supported.')) BEGIN WHILE (1 = 1) BEGIN @@ -891,10 +834,8 @@ BEGIN IF NOT EXISTS (SELECT * FROM @DirectoryInfo WHERE FileExists = 0 AND FileIsADirectory = 1 AND ParentDirectoryExists = 1) BEGIN - SET @ErrorMessage = 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.' END UPDATE @Directories @@ -976,20 +917,16 @@ BEGIN OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @URL is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @URL is not supported.' END IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath NOT LIKE 'https://%/%') OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MirrorURL is not supported.' END ---------------------------------------------------------------------------------------------------- @@ -1077,567 +1014,426 @@ BEGIN IF @BackupType NOT IN ('FULL','DIFF','LOG') OR @BackupType IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @BackupType is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @BackupType is not supported.' END IF SERVERPROPERTY('EngineEdition') = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN - SET @ErrorMessage = 'SQL Database Managed Instance only supports COPY_ONLY full backups.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.' END IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Verify is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Verify is not supported.' END IF @Verify = 'Y' AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN - SET @ErrorMessage = 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.' END IF @CleanupTime < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupTime is not supported.' END IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.' END IF @CleanupTime IS NOT NULL AND @HostPlatform = 'Linux' BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.' END IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.' END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.' END IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.' END IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupMode is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupMode is not supported.' END IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @Compress is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Compress is not supported.' END IF @CopyOnly NOT IN ('Y','N') OR @CopyOnly IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CopyOnly is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CopyOnly is not supported.' END IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @ChangeBackupType is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @ChangeBackupType is not supported.' END IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN - SET @ErrorMessage = 'The value for the parameter @BackupSoftware is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @BackupSoftware is not supported.' END IF @BackupSoftware = 'LITESPEED' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_backup_database') BEGIN - SET @ErrorMessage = 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.' END IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN - SET @ErrorMessage = 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.' END IF @BackupSoftware = 'SQLSAFE' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_ss_backup') BEGIN - SET @ErrorMessage = 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.' END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'PC' AND [name] = 'emc_run_backup') BEGIN - SET @ErrorMessage = 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.' END IF @CheckSum NOT IN ('Y','N') OR @CheckSum IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CheckSum is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CheckSum is not supported.' END IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @BlockSize is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @BlockSize is not supported.' END IF @BufferCount <= 0 OR @BufferCount > 2147483647 OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE') BEGIN - SET @ErrorMessage = 'The value for the parameter @BufferCount is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @BufferCount is not supported.' END IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxTransferSize is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MaxTransferSize is not supported.' END IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @NumberOfFiles is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.' END IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @CompressionLevel is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CompressionLevel is not supported.' END IF LEN(@Description) > 255 OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) BEGIN - SET @ErrorMessage = 'The value for the parameter @Description is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Description is not supported.' END IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) OR (@BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32)) OR (@BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32)) OR (@BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64)) BEGIN - SET @ErrorMessage = 'The value for the parameter @Threads is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Threads is not supported.' END IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) OR @Throttle < 1 OR @Throttle > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @Throttle is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Throttle is not supported.' END IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Encrypt is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Encrypt is not supported.' END IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @EncryptionAlgorithm is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.' END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL) OR (@ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate)) BEGIN - SET @ErrorMessage = 'The value for the parameter @ServerCertificate is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @ServerCertificate is not supported.' END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL) OR (@ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey)) BEGIN - SET @ErrorMessage = 'The value for the parameter @ServerAsymmetricKey is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.' END IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @EncryptionKey is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @EncryptionKey is not supported.' END IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL OR (@ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG') BEGIN - SET @ErrorMessage = 'The value for the parameter @ReadWriteFileGroups is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.' END IF @OverrideBackupPreference NOT IN('Y','N') OR @OverrideBackupPreference IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @OverrideBackupPreference is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @OverrideBackupPreference is not supported.' END IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL OR (@NoRecovery = 'Y' AND @BackupType <> 'LOG') OR (@NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE') BEGIN - SET @ErrorMessage = 'The value for the parameter @NoRecovery is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @NoRecovery is not supported.' END IF (@URL IS NOT NULL AND @Directory IS NOT NULL) OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@URL IS NOT NULL AND @Version < 11.03339) OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @URL is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @URL is not supported.' END IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) BEGIN - SET @ErrorMessage = 'The value for the parameter @Credential is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Credential is not supported.' END IF @MirrorCleanupTime < 0 OR (@MirrorCleanupTime IS NOT NULL AND @MirrorDirectory IS NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorCleanupTime is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MirrorCleanupTime is not supported.' END IF @MirrorCleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @MirrorCleanupMode IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorCleanupMode is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MirrorCleanupMode is not supported.' END IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @URL IS NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MirrorURL is not supported.' END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Updateability is not supported.' END IF @AdaptiveCompression NOT IN('SIZE','SPEED') OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) BEGIN - SET @ErrorMessage = 'The value for the parameter @AdaptiveCompression is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @AdaptiveCompression is not supported.' END IF (@ModificationLevel IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN - SET @ErrorMessage = 'The value for the parameter @ModificationLevel is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @ModificationLevel is not supported.' END IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN - SET @ErrorMessage = 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' END IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN - SET @ErrorMessage = 'The value for the parameter @TimeSinceLastLogBackup is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @TimeSinceLastLogBackup is not supported.' END IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostHost is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DataDomainBoostHost is not supported.' END IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostUser is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DataDomainBoostUser is not supported.' END IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostDevicePath is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.' END IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostLockboxPath is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.' END IF @DirectoryStructure = '' BEGIN - SET @ErrorMessage = 'The value for the parameter @DirectoryStructure is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DirectoryStructure is not supported.' END IF @AvailabilityGroupDirectoryStructure = '' BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.' END IF @FileName IS NULL OR @FileName = '' OR @FileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') OR @FileName LIKE '%{DirectorySeperator}%' OR @FileName LIKE '%/%' OR @FileName LIKE '%\%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileName is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FileName is not supported.' END IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) OR @AvailabilityGroupFileName = '' OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' OR @AvailabilityGroupFileName LIKE '%/%' OR @AvailabilityGroupFileName LIKE '%\%' BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupFileName is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.' END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The parameter @FileName contains one or more tokens that are not supported.' END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' END IF @FileExtensionFull LIKE '%.%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileExtensionFull is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FileExtensionFull is not supported.' END IF @FileExtensionDiff LIKE '%.%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileExtensionDiff is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FileExtensionDiff is not supported.' END IF @FileExtensionLog LIKE '%.%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileExtensionLog is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FileExtensionLog is not supported.' END IF @Init NOT IN('Y','N') OR @Init IS NULL OR (@Init = 'Y' AND @BackupType = 'LOG') OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Init is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Init is not supported.' END IF @Format NOT IN('Y','N') OR @Format IS NULL OR (@Format = 'Y' AND @BackupType = 'LOG') OR (@Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Format is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Format is not supported.' END IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL) OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED') OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG') BEGIN - SET @ErrorMessage = 'The value for the parameter @ObjectLevelRecovery is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.' END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.' END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.' END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LogToTable is not supported.' END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Execute is not supported.' END - IF @Error <> 0 + IF EXISTS(SELECT * FROM @Errors) BEGIN - SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - SET @ReturnCode = @Error - GOTO Logging + INSERT INTO @Errors ([Message]) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.' END ---------------------------------------------------------------------------------------------------- @@ -1651,10 +1447,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -1664,10 +1458,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END ---------------------------------------------------------------------------------------------------- @@ -1676,10 +1468,36 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + END + + ---------------------------------------------------------------------------------------------------- + --// Raise errors //-- + ---------------------------------------------------------------------------------------------------- + + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + + OPEN ErrorCursor + + FETCH ErrorCursor INTO @CurrentMessage + + WHILE @@FETCH_STATUS = 0 + BEGIN + RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT + + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage + END + + CLOSE ErrorCursor + + DEALLOCATE ErrorCursor + + IF EXISTS (SELECT * FROM @Errors) + BEGIN + SET @ReturnCode = 50000 + GOTO Logging END ---------------------------------------------------------------------------------------------------- @@ -1826,7 +1644,7 @@ BEGIN BEGIN TRANSACTION UPDATE [Queue] - SET QueueStartTime = GETDATE(), + SET QueueStartTime = SYSDATETIME(), SessionID = @@SPID, RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID) @@ -1906,7 +1724,7 @@ BEGIN AND NOT EXISTS (SELECT * FROM sys.dm_exec_requests WHERE session_id = QueueDatabase.SessionID AND request_id = QueueDatabase.RequestID AND start_time = QueueDatabase.RequestStartTime) UPDATE QueueDatabase - SET DatabaseStartTime = GETDATE(), + SET DatabaseStartTime = SYSDATETIME(), DatabaseEndTime = NULL, SessionID = @@SPID, RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), @@ -1949,17 +1767,11 @@ BEGIN @CurrentDatabaseState = state_desc, @CurrentInStandby = is_in_standby, @CurrentRecoveryModel = recovery_model_desc, + @CurrentIsEncrypted = is_encrypted, @CurrentDatabaseSize = (SELECT SUM(CAST(size AS bigint)) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) FROM sys.databases WHERE [name] = @CurrentDatabaseName - IF @Version >= 10 - BEGIN - SET @CurrentCommand06 = 'SELECT @ParamIsEncrypted = is_encrypted FROM sys.databases WHERE name = @ParamDatabaseName' - - EXECUTE sp_executesql @stmt = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT - END - SELECT @CurrentMaxTransferSize = CASE WHEN @MaxTransferSize IS NOT NULL THEN @MaxTransferSize WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND @Version >= 13.04446 THEN 65537 @@ -1999,13 +1811,6 @@ BEGIN AND [type] = 0 AND [file_id] = 1 - -- Workaround for a bug in SQL Server 2005 - IF @Version >= 9 AND @Version < 10 - AND EXISTS(SELECT * FROM sys.master_files WHERE database_id = DB_ID(@CurrentDatabaseName) AND [type] = 0 AND [file_id] = 1 AND differential_base_lsn IS NOT NULL AND differential_base_guid IS NOT NULL AND differential_base_time IS NULL) - BEGIN - SET @CurrentDifferentialBaseLSN = NULL - END - IF @CurrentDatabaseState = 'ONLINE' BEGIN SELECT @CurrentLogLSN = last_log_backup_lsn @@ -2074,7 +1879,7 @@ BEGIN SET @CurrentLogShippingRole = 'SECONDARY' END - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) @@ -2178,7 +1983,7 @@ BEGIN AND NOT ((@CurrentLogShippingRole = 'PRIMARY' AND @CurrentLogShippingRole IS NOT NULL) AND @CurrentBackupType = 'LOG') AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') - AND NOT (@CurrentBackupType = 'LOG' AND @LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NOT NULL AND NOT(@CurrentLogSizeSinceLastLogBackup >= @LogSizeSinceLastLogBackup OR @CurrentLogSizeSinceLastLogBackup IS NULL OR DATEDIFF(SECOND,@CurrentLastLogBackup,GETDATE()) >= @TimeSinceLastLogBackup OR @CurrentLastLogBackup IS NULL)) + AND NOT (@CurrentBackupType = 'LOG' AND @LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NOT NULL AND NOT(@CurrentLogSizeSinceLastLogBackup >= @LogSizeSinceLastLogBackup OR @CurrentLogSizeSinceLastLogBackup IS NULL OR DATEDIFF(SECOND,@CurrentLastLogBackup,SYSDATETIME()) >= @TimeSinceLastLogBackup OR @CurrentLastLogBackup IS NULL)) BEGIN IF @CurrentBackupType = 'LOG' AND (@CleanupTime IS NOT NULL OR @MirrorCleanupTime IS NOT NULL) @@ -2191,7 +1996,7 @@ BEGIN AND database_name = @CurrentDatabaseName END - SET @CurrentDate = GETDATE() + SET @CurrentDate = SYSDATETIME() INSERT INTO @CurrentCleanupDates (CleanupDate) SELECT @CurrentDate @@ -2381,6 +2186,7 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,@CurrentDate) AS nvarchar),6)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),3))) END @@ -2528,6 +2334,7 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,@CurrentDate) AS nvarchar),6)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',@CurrentNumberOfFiles) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) @@ -2720,7 +2527,7 @@ BEGIN IF @CleanupMode = 'BEFORE_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@CleanupTime),GETDATE()), 0 + SELECT DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 0 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -2736,7 +2543,7 @@ BEGIN IF @MirrorCleanupMode = 'BEFORE_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@MirrorCleanupTime),GETDATE()), 1 + SELECT DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 1 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -2782,21 +2589,21 @@ BEGIN BEGIN SET @CurrentCommandType02 = 'xp_slssqlmaint' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN SET @CurrentCommandType02 = 'sqbutility' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' + SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN SET @CurrentCommandType02 = 'xp_ss_delete' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END EXECUTE @CurrentCommandOutput02 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand02, @CommandType = @CurrentCommandType02, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -2836,54 +2643,54 @@ BEGIN WHEN @CurrentBackupType = 'LOG' THEN 'BACKUP LOG ' + QUOTENAME(@CurrentDatabaseName) END - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ' READ_WRITE_FILEGROUPS' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ' READ_WRITE_FILEGROUPS' - SET @CurrentCommand03 = @CurrentCommand03 + ' TO' + SET @CurrentCommand03 += ' TO' - SELECT @CurrentCommand03 = @CurrentCommand03 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand03 += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SET @CurrentCommand03 = @CurrentCommand03 + ' MIRROR TO' + SET @CurrentCommand03 += ' MIRROR TO' - SELECT @CurrentCommand03 = @CurrentCommand03 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand03 += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 1 ORDER BY FilePath ASC END - SET @CurrentCommand03 = @CurrentCommand03 + ' WITH ' - IF @CheckSum = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand03 = @CurrentCommand03 + 'NO_CHECKSUM' + SET @CurrentCommand03 += ' WITH ' + IF @CheckSum = 'Y' SET @CurrentCommand03 += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand03 += 'NO_CHECKSUM' IF @Version >= 10 BEGIN - SET @CurrentCommand03 = @CurrentCommand03 + CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND @Version >= 13 AND @CurrentMaxTransferSize > 65536)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END + SET @CurrentCommand03 += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND @Version >= 13 AND @CurrentMaxTransferSize > 65536)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END END - IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 = @CurrentCommand03 + ', DIFFERENTIAL' + IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 += ', DIFFERENTIAL' IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SET @CurrentCommand03 = @CurrentCommand03 + ', FORMAT' + SET @CurrentCommand03 += ', FORMAT' END - IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', COPY_ONLY' - IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 = @CurrentCommand03 + ', NORECOVERY' - IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', INIT' - IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', FORMAT' - IF @BlockSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) - IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar) - IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' - IF @Encrypt = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', ENCRYPTION (ALGORITHM = ' + UPPER(@EncryptionAlgorithm) + ', ' - IF @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + 'SERVER CERTIFICATE = ' + QUOTENAME(@ServerCertificate) - IF @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + 'SERVER ASYMMETRIC KEY = ' + QUOTENAME(@ServerAsymmetricKey) - IF @Encrypt = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ')' - IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' + IF @CopyOnly = 'Y' SET @CurrentCommand03 += ', COPY_ONLY' + IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 += ', NORECOVERY' + IF @Init = 'Y' SET @CurrentCommand03 += ', INIT' + IF @Format = 'Y' SET @CurrentCommand03 += ', FORMAT' + IF @BlockSize IS NOT NULL SET @CurrentCommand03 += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) + IF @BufferCount IS NOT NULL SET @CurrentCommand03 += ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) + IF @Description IS NOT NULL SET @CurrentCommand03 += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' + IF @Encrypt = 'Y' SET @CurrentCommand03 += ', ENCRYPTION (ALGORITHM = ' + UPPER(@EncryptionAlgorithm) + ', ' + IF @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL SET @CurrentCommand03 += 'SERVER CERTIFICATE = ' + QUOTENAME(@ServerCertificate) + IF @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL SET @CurrentCommand03 += 'SERVER ASYMMETRIC KEY = ' + QUOTENAME(@ServerAsymmetricKey) + IF @Encrypt = 'Y' SET @CurrentCommand03 += ')' + IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand03 += ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' END IF @BackupSoftware = 'LITESPEED' @@ -2898,40 +2705,40 @@ BEGIN WHEN @CurrentBackupType = 'LOG' THEN 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_backup_log @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' END - SELECT @CurrentCommand03 = @CurrentCommand03 + ', @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand03 += ', @filename = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SELECT @CurrentCommand03 = @CurrentCommand03 + ', @mirror = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand03 += ', @mirror = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 1 ORDER BY FilePath ASC END - SET @CurrentCommand03 = @CurrentCommand03 + ', @with = ''' - IF @CheckSum = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand03 = @CurrentCommand03 + 'NO_CHECKSUM' - IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 = @CurrentCommand03 + ', DIFFERENTIAL' - IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', COPY_ONLY' - IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 = @CurrentCommand03 + ', NORECOVERY' - IF @BlockSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) - SET @CurrentCommand03 = @CurrentCommand03 + '''' - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ', @read_write_filegroups = 1' - IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) - IF @AdaptiveCompression IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @adaptivecompression = ''' + CASE WHEN @AdaptiveCompression = 'SIZE' THEN 'Size' WHEN @AdaptiveCompression = 'SPEED' THEN 'Speed' END + '''' - IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @buffercount = ' + CAST(@BufferCount AS nvarchar) - IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @maxtransfersize = ' + CAST(@CurrentMaxTransferSize AS nvarchar) - IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @threads = ' + CAST(@Threads AS nvarchar) - IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @init = 1' - IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @format = 1' - IF @Throttle IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @throttle = ' + CAST(@Throttle AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' - IF @ObjectLevelRecoveryMap = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @olrmap = 1' - - IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @cryptlevel = ' + CASE + SET @CurrentCommand03 += ', @with = ''' + IF @CheckSum = 'Y' SET @CurrentCommand03 += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand03 += 'NO_CHECKSUM' + IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 += ', DIFFERENTIAL' + IF @CopyOnly = 'Y' SET @CurrentCommand03 += ', COPY_ONLY' + IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 += ', NORECOVERY' + IF @BlockSize IS NOT NULL SET @CurrentCommand03 += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) + SET @CurrentCommand03 += '''' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ', @read_write_filegroups = 1' + IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 += ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) + IF @AdaptiveCompression IS NOT NULL SET @CurrentCommand03 += ', @adaptivecompression = ''' + CASE WHEN @AdaptiveCompression = 'SIZE' THEN 'Size' WHEN @AdaptiveCompression = 'SPEED' THEN 'Speed' END + '''' + IF @BufferCount IS NOT NULL SET @CurrentCommand03 += ', @buffercount = ' + CAST(@BufferCount AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 += ', @maxtransfersize = ' + CAST(@CurrentMaxTransferSize AS nvarchar) + IF @Threads IS NOT NULL SET @CurrentCommand03 += ', @threads = ' + CAST(@Threads AS nvarchar) + IF @Init = 'Y' SET @CurrentCommand03 += ', @init = 1' + IF @Format = 'Y' SET @CurrentCommand03 += ', @format = 1' + IF @Throttle IS NOT NULL SET @CurrentCommand03 += ', @throttle = ' + CAST(@Throttle AS nvarchar) + IF @Description IS NOT NULL SET @CurrentCommand03 += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' + IF @ObjectLevelRecoveryMap = 'Y' SET @CurrentCommand03 += ', @olrmap = 1' + + IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 += ', @cryptlevel = ' + CASE WHEN @EncryptionAlgorithm = 'RC2_40' THEN '0' WHEN @EncryptionAlgorithm = 'RC2_56' THEN '1' WHEN @EncryptionAlgorithm = 'RC2_112' THEN '2' @@ -2943,8 +2750,8 @@ BEGIN WHEN @EncryptionAlgorithm = 'AES_256' THEN '8' END - IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand03 = @CurrentCommand03 + ' IF @ReturnCode <> 0 RAISERROR(''Error performing LiteSpeed backup.'', 16, 1)' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand03 += ' IF @ReturnCode <> 0 RAISERROR(''Error performing LiteSpeed backup.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -2956,40 +2763,40 @@ BEGIN WHEN @CurrentBackupType = 'LOG' THEN 'BACKUP LOG ' + QUOTENAME(@CurrentDatabaseName) END - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ' READ_WRITE_FILEGROUPS' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ' READ_WRITE_FILEGROUPS' - SET @CurrentCommand03 = @CurrentCommand03 + ' TO' + SET @CurrentCommand03 += ' TO' - SELECT @CurrentCommand03 = @CurrentCommand03 + ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand03 += ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC - SET @CurrentCommand03 = @CurrentCommand03 + ' WITH ' + SET @CurrentCommand03 += ' WITH ' IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SET @CurrentCommand03 = @CurrentCommand03 + ' MIRRORFILE' + ' = N''' + REPLACE((SELECT FilePath FROM @CurrentFiles WHERE Mirror = 1),'''','''''') + ''', ' + SET @CurrentCommand03 += ' MIRRORFILE' + ' = N''' + REPLACE((SELECT FilePath FROM @CurrentFiles WHERE Mirror = 1),'''','''''') + ''', ' END - IF @CheckSum = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand03 = @CurrentCommand03 + 'NO_CHECKSUM' - IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 = @CurrentCommand03 + ', DIFFERENTIAL' - IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', COPY_ONLY' - IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 = @CurrentCommand03 + ', NORECOVERY' - IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', INIT' - IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', FORMAT' - IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', COMPRESSION = ' + CAST(@CompressionLevel AS nvarchar) - IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', THREADCOUNT = ' + CAST(@Threads AS nvarchar) - IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' - - IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', KEYSIZE = ' + CASE + IF @CheckSum = 'Y' SET @CurrentCommand03 += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand03 += 'NO_CHECKSUM' + IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 += ', DIFFERENTIAL' + IF @CopyOnly = 'Y' SET @CurrentCommand03 += ', COPY_ONLY' + IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 += ', NORECOVERY' + IF @Init = 'Y' SET @CurrentCommand03 += ', INIT' + IF @Format = 'Y' SET @CurrentCommand03 += ', FORMAT' + IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 += ', COMPRESSION = ' + CAST(@CompressionLevel AS nvarchar) + IF @Threads IS NOT NULL SET @CurrentCommand03 += ', THREADCOUNT = ' + CAST(@Threads AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) + IF @Description IS NOT NULL SET @CurrentCommand03 += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' + + IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 += ', KEYSIZE = ' + CASE WHEN @EncryptionAlgorithm = 'AES_128' THEN '128' WHEN @EncryptionAlgorithm = 'AES_256' THEN '256' END - IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 += ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand03,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLBackup backup.'', 16, 1)' END @@ -2999,32 +2806,32 @@ BEGIN SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_backup @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' - SELECT @CurrentCommand03 = @CurrentCommand03 + ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand03 += ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC - SELECT @CurrentCommand03 = @CurrentCommand03 + ', @mirrorfile = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand03 += ', @mirrorfile = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 1 ORDER BY FilePath ASC - SET @CurrentCommand03 = @CurrentCommand03 + ', @backuptype = ' + CASE WHEN @CurrentBackupType = 'FULL' THEN '''Full''' WHEN @CurrentBackupType = 'DIFF' THEN '''Differential''' WHEN @CurrentBackupType = 'LOG' THEN '''Log''' END - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ', @readwritefilegroups = 1' - SET @CurrentCommand03 = @CurrentCommand03 + ', @checksum = ' + CASE WHEN @CheckSum = 'Y' THEN '1' WHEN @CheckSum = 'N' THEN '0' END - SET @CurrentCommand03 = @CurrentCommand03 + ', @copyonly = ' + CASE WHEN @CopyOnly = 'Y' THEN '1' WHEN @CopyOnly = 'N' THEN '0' END - IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) - IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @threads = ' + CAST(@Threads AS nvarchar) - IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @overwrite = 1' - IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' + SET @CurrentCommand03 += ', @backuptype = ' + CASE WHEN @CurrentBackupType = 'FULL' THEN '''Full''' WHEN @CurrentBackupType = 'DIFF' THEN '''Differential''' WHEN @CurrentBackupType = 'LOG' THEN '''Log''' END + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ', @readwritefilegroups = 1' + SET @CurrentCommand03 += ', @checksum = ' + CASE WHEN @CheckSum = 'Y' THEN '1' WHEN @CheckSum = 'N' THEN '0' END + SET @CurrentCommand03 += ', @copyonly = ' + CASE WHEN @CopyOnly = 'Y' THEN '1' WHEN @CopyOnly = 'N' THEN '0' END + IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 += ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) + IF @Threads IS NOT NULL SET @CurrentCommand03 += ', @threads = ' + CAST(@Threads AS nvarchar) + IF @Init = 'Y' SET @CurrentCommand03 += ', @overwrite = 1' + IF @Description IS NOT NULL SET @CurrentCommand03 += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' - IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @encryptiontype = N''' + CASE + IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 += ', @encryptiontype = N''' + CASE WHEN @EncryptionAlgorithm = 'AES_128' THEN 'AES128' WHEN @EncryptionAlgorithm = 'AES_256' THEN 'AES256' END + '''' - IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @encryptedbackuppassword = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand03 = @CurrentCommand03 + ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 += ', @encryptedbackuppassword = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand03 += ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' @@ -3033,41 +2840,41 @@ BEGIN SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.emc_run_backup ''' - SET @CurrentCommand03 = @CurrentCommand03 + ' -c ' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar) END + SET @CurrentCommand03 += ' -c ' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar) END - SET @CurrentCommand03 = @CurrentCommand03 + ' -l ' + CASE + SET @CurrentCommand03 += ' -l ' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'full' WHEN @CurrentBackupType = 'DIFF' THEN 'diff' WHEN @CurrentBackupType = 'LOG' THEN 'incr' END - IF @NoRecovery = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ' -H' + IF @NoRecovery = 'Y' SET @CurrentCommand03 += ' -H' - IF @CleanupTime IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -y +' + CAST(@CleanupTime/24 + CASE WHEN @CleanupTime%24 > 0 THEN 1 ELSE 0 END AS nvarchar) + 'd' + IF @CleanupTime IS NOT NULL SET @CurrentCommand03 += ' -y +' + CAST(@CleanupTime/24 + CASE WHEN @CleanupTime%24 > 0 THEN 1 ELSE 0 END AS nvarchar) + 'd' - IF @CheckSum = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ' -k' + IF @CheckSum = 'Y' SET @CurrentCommand03 += ' -k' - SET @CurrentCommand03 = @CurrentCommand03 + ' -S ' + CAST(@CurrentNumberOfFiles AS nvarchar) + SET @CurrentCommand03 += ' -S ' + CAST(@CurrentNumberOfFiles AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -b "' + REPLACE(@Description,'''','''''') + '"' + IF @Description IS NOT NULL SET @CurrentCommand03 += ' -b "' + REPLACE(@Description,'''','''''') + '"' - IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -O "BUFFERCOUNT=' + CAST(@BufferCount AS nvarchar) + '"' + IF @BufferCount IS NOT NULL SET @CurrentCommand03 += ' -O "BUFFERCOUNT=' + CAST(@BufferCount AS nvarchar) + '"' - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ' -O "READ_WRITE_FILEGROUPS"' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ' -O "READ_WRITE_FILEGROUPS"' - IF @DataDomainBoostHost IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_HOST=' + REPLACE(@DataDomainBoostHost,'''','''''') + '"' - IF @DataDomainBoostUser IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_USER=' + REPLACE(@DataDomainBoostUser,'''','''''') + '"' - IF @DataDomainBoostDevicePath IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DEVICE_PATH=' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '"' - IF @DataDomainBoostLockboxPath IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_LOCKBOX_PATH=' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '"' - SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_SKIP_NON_BACKUPABLE_STATE_DB=TRUE"' - IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_COPY_ONLY=TRUE"' + IF @DataDomainBoostHost IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DD_HOST=' + REPLACE(@DataDomainBoostHost,'''','''''') + '"' + IF @DataDomainBoostUser IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DD_USER=' + REPLACE(@DataDomainBoostUser,'''','''''') + '"' + IF @DataDomainBoostDevicePath IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DEVICE_PATH=' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '"' + IF @DataDomainBoostLockboxPath IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DD_LOCKBOX_PATH=' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '"' + SET @CurrentCommand03 += ' -a "NSR_SKIP_NON_BACKUPABLE_STATE_DB=TRUE"' + IF @CopyOnly = 'Y' SET @CurrentCommand03 += ' -a "NSR_COPY_ONLY=TRUE"' - IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand03 = @CurrentCommand03 + ' "MSSQL' + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' - IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar) + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' + IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand03 += ' "MSSQL' + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' + IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand03 += ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar) + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' - SET @CurrentCommand03 = @CurrentCommand03 + '''' + SET @CurrentCommand03 += '''' - SET @CurrentCommand03 = @CurrentCommand03 + ' IF @ReturnCode <> 0 RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' + SET @CurrentCommand03 += ' IF @ReturnCode <> 0 RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' END EXECUTE @CurrentCommandOutput03 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand03, @CommandType = @CurrentCommandType03, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -3098,15 +2905,15 @@ BEGIN SET @CurrentCommand04 = 'RESTORE VERIFYONLY FROM' - SELECT @CurrentCommand04 = @CurrentCommand04 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand04 += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 = @CurrentCommand04 + ' WITH ' - IF @CheckSum = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand04 = @CurrentCommand04 + 'NO_CHECKSUM' - IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand04 = @CurrentCommand04 + ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' + SET @CurrentCommand04 += ' WITH ' + IF @CheckSum = 'Y' SET @CurrentCommand04 += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand04 += 'NO_CHECKSUM' + IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand04 += ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' END IF @BackupSoftware = 'LITESPEED' @@ -3115,18 +2922,18 @@ BEGIN SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_restore_verifyonly' - SELECT @CurrentCommand04 = @CurrentCommand04 + ' @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand04 += ' @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 = @CurrentCommand04 + ', @with = ''' - IF @CheckSum = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand04 = @CurrentCommand04 + 'NO_CHECKSUM' - SET @CurrentCommand04 = @CurrentCommand04 + '''' - IF @EncryptionKey IS NOT NULL SET @CurrentCommand04 = @CurrentCommand04 + ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand04 += ', @with = ''' + IF @CheckSum = 'Y' SET @CurrentCommand04 += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand04 += 'NO_CHECKSUM' + SET @CurrentCommand04 += '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand04 += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand04 = @CurrentCommand04 + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying LiteSpeed backup.'', 16, 1)' + SET @CurrentCommand04 += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying LiteSpeed backup.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -3135,15 +2942,15 @@ BEGIN SET @CurrentCommand04 = 'RESTORE VERIFYONLY FROM' - SELECT @CurrentCommand04 = @CurrentCommand04 + ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand04 += ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 = @CurrentCommand04 + ' WITH ' - IF @CheckSum = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand04 = @CurrentCommand04 + 'NO_CHECKSUM' - IF @EncryptionKey IS NOT NULL SET @CurrentCommand04 = @CurrentCommand04 + ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand04 += ' WITH ' + IF @CheckSum = 'Y' SET @CurrentCommand04 += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand04 += 'NO_CHECKSUM' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand04 += ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand04,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLBackup backup.'', 16, 1)' END @@ -3154,12 +2961,12 @@ BEGIN SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_verify @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' - SELECT @CurrentCommand04 = @CurrentCommand04 + ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand04 += ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 = @CurrentCommand04 + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' + SET @CurrentCommand04 += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' END EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -3186,7 +2993,7 @@ BEGIN IF @CleanupMode = 'AFTER_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@CleanupTime),GETDATE()), 0 + SELECT DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 0 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -3202,7 +3009,7 @@ BEGIN IF @MirrorCleanupMode = 'AFTER_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@MirrorCleanupTime),GETDATE()), 1 + SELECT DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 1 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -3249,21 +3056,21 @@ BEGIN BEGIN SET @CurrentCommandType05 = 'xp_slssqlmaint' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN SET @CurrentCommandType05 = 'sqbutility' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' + SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN SET @CurrentCommandType05 = 'xp_ss_delete' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -3301,7 +3108,7 @@ BEGIN IF @DatabasesInParallel = 'Y' BEGIN UPDATE dbo.QueueDatabase - SET DatabaseEndTime = GETDATE() + SET DatabaseEndTime = SYSDATETIME() WHERE QueueID = @QueueID AND DatabaseName = @CurrentDatabaseName END @@ -3356,7 +3163,6 @@ BEGIN SET @CurrentModifiedExtentPageCount = NULL SET @CurrentCommand03 = NULL - SET @CurrentCommand06 = NULL SET @CurrentCommand07 = NULL SET @CurrentCommandOutput03 = NULL @@ -3376,7 +3182,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- Logging: - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 603cfc8c..133ec756 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-03 23:04:49 //-- + --// Version: 2020-01-05 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -48,18 +48,16 @@ BEGIN DECLARE @ErrorMessage nvarchar(max) DECLARE @Severity int - DECLARE @StartTime datetime - DECLARE @SchemaName nvarchar(max) - DECLARE @ObjectName nvarchar(max) - DECLARE @VersionTimestamp nvarchar(max) + DECLARE @StartTime datetime2 = SYSDATETIME() + DECLARE @SchemaName nvarchar(max) = OBJECT_SCHEMA_NAME(@@PROCID) + DECLARE @ObjectName nvarchar(max) = OBJECT_NAME(@@PROCID) + DECLARE @VersionTimestamp nvarchar(max) = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) DECLARE @Parameters nvarchar(max) - DECLARE @Version numeric(18,10) DECLARE @HostPlatform nvarchar(max) - DECLARE @AmazonRDS bit DECLARE @QueueID int - DECLARE @QueueStartTime datetime + DECLARE @QueueStartTime datetime2 DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -114,15 +112,20 @@ BEGIN DECLARE @CurrentCommandType08 nvarchar(max) DECLARE @CurrentCommandType09 nvarchar(max) + DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, + [Message] nvarchar(max)) + + DECLARE @CurrentMessage nvarchar(max) + DECLARE @tmpDatabases TABLE (ID int IDENTITY, DatabaseName nvarchar(max), DatabaseType nvarchar(max), AvailabilityGroup bit, [Snapshot] bit, StartPosition int, - LastCommandTime datetime, + LastCommandTime datetime2, DatabaseSize bigint, - LastGoodCheckDbTime datetime, + LastGoodCheckDbTime datetime2, [Order] int, Selected bit, Completed bit, @@ -180,17 +183,12 @@ BEGIN DECLARE @SelectedCheckCommands TABLE (CheckCommand nvarchar(max)) - DECLARE @Error int - DECLARE @ReturnCode int - - DECLARE @EmptyLine nvarchar(max) - - SET @Error = 0 - SET @ReturnCode = 0 + DECLARE @Error int = 0 + DECLARE @ReturnCode int = 0 - SET @EmptyLine = CHAR(9) + DECLARE @EmptyLine nvarchar(max) = CHAR(9) - SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) + DECLARE @Version numeric(18,10) = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) IF @Version >= 14 BEGIN @@ -202,36 +200,31 @@ BEGIN SET @HostPlatform = 'Windows' END - SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartTime = GETDATE() - SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) - SET @ObjectName = OBJECT_NAME(@@PROCID) - SET @VersionTimestamp = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) - SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @CheckCommands = ' + ISNULL('''' + REPLACE(@CheckCommands,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @PhysicalOnly = ' + ISNULL('''' + REPLACE(@PhysicalOnly,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @NoIndex = ' + ISNULL('''' + REPLACE(@NoIndex,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ExtendedLogicalChecks = ' + ISNULL('''' + REPLACE(@ExtendedLogicalChecks,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @TabLock = ' + ISNULL('''' + REPLACE(@TabLock,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FileGroups = ' + ISNULL('''' + REPLACE(@FileGroups,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Objects = ' + ISNULL('''' + REPLACE(@Objects,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @AvailabilityGroupReplicas = ' + ISNULL('''' + REPLACE(@AvailabilityGroupReplicas,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @Parameters += ', @CheckCommands = ' + ISNULL('''' + REPLACE(@CheckCommands,'''','''''') + '''','NULL') + SET @Parameters += ', @PhysicalOnly = ' + ISNULL('''' + REPLACE(@PhysicalOnly,'''','''''') + '''','NULL') + SET @Parameters += ', @NoIndex = ' + ISNULL('''' + REPLACE(@NoIndex,'''','''''') + '''','NULL') + SET @Parameters += ', @ExtendedLogicalChecks = ' + ISNULL('''' + REPLACE(@ExtendedLogicalChecks,'''','''''') + '''','NULL') + SET @Parameters += ', @TabLock = ' + ISNULL('''' + REPLACE(@TabLock,'''','''''') + '''','NULL') + SET @Parameters += ', @FileGroups = ' + ISNULL('''' + REPLACE(@FileGroups,'''','''''') + '''','NULL') + SET @Parameters += ', @Objects = ' + ISNULL('''' + REPLACE(@Objects,'''','''''') + '''','NULL') + SET @Parameters += ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') + SET @Parameters += ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') + SET @Parameters += ', @AvailabilityGroupReplicas = ' + ISNULL('''' + REPLACE(@AvailabilityGroupReplicas,'''','''''') + '''','NULL') + SET @Parameters += ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') + SET @Parameters += ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') + SET @Parameters += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') + SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') + SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') + SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') + SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -268,80 +261,56 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' END IF @@TRANCOUNT <> 0 BEGIN - SET @ErrorMessage = 'The transaction count is not 0.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - END - - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO Logging + INSERT INTO @Errors ([Message]) + SELECT 'The transaction count is not 0.' END ---------------------------------------------------------------------------------------------------- @@ -468,10 +437,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Databases is not supported.' END ---------------------------------------------------------------------------------------------------- @@ -565,26 +532,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.' END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' END ---------------------------------------------------------------------------------------------------- @@ -722,147 +683,110 @@ BEGIN IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) OR EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) OR NOT EXISTS (SELECT * FROM @SelectedCheckCommands) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG'))) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE'))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CheckCommands is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CheckCommands is not supported.' END IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @PhysicalOnly is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @PhysicalOnly is not supported.' END IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @NoIndex is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @NoIndex is not supported.' END IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL OR (@ExtendedLogicalChecks = 'Y' AND NOT @Version >= 10) OR (@PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y') BEGIN - SET @ErrorMessage = 'The value for the parameter @ExtendedLogicalChecks is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @ExtendedLogicalChecks is not supported.' END IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @TabLock is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @TabLock is not supported.' END IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) OR (@FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups)) OR (@FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP')) BEGIN - SET @ErrorMessage = 'The value for the parameter @FileGroups is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FileGroups is not supported.' END IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) OR (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) OR (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Objects is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Objects is not supported.' END IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MaxDOP is not supported.' END IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupReplicas is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @AvailabilityGroupReplicas is not supported.' END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Updateability is not supported.' END IF @TimeLimit < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @TimeLimit is not supported.' END IF @LockTimeout < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LockTimeout is not supported.' END IF @LockMessageSeverity NOT IN(10,16) BEGIN - SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.' END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.' END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.' END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LogToTable is not supported.' END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Execute is not supported.' END - IF @Error <> 0 + IF EXISTS(SELECT * FROM @Errors) BEGIN - SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - SET @ReturnCode = @Error - GOTO Logging + INSERT INTO @Errors ([Message]) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.' END ---------------------------------------------------------------------------------------------------- @@ -876,10 +800,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -889,10 +811,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -902,10 +822,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -915,10 +833,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -929,10 +845,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -943,10 +857,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END ---------------------------------------------------------------------------------------------------- @@ -955,10 +867,36 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + END + + ---------------------------------------------------------------------------------------------------- + --// Raise errors //-- + ---------------------------------------------------------------------------------------------------- + + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + + OPEN ErrorCursor + + FETCH ErrorCursor INTO @CurrentMessage + + WHILE @@FETCH_STATUS = 0 + BEGIN + RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT + + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage + END + + CLOSE ErrorCursor + + DEALLOCATE ErrorCursor + + IF EXISTS (SELECT * FROM @Errors) + BEGIN + SET @ReturnCode = 50000 + GOTO Logging END ---------------------------------------------------------------------------------------------------- @@ -975,7 +913,7 @@ BEGIN IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') BEGIN UPDATE tmpDatabases - SET LastGoodCheckDbTime = NULLIF(CAST(DATABASEPROPERTYEX (DatabaseName,'LastGoodCheckDbTime') AS datetime),'1900-01-01 00:00:00.000') + SET LastGoodCheckDbTime = NULLIF(CAST(DATABASEPROPERTYEX (DatabaseName,'LastGoodCheckDbTime') AS datetime2),'1900-01-01 00:00:00.000') FROM @tmpDatabases tmpDatabases END @@ -1130,7 +1068,7 @@ BEGIN BEGIN TRANSACTION UPDATE [Queue] - SET QueueStartTime = GETDATE(), + SET QueueStartTime = SYSDATETIME(), SessionID = @@SPID, RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID) @@ -1210,7 +1148,7 @@ BEGIN AND NOT EXISTS (SELECT * FROM sys.dm_exec_requests WHERE session_id = QueueDatabase.SessionID AND request_id = QueueDatabase.RequestID AND start_time = QueueDatabase.RequestStartTime) UPDATE QueueDatabase - SET DatabaseStartTime = GETDATE(), + SET DatabaseStartTime = SYSDATETIME(), DatabaseEndTime = NULL, SessionID = @@SPID, RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), @@ -1289,7 +1227,7 @@ BEGIN WHERE database_id = DB_ID(@CurrentDatabaseName) END - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) @@ -1351,20 +1289,20 @@ BEGIN BEGIN -- Check database - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKDB') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKDB') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType01 = 'DBCC_CHECKDB' SET @CurrentCommand01 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand01 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand01 = @CurrentCommand01 + 'DBCC CHECKDB (' + QUOTENAME(@CurrentDatabaseName) - IF @NoIndex = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', NOINDEX' - SET @CurrentCommand01 = @CurrentCommand01 + ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'N' SET @CurrentCommand01 = @CurrentCommand01 + ', DATA_PURITY' - IF @PhysicalOnly = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', PHYSICAL_ONLY' - IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', EXTENDED_LOGICAL_CHECKS' - IF @TabLock = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand01 = @CurrentCommand01 + ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + SET @CurrentCommand01 += 'DBCC CHECKDB (' + QUOTENAME(@CurrentDatabaseName) + IF @NoIndex = 'Y' SET @CurrentCommand01 += ', NOINDEX' + SET @CurrentCommand01 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @PhysicalOnly = 'N' SET @CurrentCommand01 += ', DATA_PURITY' + IF @PhysicalOnly = 'Y' SET @CurrentCommand01 += ', PHYSICAL_ONLY' + IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand01 += ', EXTENDED_LOGICAL_CHECKS' + IF @TabLock = 'Y' SET @CurrentCommand01 += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand01 += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -1373,7 +1311,7 @@ BEGIN END -- Check filegroups - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand02 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' @@ -1438,7 +1376,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + WHILE (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SELECT TOP 1 @CurrentFGID = ID, @CurrentFileGroupID = FileGroupID, @@ -1456,7 +1394,7 @@ BEGIN -- Does the filegroup exist? SET @CurrentCommand03 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM sys.filegroups filegroups WHERE [type] <> ''FX'' AND filegroups.data_space_id = @ParamFileGroupID AND filegroups.[name] = @ParamFileGroupName) BEGIN SET @ParamFileGroupExists = 1 END' + SET @CurrentCommand03 += 'IF EXISTS(SELECT * FROM sys.filegroups filegroups WHERE [type] <> ''FX'' AND filegroups.data_space_id = @ParamFileGroupID AND filegroups.[name] = @ParamFileGroupName) BEGIN SET @ParamFileGroupExists = 1 END' BEGIN TRY EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand03, @params = N'@ParamFileGroupID int, @ParamFileGroupName sysname, @ParamFileGroupExists bit OUTPUT', @ParamFileGroupID = @CurrentFileGroupID, @ParamFileGroupName = @CurrentFileGroupName, @ParamFileGroupExists = @CurrentFileGroupExists OUTPUT @@ -1481,12 +1419,12 @@ BEGIN SET @CurrentCommand04 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand04 = @CurrentCommand04 + 'DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) - IF @NoIndex = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + ', NOINDEX' - SET @CurrentCommand04 = @CurrentCommand04 + ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + ', PHYSICAL_ONLY' - IF @TabLock = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand04 = @CurrentCommand04 + ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + SET @CurrentCommand04 += 'DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) + IF @NoIndex = 'Y' SET @CurrentCommand04 += ', NOINDEX' + SET @CurrentCommand04 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @PhysicalOnly = 'Y' SET @CurrentCommand04 += ', PHYSICAL_ONLY' + IF @TabLock = 'Y' SET @CurrentCommand04 += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand04 += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -1515,15 +1453,15 @@ BEGIN END -- Check disk space allocation structures - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKALLOC') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKALLOC') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType05 = 'DBCC_CHECKALLOC' SET @CurrentCommand05 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand05 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand05 = @CurrentCommand05 + 'DBCC CHECKALLOC (' + QUOTENAME(@CurrentDatabaseName) - SET @CurrentCommand05 = @CurrentCommand05 + ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @TabLock = 'Y' SET @CurrentCommand05 = @CurrentCommand05 + ', TABLOCK' + SET @CurrentCommand05 += 'DBCC CHECKALLOC (' + QUOTENAME(@CurrentDatabaseName) + SET @CurrentCommand05 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @TabLock = 'Y' SET @CurrentCommand05 += ', TABLOCK' EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -1532,7 +1470,7 @@ BEGIN END -- Check objects - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand06 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' @@ -1598,7 +1536,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + WHILE (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SELECT TOP 1 @CurrentOID = ID, @CurrentSchemaID = SchemaID, @@ -1619,7 +1557,7 @@ BEGIN -- Does the object exist? SET @CurrentCommand07 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand07 = @CurrentCommand07 + 'IF EXISTS(SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType) BEGIN SET @ParamObjectExists = 1 END' + SET @CurrentCommand07 += 'IF EXISTS(SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType) BEGIN SET @ParamObjectExists = 1 END' BEGIN TRY EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand07, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamObjectExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamObjectExists = @CurrentObjectExists OUTPUT @@ -1644,14 +1582,14 @@ BEGIN SET @CurrentCommand08 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand08 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand08 = @CurrentCommand08 + 'DBCC CHECKTABLE (''' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + '''' - IF @NoIndex = 'Y' SET @CurrentCommand08 = @CurrentCommand08 + ', NOINDEX' - SET @CurrentCommand08 = @CurrentCommand08 + ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'N' SET @CurrentCommand08 = @CurrentCommand08 + ', DATA_PURITY' - IF @PhysicalOnly = 'Y' SET @CurrentCommand08 = @CurrentCommand08 + ', PHYSICAL_ONLY' - IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand08 = @CurrentCommand08 + ', EXTENDED_LOGICAL_CHECKS' - IF @TabLock = 'Y' SET @CurrentCommand08 = @CurrentCommand08 + ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand08 = @CurrentCommand08 + ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + SET @CurrentCommand08 += 'DBCC CHECKTABLE (''' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + '''' + IF @NoIndex = 'Y' SET @CurrentCommand08 += ', NOINDEX' + SET @CurrentCommand08 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @PhysicalOnly = 'N' SET @CurrentCommand08 += ', DATA_PURITY' + IF @PhysicalOnly = 'Y' SET @CurrentCommand08 += ', PHYSICAL_ONLY' + IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand08 += ', EXTENDED_LOGICAL_CHECKS' + IF @TabLock = 'Y' SET @CurrentCommand08 += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand08 += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) EXECUTE @CurrentCommandOutput08 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand08, @CommandType = @CurrentCommandType08, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -1683,14 +1621,14 @@ BEGIN END -- Check catalog - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType09 = 'DBCC_CHECKCATALOG' SET @CurrentCommand09 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand09 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand09 = @CurrentCommand09 + 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) - SET @CurrentCommand09 = @CurrentCommand09 + ') WITH NO_INFOMSGS' + SET @CurrentCommand09 += 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) + SET @CurrentCommand09 += ') WITH NO_INFOMSGS' EXECUTE @CurrentCommandOutput09 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand09, @CommandType = @CurrentCommandType09, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -1712,7 +1650,7 @@ BEGIN IF @DatabasesInParallel = 'Y' BEGIN UPDATE dbo.QueueDatabase - SET DatabaseEndTime = GETDATE() + SET DatabaseEndTime = SYSDATETIME() WHERE QueueID = @QueueID AND DatabaseName = @CurrentDatabaseName END @@ -1768,7 +1706,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- Logging: - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 62255738..55735ef5 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-03 23:04:49 //-- + --// Version: 2020-01-05 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -66,20 +66,18 @@ BEGIN DECLARE @ErrorMessage nvarchar(max) DECLARE @Severity int - DECLARE @StartTime datetime - DECLARE @SchemaName nvarchar(max) - DECLARE @ObjectName nvarchar(max) - DECLARE @VersionTimestamp nvarchar(max) + DECLARE @StartTime datetime2 = SYSDATETIME() + DECLARE @SchemaName nvarchar(max) = OBJECT_SCHEMA_NAME(@@PROCID) + DECLARE @ObjectName nvarchar(max) = OBJECT_NAME(@@PROCID) + DECLARE @VersionTimestamp nvarchar(max) = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) DECLARE @Parameters nvarchar(max) - DECLARE @Version numeric(18,10) DECLARE @HostPlatform nvarchar(max) - DECLARE @AmazonRDS bit DECLARE @PartitionLevelStatistics bit DECLARE @QueueID int - DECLARE @QueueStartTime datetime + DECLARE @QueueStartTime datetime2 DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -117,6 +115,11 @@ BEGIN DECLARE @CurrentExtendedInfo06 xml DECLARE @CurrentExtendedInfo07 xml + DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, + [Message] nvarchar(max)) + + DECLARE @CurrentMessage nvarchar(max) + DECLARE @CurrentIxID int DECLARE @CurrentIxOrder int DECLARE @CurrentSchemaID int @@ -157,7 +160,7 @@ BEGIN DECLARE @CurrentUpdateStatistics nvarchar(max) DECLARE @CurrentStatisticsSample int DECLARE @CurrentStatisticsResample nvarchar(max) - DECLARE @CurrentDelay datetime + DECLARE @CurrentDelay datetime2 DECLARE @tmpDatabases TABLE (ID int IDENTITY, DatabaseName nvarchar(max), @@ -255,17 +258,12 @@ BEGIN DECLARE @CurrentUpdateStatisticsArgument nvarchar(max) DECLARE @CurrentUpdateStatisticsWithClause nvarchar(max) - DECLARE @Error int - DECLARE @ReturnCode int - - DECLARE @EmptyLine nvarchar(max) + DECLARE @Error int = 0 + DECLARE @ReturnCode int = 0 - SET @Error = 0 - SET @ReturnCode = 0 + DECLARE @EmptyLine nvarchar(max) = CHAR(9) - SET @EmptyLine = CHAR(9) - - SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) + DECLARE @Version numeric(18,10) = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) IF @Version >= 14 BEGIN @@ -277,50 +275,45 @@ BEGIN SET @HostPlatform = 'Windows' END - SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartTime = GETDATE() - SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) - SET @ObjectName = OBJECT_NAME(@@PROCID) - SET @VersionTimestamp = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) - SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FragmentationLow = ' + ISNULL('''' + REPLACE(@FragmentationLow,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FragmentationMedium = ' + ISNULL('''' + REPLACE(@FragmentationMedium,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FragmentationHigh = ' + ISNULL('''' + REPLACE(@FragmentationHigh,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FragmentationLevel1 = ' + ISNULL(CAST(@FragmentationLevel1 AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @FragmentationLevel2 = ' + ISNULL(CAST(@FragmentationLevel2 AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @MinNumberOfPages = ' + ISNULL(CAST(@MinNumberOfPages AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @MaxNumberOfPages = ' + ISNULL(CAST(@MaxNumberOfPages AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @SortInTempdb = ' + ISNULL('''' + REPLACE(@SortInTempdb,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @PadIndex = ' + ISNULL('''' + REPLACE(@PadIndex,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @LOBCompaction = ' + ISNULL('''' + REPLACE(@LOBCompaction,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @UpdateStatistics = ' + ISNULL('''' + REPLACE(@UpdateStatistics,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @StatisticsModificationLevel = ' + ISNULL(CAST(@StatisticsModificationLevel AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @StatisticsResample = ' + ISNULL('''' + REPLACE(@StatisticsResample,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @PartitionLevel = ' + ISNULL('''' + REPLACE(@PartitionLevel,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @MSShippedObjects = ' + ISNULL('''' + REPLACE(@MSShippedObjects,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Indexes = ' + ISNULL('''' + REPLACE(@Indexes,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @WaitAtLowPriorityAbortAfterWait = ' + ISNULL('''' + REPLACE(@WaitAtLowPriorityAbortAfterWait,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Resumable = ' + ISNULL('''' + REPLACE(@Resumable,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @Parameters += ', @FragmentationLow = ' + ISNULL('''' + REPLACE(@FragmentationLow,'''','''''') + '''','NULL') + SET @Parameters += ', @FragmentationMedium = ' + ISNULL('''' + REPLACE(@FragmentationMedium,'''','''''') + '''','NULL') + SET @Parameters += ', @FragmentationHigh = ' + ISNULL('''' + REPLACE(@FragmentationHigh,'''','''''') + '''','NULL') + SET @Parameters += ', @FragmentationLevel1 = ' + ISNULL(CAST(@FragmentationLevel1 AS nvarchar),'NULL') + SET @Parameters += ', @FragmentationLevel2 = ' + ISNULL(CAST(@FragmentationLevel2 AS nvarchar),'NULL') + SET @Parameters += ', @MinNumberOfPages = ' + ISNULL(CAST(@MinNumberOfPages AS nvarchar),'NULL') + SET @Parameters += ', @MaxNumberOfPages = ' + ISNULL(CAST(@MaxNumberOfPages AS nvarchar),'NULL') + SET @Parameters += ', @SortInTempdb = ' + ISNULL('''' + REPLACE(@SortInTempdb,'''','''''') + '''','NULL') + SET @Parameters += ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') + SET @Parameters += ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar),'NULL') + SET @Parameters += ', @PadIndex = ' + ISNULL('''' + REPLACE(@PadIndex,'''','''''') + '''','NULL') + SET @Parameters += ', @LOBCompaction = ' + ISNULL('''' + REPLACE(@LOBCompaction,'''','''''') + '''','NULL') + SET @Parameters += ', @UpdateStatistics = ' + ISNULL('''' + REPLACE(@UpdateStatistics,'''','''''') + '''','NULL') + SET @Parameters += ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') + SET @Parameters += ', @StatisticsModificationLevel = ' + ISNULL(CAST(@StatisticsModificationLevel AS nvarchar),'NULL') + SET @Parameters += ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar),'NULL') + SET @Parameters += ', @StatisticsResample = ' + ISNULL('''' + REPLACE(@StatisticsResample,'''','''''') + '''','NULL') + SET @Parameters += ', @PartitionLevel = ' + ISNULL('''' + REPLACE(@PartitionLevel,'''','''''') + '''','NULL') + SET @Parameters += ', @MSShippedObjects = ' + ISNULL('''' + REPLACE(@MSShippedObjects,'''','''''') + '''','NULL') + SET @Parameters += ', @Indexes = ' + ISNULL('''' + REPLACE(@Indexes,'''','''''') + '''','NULL') + SET @Parameters += ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') + SET @Parameters += ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar),'NULL') + SET @Parameters += ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar),'NULL') + SET @Parameters += ', @WaitAtLowPriorityAbortAfterWait = ' + ISNULL('''' + REPLACE(@WaitAtLowPriorityAbortAfterWait,'''','''''') + '''','NULL') + SET @Parameters += ', @Resumable = ' + ISNULL('''' + REPLACE(@Resumable,'''','''''') + '''','NULL') + SET @Parameters += ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') + SET @Parameters += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') + SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') + SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') + SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') + SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -357,80 +350,56 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' END IF @@TRANCOUNT <> 0 BEGIN - SET @ErrorMessage = 'The transaction count is not 0.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - END - - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO Logging + INSERT INTO @Errors ([Message]) + SELECT 'The transaction count is not 0.' END ---------------------------------------------------------------------------------------------------- @@ -556,10 +525,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Databases is not supported.' END ---------------------------------------------------------------------------------------------------- @@ -653,26 +620,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.' END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' END ---------------------------------------------------------------------------------------------------- @@ -806,277 +767,208 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationLow is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FragmentationLow is not supported.' END IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationMedium is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FragmentationMedium is not supported.' END IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'High' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationHigh is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FragmentationHigh is not supported.' END IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 >= @FragmentationLevel2 OR @FragmentationLevel1 IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationLevel1 is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FragmentationLevel1 is not supported.' END IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 <= @FragmentationLevel1 OR @FragmentationLevel2 IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationLevel2 is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FragmentationLevel2 is not supported.' END IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @MinNumberOfPages is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MinNumberOfPages is not supported.' END IF @MaxNumberOfPages < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxNumberOfPages is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MaxNumberOfPages is not supported.' END IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @SortInTempdb is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @SortInTempdb is not supported.' END IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MaxDOP is not supported.' END IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @FillFactor is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FillFactor is not supported.' END IF @PadIndex NOT IN('Y','N') BEGIN - SET @ErrorMessage = 'The value for the parameter @PadIndex is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @PadIndex is not supported.' END IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LOBCompaction is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LOBCompaction is not supported.' END IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN - SET @ErrorMessage = 'The value for the parameter @UpdateStatistics is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @UpdateStatistics is not supported.' END IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @OnlyModifiedStatistics is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @OnlyModifiedStatistics is not supported.' END IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @StatisticsModificationLevel is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @StatisticsModificationLevel is not supported.' END IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.' END IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @StatisticsSample is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @StatisticsSample is not supported.' END IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL OR (@StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @StatisticsResample is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @StatisticsResample is not supported.' END IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @PartitionLevel is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @PartitionLevel is not supported.' END IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @MSShippedObjects is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MSShippedObjects is not supported.' END IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) OR (@Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes)) BEGIN - SET @ErrorMessage = 'The value for the parameter @Indexes is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Indexes is not supported.' END IF @TimeLimit < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @TimeLimit is not supported.' END IF @Delay < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @Delay is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Delay is not supported.' END IF @WaitAtLowPriorityMaxDuration < 0 OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @WaitAtLowPriorityAbortAfterWait IS NULL) OR (@WaitAtLowPriorityMaxDuration IS NULL AND @WaitAtLowPriorityAbortAfterWait IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.' END IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.' END IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL OR (@Resumable = 'Y' AND NOT (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8))) BEGIN - SET @ErrorMessage = 'The value for the parameter @Resumable is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Resumable is not supported.' END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Resumable and @SortInTempdb.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.' END IF @LockTimeout < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LockTimeout is not supported.' END IF @LockMessageSeverity NOT IN(10,16) BEGIN - SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.' END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.' END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.' END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LogToTable is not supported.' END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Execute is not supported.' END - IF @Error <> 0 + IF EXISTS(SELECT * FROM @Errors) BEGIN - SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - SET @ReturnCode = @Error - GOTO Logging + INSERT INTO @Errors ([Message]) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.' END ---------------------------------------------------------------------------------------------------- @@ -1090,10 +982,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -1103,10 +993,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -1116,10 +1004,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -1130,10 +1016,36 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + END + + ---------------------------------------------------------------------------------------------------- + --// Raise errors //-- + ---------------------------------------------------------------------------------------------------- + + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + + OPEN ErrorCursor + + FETCH ErrorCursor INTO @CurrentMessage + + WHILE @@FETCH_STATUS = 0 + BEGIN + RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT + + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage + END + + CLOSE ErrorCursor + + DEALLOCATE ErrorCursor + + IF EXISTS (SELECT * FROM @Errors) + BEGIN + SET @ReturnCode = 50000 + GOTO Logging END ---------------------------------------------------------------------------------------------------- @@ -1247,7 +1159,7 @@ BEGIN BEGIN TRANSACTION UPDATE [Queue] - SET QueueStartTime = GETDATE(), + SET QueueStartTime = SYSDATETIME(), SessionID = @@SPID, RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID) @@ -1327,7 +1239,7 @@ BEGIN AND NOT EXISTS (SELECT * FROM sys.dm_exec_requests WHERE session_id = QueueDatabase.SessionID AND request_id = QueueDatabase.RequestID AND start_time = QueueDatabase.RequestStartTime) UPDATE QueueDatabase - SET DatabaseStartTime = GETDATE(), + SET DatabaseStartTime = SYSDATETIME(), DatabaseEndTime = NULL, SessionID = @@SPID, RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), @@ -1400,7 +1312,7 @@ BEGIN WHERE database_id = DB_ID(@CurrentDatabaseName) END - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) @@ -1450,7 +1362,7 @@ BEGIN BEGIN -- Select indexes in the current database - IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, IsComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' @@ -1652,7 +1564,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + WHILE (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SELECT TOP 1 @CurrentIxID = ID, @CurrentIxOrder = [Order], @@ -1701,8 +1613,8 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand02 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - IF @CurrentIsPartition = 0 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' - IF @CurrentIsPartition = 1 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' + IF @CurrentIsPartition = 0 SET @CurrentCommand02 += 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' + IF @CurrentIsPartition = 1 SET @CurrentCommand02 += 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' BEGIN TRY EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand02, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT @@ -1735,7 +1647,7 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM sys.stats stats INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' + SET @CurrentCommand03 += 'IF EXISTS(SELECT * FROM sys.stats stats INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' BEGIN TRY EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand03, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT @@ -1770,16 +1682,16 @@ BEGIN IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN - SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' + SET @CurrentCommand04 += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' END ELSE IF (@Version >= 10.504000 AND @Version < 11) OR @Version >= 11.03000 BEGIN - SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' + SET @CurrentCommand04 += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' END ELSE BEGIN - SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = rowcnt, @ParamModificationCounter = rowmodctr FROM sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID' + SET @CurrentCommand04 += 'SELECT @ParamRowCount = rowcnt, @ParamModificationCounter = rowmodctr FROM sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID' END BEGIN TRY @@ -1813,7 +1725,7 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand05 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand05 = @CurrentCommand05 + 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + SET @CurrentCommand05 += 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' BEGIN TRY EXECUTE sp_executesql @stmt = @CurrentCommand05, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT @@ -1948,16 +1860,16 @@ BEGIN IF @CurrentIndexID IS NOT NULL BEGIN SET @CurrentComment06 = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment06 = @CurrentComment06 + 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' - SET @CurrentComment06 = @CurrentComment06 + 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 = @CurrentComment06 + 'NewLOB: ' + CASE WHEN @CurrentIsNewLOB = 1 THEN 'Yes' WHEN @CurrentIsNewLOB = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 = @CurrentComment06 + 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 11 SET @CurrentComment06 = @CurrentComment06 + 'ColumnStore: ' + CASE WHEN @CurrentIsColumnStore = 1 THEN 'Yes' WHEN @CurrentIsColumnStore = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 = @CurrentComment06 + 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 = @CurrentComment06 + 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 = @CurrentComment06 + 'AllowPageLocks: ' + CASE WHEN @CurrentAllowPageLocks = 1 THEN 'Yes' WHEN @CurrentAllowPageLocks = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 = @CurrentComment06 + 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar),'N/A') + ', ' - SET @CurrentComment06 = @CurrentComment06 + 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar),'N/A') + SET @CurrentComment06 += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' + SET @CurrentComment06 += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 += 'NewLOB: ' + CASE WHEN @CurrentIsNewLOB = 1 THEN 'Yes' WHEN @CurrentIsNewLOB = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 11 SET @CurrentComment06 += 'ColumnStore: ' + CASE WHEN @CurrentIsColumnStore = 1 THEN 'Yes' WHEN @CurrentIsColumnStore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 += 'AllowPageLocks: ' + CASE WHEN @CurrentAllowPageLocks = 1 THEN 'Yes' WHEN @CurrentAllowPageLocks = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 += 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar),'N/A') + ', ' + SET @CurrentComment06 += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar),'N/A') END IF @CurrentIndexID IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) @@ -1972,11 +1884,11 @@ BEGIN IF @CurrentStatisticsID IS NOT NULL BEGIN SET @CurrentComment07 = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment07 = @CurrentComment07 + 'IndexType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' - IF @CurrentIndexID IS NOT NULL SET @CurrentComment07 = @CurrentComment07 + 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' - SET @CurrentComment07 = @CurrentComment07 + 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Y' WHEN @CurrentIsIncremental = 0 THEN 'N' ELSE 'N/A' END + ', ' - SET @CurrentComment07 = @CurrentComment07 + 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' - SET @CurrentComment07 = @CurrentComment07 + 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') + SET @CurrentComment07 += 'IndexType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' + IF @CurrentIndexID IS NOT NULL SET @CurrentComment07 += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' + SET @CurrentComment07 += 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Y' WHEN @CurrentIsIncremental = 0 THEN 'N' ELSE 'N/A' END + ', ' + SET @CurrentComment07 += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' + SET @CurrentComment07 += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') END IF @CurrentStatisticsID IS NOT NULL AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) @@ -1987,17 +1899,17 @@ BEGIN ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END - IF @CurrentIndexID IS NOT NULL AND @CurrentAction IS NOT NULL AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF @CurrentIndexID IS NOT NULL AND @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType06 = 'ALTER_INDEX' SET @CurrentCommand06 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand06 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand06 = @CurrentCommand06 + 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) - IF @CurrentResumableIndexOperation = 1 SET @CurrentCommand06 = @CurrentCommand06 + ' RESUME' - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' REBUILD' - IF @CurrentAction IN('INDEX_REORGANIZE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' REORGANIZE' - IF @CurrentIsPartition = 1 AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) + SET @CurrentCommand06 += 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + IF @CurrentResumableIndexOperation = 1 SET @CurrentCommand06 += ' RESUME' + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 += ' REBUILD' + IF @CurrentAction IN('INDEX_REORGANIZE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 += ' REORGANIZE' + IF @CurrentIsPartition = 1 AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 += ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN @@ -2050,7 +1962,7 @@ BEGIN IF (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsTimestamp = 0 AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'MAX_DURATION = ' + CAST(DATEDIFF(MINUTE,GETDATE(),DATEADD(ss,@TimeLimit,@StartTime)) AS nvarchar(max)) + SELECT 'MAX_DURATION = ' + CAST(DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) AS nvarchar(max)) END IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' @@ -2082,7 +1994,7 @@ BEGIN BREAK END - SET @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + @CurrentAlterIndexArgument + ', ' + SET @CurrentAlterIndexWithClause += @CurrentAlterIndexArgument + ', ' UPDATE @CurrentAlterIndexWithClauseArguments SET Added = 1 @@ -2096,7 +2008,7 @@ BEGIN SET @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + ')' END - IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand06 = @CurrentCommand06 + @CurrentAlterIndexWithClause + IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand06 += @CurrentAlterIndexWithClause EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment06, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo06, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -2112,13 +2024,13 @@ BEGIN SET @CurrentMaxDOP = @MaxDOP - IF @CurrentStatisticsID IS NOT NULL AND @CurrentUpdateStatistics = 'Y' AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF @CurrentStatisticsID IS NOT NULL AND @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType07 = 'UPDATE_STATISTICS' SET @CurrentCommand07 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand07 = @CurrentCommand07 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) + SET @CurrentCommand07 += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) BEGIN @@ -2177,9 +2089,9 @@ BEGIN SET @CurrentUpdateStatisticsWithClause = LEFT(@CurrentUpdateStatisticsWithClause,LEN(@CurrentUpdateStatisticsWithClause) - 1) END - IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + @CurrentUpdateStatisticsWithClause + IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand07 += @CurrentUpdateStatisticsWithClause - IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand07 += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -2284,7 +2196,7 @@ BEGIN IF @DatabasesInParallel = 'Y' BEGIN UPDATE dbo.QueueDatabase - SET DatabaseEndTime = GETDATE() + SET DatabaseEndTime = SYSDATETIME() WHERE QueueID = @QueueID AND DatabaseName = @CurrentDatabaseName END @@ -2325,7 +2237,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- Logging: - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 3b16f772..32c5987b 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -1,6 +1,6 @@ /* -SQL Server Maintenance Solution - SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, and SQL Server 2019 +SQL Server Maintenance Solution - SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, and SQL Server 2019 Backup: https://ola.hallengren.com/sql-server-backup.html Integrity Check: https://ola.hallengren.com/sql-server-integrity-check.html @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-03 23:04:49 +Version: 2020-01-05 15:00:38 You can contact me by e-mail at ola@hallengren.com. @@ -79,8 +79,8 @@ CREATE TABLE [dbo].[CommandLog]( [ExtendedInfo] [xml] NULL, [Command] [nvarchar](max) NOT NULL, [CommandType] [nvarchar](60) NOT NULL, - [StartTime] [datetime] NOT NULL, - [EndTime] [datetime] NULL, + [StartTime] [datetime2](7) NOT NULL, + [EndTime] [datetime2](7) NULL, [ErrorNumber] [int] NULL, [ErrorMessage] [nvarchar](max) NULL, CONSTRAINT [PK_CommandLog] PRIMARY KEY CLUSTERED @@ -127,7 +127,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-03 23:04:49 //-- + --// Version: 2020-01-05 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -138,27 +138,22 @@ BEGIN DECLARE @ErrorMessageOriginal nvarchar(max) DECLARE @Severity int - DECLARE @sp_executesql nvarchar(max) + DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, + [Message] nvarchar(max)) - DECLARE @StartTime datetime - DECLARE @EndTime datetime + DECLARE @CurrentMessage nvarchar(max) - DECLARE @StartTimeSec datetime - DECLARE @EndTimeSec datetime + DECLARE @sp_executesql nvarchar(max) = QUOTENAME(@DatabaseContext) + '.sys.sp_executesql' - DECLARE @ID int - - DECLARE @Error int - DECLARE @ReturnCode int + DECLARE @StartTime datetime2 + DECLARE @EndTime datetime2 - DECLARE @EmptyLine nvarchar(max) - - SET @sp_executesql = QUOTENAME(@DatabaseContext) + '.sys.sp_executesql' + DECLARE @ID int - SET @Error = 0 - SET @ReturnCode = 0 + DECLARE @Error int = 0 + DECLARE @ReturnCode int = 0 - SET @EmptyLine = CHAR(9) + DECLARE @EmptyLine nvarchar(max) = CHAR(9) ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- @@ -166,40 +161,26 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - END - - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO ReturnCode + INSERT INTO @Errors ([Message]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' END ---------------------------------------------------------------------------------------------------- @@ -208,63 +189,71 @@ BEGIN IF @DatabaseContext IS NULL OR NOT EXISTS (SELECT * FROM sys.databases WHERE name = @DatabaseContext) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabaseContext is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabaseContext is not supported.' END IF @Command IS NULL OR @Command = '' BEGIN - SET @ErrorMessage = 'The value for the parameter @Command is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Command is not supported.' END IF @CommandType IS NULL OR @CommandType = '' OR LEN(@CommandType) > 60 BEGIN - SET @ErrorMessage = 'The value for the parameter @CommandType is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CommandType is not supported.' END IF @Mode NOT IN(1,2) OR @Mode IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Mode is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Mode is not supported.' END IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.' END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LogToTable is not supported.' END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Execute is not supported.' + END + + ---------------------------------------------------------------------------------------------------- + --// Raise errors //-- + ---------------------------------------------------------------------------------------------------- + + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + + OPEN ErrorCursor + + FETCH ErrorCursor INTO @CurrentMessage + + WHILE @@FETCH_STATUS = 0 + BEGIN + RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT + + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage END - IF @Error <> 0 + CLOSE ErrorCursor + + DEALLOCATE ErrorCursor + + IF EXISTS (SELECT * FROM @Errors) BEGIN - SET @ReturnCode = @Error + SET @ReturnCode = 50000 GOTO ReturnCode END @@ -272,10 +261,9 @@ BEGIN --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartTime = GETDATE() - SET @StartTimeSec = CONVERT(datetime,CONVERT(nvarchar,@StartTime,120),120) + SET @StartTime = SYSDATETIME() - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTimeSec,120) + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Database context: ' + QUOTENAME(@DatabaseContext) @@ -333,16 +321,15 @@ BEGIN --// Log completing information //-- ---------------------------------------------------------------------------------------------------- - SET @EndTime = GETDATE() - SET @EndTimeSec = CONVERT(datetime,CONVERT(varchar,@EndTime,120),120) + SET @EndTime = SYSDATETIME() SET @EndMessage = 'Outcome: ' + CASE WHEN @Execute = 'N' THEN 'Not Executed' WHEN @Error = 0 THEN 'Succeeded' ELSE 'Failed' END RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT - SET @EndMessage = 'Duration: ' + CASE WHEN DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) > 0 THEN CAST(DATEDIFF(ss,@StartTimeSec, @EndTimeSec)/(24*3600) AS nvarchar) + '.' ELSE '' END + CONVERT(nvarchar,@EndTimeSec - @StartTimeSec,108) + 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) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTimeSec,120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTime,120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT @@ -443,7 +430,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-03 23:04:49 //-- + --// Version: 2020-01-05 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -453,16 +440,14 @@ BEGIN DECLARE @DatabaseMessage nvarchar(max) DECLARE @ErrorMessage nvarchar(max) - DECLARE @StartTime datetime - DECLARE @SchemaName nvarchar(max) - DECLARE @ObjectName nvarchar(max) - DECLARE @VersionTimestamp nvarchar(max) + DECLARE @StartTime datetime2 = SYSDATETIME() + DECLARE @SchemaName nvarchar(max) = OBJECT_SCHEMA_NAME(@@PROCID) + DECLARE @ObjectName nvarchar(max) = OBJECT_NAME(@@PROCID) + DECLARE @VersionTimestamp nvarchar(max) = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) DECLARE @Parameters nvarchar(max) - DECLARE @Version numeric(18,10) DECLARE @HostPlatform nvarchar(max) DECLARE @DirectorySeparator nvarchar(max) - DECLARE @AmazonRDS bit DECLARE @Updated bit @@ -471,7 +456,7 @@ BEGIN DECLARE @DefaultDirectory nvarchar(4000) DECLARE @QueueID int - DECLARE @QueueStartTime datetime + DECLARE @QueueStartTime datetime2 DECLARE @CurrentRootDirectoryID int DECLARE @CurrentRootDirectoryPath nvarchar(4000) @@ -498,7 +483,7 @@ BEGIN DECLARE @CurrentDifferentialBaseLSN numeric(25,0) DECLARE @CurrentDifferentialBaseIsSnapshot bit DECLARE @CurrentLogLSN numeric(25,0) - DECLARE @CurrentLatestBackup datetime + DECLARE @CurrentLatestBackup datetime2 DECLARE @CurrentDatabaseNameFS nvarchar(max) DECLARE @CurrentDirectoryStructure nvarchar(max) DECLARE @CurrentDatabaseFileName nvarchar(max) @@ -507,8 +492,8 @@ BEGIN DECLARE @CurrentDirectoryID int DECLARE @CurrentDirectoryPath nvarchar(max) DECLARE @CurrentFilePath nvarchar(max) - DECLARE @CurrentDate datetime - DECLARE @CurrentCleanupDate datetime + DECLARE @CurrentDate datetime2 + DECLARE @CurrentCleanupDate datetime2 DECLARE @CurrentIsDatabaseAccessible bit DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) @@ -519,7 +504,7 @@ BEGIN DECLARE @CurrentBackupSetID int DECLARE @CurrentIsMirror bit - DECLARE @CurrentLastLogBackup datetime + DECLARE @CurrentLastLogBackup datetime2 DECLARE @CurrentLogSizeSinceLastLogBackup float DECLARE @CurrentAllocatedExtentPageCount bigint DECLARE @CurrentModifiedExtentPageCount bigint @@ -529,7 +514,6 @@ BEGIN DECLARE @CurrentCommand03 nvarchar(max) DECLARE @CurrentCommand04 nvarchar(max) DECLARE @CurrentCommand05 nvarchar(max) - DECLARE @CurrentCommand06 nvarchar(max) DECLARE @CurrentCommand07 nvarchar(max) DECLARE @CurrentCommandOutput01 int @@ -544,6 +528,11 @@ BEGIN DECLARE @CurrentCommandType04 nvarchar(max) DECLARE @CurrentCommandType05 nvarchar(max) + DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, + [Message] nvarchar(max)) + + DECLARE @CurrentMessage nvarchar(max) + DECLARE @Directories TABLE (ID int PRIMARY KEY, DirectoryPath nvarchar(max), Mirror bit, @@ -597,7 +586,7 @@ BEGIN DirectoryPath nvarchar(max), Mirror bit, DirectoryNumber int, - CleanupDate datetime, + CleanupDate datetime2, CleanupMode nvarchar(max), CreateCompleted bit, CleanupCompleted bit, @@ -613,21 +602,15 @@ BEGIN FilePath nvarchar(max), Mirror bit) - DECLARE @CurrentCleanupDates TABLE (CleanupDate datetime, Mirror bit) + DECLARE @CurrentCleanupDates TABLE (CleanupDate datetime2, + Mirror bit) - DECLARE @DirectoryCheck bit + DECLARE @Error int = 0 + DECLARE @ReturnCode int = 0 - DECLARE @Error int - DECLARE @ReturnCode int + DECLARE @EmptyLine nvarchar(max) = CHAR(9) - DECLARE @EmptyLine nvarchar(max) - - SET @Error = 0 - SET @ReturnCode = 0 - - SET @EmptyLine = CHAR(9) - - SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) + DECLARE @Version numeric(18,10) = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) IF @Version >= 14 BEGIN @@ -639,74 +622,69 @@ BEGIN SET @HostPlatform = 'Windows' END - SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartTime = GETDATE() - SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) - SET @ObjectName = OBJECT_NAME(@@PROCID) - SET @VersionTimestamp = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) - SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @BackupType = ' + ISNULL('''' + REPLACE(@BackupType,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Verify = ' + ISNULL('''' + REPLACE(@Verify,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @CleanupMode = ' + ISNULL('''' + REPLACE(@CleanupMode,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Compress = ' + ISNULL('''' + REPLACE(@Compress,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @CopyOnly = ' + ISNULL('''' + REPLACE(@CopyOnly,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ChangeBackupType = ' + ISNULL('''' + REPLACE(@ChangeBackupType,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @BackupSoftware = ' + ISNULL('''' + REPLACE(@BackupSoftware,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @CheckSum = ' + ISNULL('''' + REPLACE(@CheckSum,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @BlockSize = ' + ISNULL(CAST(@BlockSize AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @CompressionLevel = ' + ISNULL(CAST(@CompressionLevel AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @Encrypt = ' + ISNULL('''' + REPLACE(@Encrypt,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @EncryptionAlgorithm = ' + ISNULL('''' + REPLACE(@EncryptionAlgorithm,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ServerCertificate = ' + ISNULL('''' + REPLACE(@ServerCertificate,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ServerAsymmetricKey = ' + ISNULL('''' + REPLACE(@ServerAsymmetricKey,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @EncryptionKey = ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ReadWriteFileGroups = ' + ISNULL('''' + REPLACE(@ReadWriteFileGroups,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @OverrideBackupPreference = ' + ISNULL('''' + REPLACE(@OverrideBackupPreference,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @NoRecovery = ' + ISNULL('''' + REPLACE(@NoRecovery,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @URL = ' + ISNULL('''' + REPLACE(@URL,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Credential = ' + ISNULL('''' + REPLACE(@Credential,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @MirrorDirectory = ' + ISNULL('''' + REPLACE(@MirrorDirectory,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @MirrorCleanupTime = ' + ISNULL(CAST(@MirrorCleanupTime AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @MirrorCleanupMode = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @MirrorURL = ' + ISNULL('''' + REPLACE(@MirrorURL,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ModificationLevel = ' + ISNULL(CAST(@ModificationLevel AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @DataDomainBoostHost = ' + ISNULL('''' + REPLACE(@DataDomainBoostHost,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DataDomainBoostUser = ' + ISNULL('''' + REPLACE(@DataDomainBoostUser,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DataDomainBoostDevicePath = ' + ISNULL('''' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DataDomainBoostLockboxPath = ' + ISNULL('''' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DirectoryStructure = ' + ISNULL('''' + REPLACE(@DirectoryStructure,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @AvailabilityGroupDirectoryStructure = ' + ISNULL('''' + REPLACE(@AvailabilityGroupDirectoryStructure,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FileName = ' + ISNULL('''' + REPLACE(@FileName,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @AvailabilityGroupFileName = ' + ISNULL('''' + REPLACE(@AvailabilityGroupFileName,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FileExtensionFull = ' + ISNULL('''' + REPLACE(@FileExtensionFull,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FileExtensionDiff = ' + ISNULL('''' + REPLACE(@FileExtensionDiff,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ObjectLevelRecoveryMap = ' + ISNULL('''' + REPLACE(@ObjectLevelRecoveryMap,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @Parameters += ', @Directory = ' + ISNULL('''' + REPLACE(@Directory,'''','''''') + '''','NULL') + SET @Parameters += ', @BackupType = ' + ISNULL('''' + REPLACE(@BackupType,'''','''''') + '''','NULL') + SET @Parameters += ', @Verify = ' + ISNULL('''' + REPLACE(@Verify,'''','''''') + '''','NULL') + SET @Parameters += ', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar),'NULL') + SET @Parameters += ', @CleanupMode = ' + ISNULL('''' + REPLACE(@CleanupMode,'''','''''') + '''','NULL') + SET @Parameters += ', @Compress = ' + ISNULL('''' + REPLACE(@Compress,'''','''''') + '''','NULL') + SET @Parameters += ', @CopyOnly = ' + ISNULL('''' + REPLACE(@CopyOnly,'''','''''') + '''','NULL') + SET @Parameters += ', @ChangeBackupType = ' + ISNULL('''' + REPLACE(@ChangeBackupType,'''','''''') + '''','NULL') + SET @Parameters += ', @BackupSoftware = ' + ISNULL('''' + REPLACE(@BackupSoftware,'''','''''') + '''','NULL') + SET @Parameters += ', @CheckSum = ' + ISNULL('''' + REPLACE(@CheckSum,'''','''''') + '''','NULL') + SET @Parameters += ', @BlockSize = ' + ISNULL(CAST(@BlockSize AS nvarchar),'NULL') + SET @Parameters += ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar),'NULL') + SET @Parameters += ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar),'NULL') + SET @Parameters += ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar),'NULL') + SET @Parameters += ', @CompressionLevel = ' + ISNULL(CAST(@CompressionLevel AS nvarchar),'NULL') + SET @Parameters += ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL') + SET @Parameters += ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar),'NULL') + SET @Parameters += ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar),'NULL') + SET @Parameters += ', @Encrypt = ' + ISNULL('''' + REPLACE(@Encrypt,'''','''''') + '''','NULL') + SET @Parameters += ', @EncryptionAlgorithm = ' + ISNULL('''' + REPLACE(@EncryptionAlgorithm,'''','''''') + '''','NULL') + SET @Parameters += ', @ServerCertificate = ' + ISNULL('''' + REPLACE(@ServerCertificate,'''','''''') + '''','NULL') + SET @Parameters += ', @ServerAsymmetricKey = ' + ISNULL('''' + REPLACE(@ServerAsymmetricKey,'''','''''') + '''','NULL') + SET @Parameters += ', @EncryptionKey = ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + SET @Parameters += ', @ReadWriteFileGroups = ' + ISNULL('''' + REPLACE(@ReadWriteFileGroups,'''','''''') + '''','NULL') + SET @Parameters += ', @OverrideBackupPreference = ' + ISNULL('''' + REPLACE(@OverrideBackupPreference,'''','''''') + '''','NULL') + SET @Parameters += ', @NoRecovery = ' + ISNULL('''' + REPLACE(@NoRecovery,'''','''''') + '''','NULL') + SET @Parameters += ', @URL = ' + ISNULL('''' + REPLACE(@URL,'''','''''') + '''','NULL') + SET @Parameters += ', @Credential = ' + ISNULL('''' + REPLACE(@Credential,'''','''''') + '''','NULL') + SET @Parameters += ', @MirrorDirectory = ' + ISNULL('''' + REPLACE(@MirrorDirectory,'''','''''') + '''','NULL') + SET @Parameters += ', @MirrorCleanupTime = ' + ISNULL(CAST(@MirrorCleanupTime AS nvarchar),'NULL') + SET @Parameters += ', @MirrorCleanupMode = ' + ISNULL('''' + REPLACE(@MirrorCleanupMode,'''','''''') + '''','NULL') + SET @Parameters += ', @MirrorURL = ' + ISNULL('''' + REPLACE(@MirrorURL,'''','''''') + '''','NULL') + SET @Parameters += ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') + SET @Parameters += ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') + SET @Parameters += ', @AdaptiveCompression = ' + ISNULL('''' + REPLACE(@AdaptiveCompression,'''','''''') + '''','NULL') + SET @Parameters += ', @ModificationLevel = ' + ISNULL(CAST(@ModificationLevel AS nvarchar),'NULL') + SET @Parameters += ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar),'NULL') + SET @Parameters += ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar),'NULL') + SET @Parameters += ', @DataDomainBoostHost = ' + ISNULL('''' + REPLACE(@DataDomainBoostHost,'''','''''') + '''','NULL') + SET @Parameters += ', @DataDomainBoostUser = ' + ISNULL('''' + REPLACE(@DataDomainBoostUser,'''','''''') + '''','NULL') + SET @Parameters += ', @DataDomainBoostDevicePath = ' + ISNULL('''' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '''','NULL') + SET @Parameters += ', @DataDomainBoostLockboxPath = ' + ISNULL('''' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '''','NULL') + SET @Parameters += ', @DirectoryStructure = ' + ISNULL('''' + REPLACE(@DirectoryStructure,'''','''''') + '''','NULL') + SET @Parameters += ', @AvailabilityGroupDirectoryStructure = ' + ISNULL('''' + REPLACE(@AvailabilityGroupDirectoryStructure,'''','''''') + '''','NULL') + SET @Parameters += ', @FileName = ' + ISNULL('''' + REPLACE(@FileName,'''','''''') + '''','NULL') + SET @Parameters += ', @AvailabilityGroupFileName = ' + ISNULL('''' + REPLACE(@AvailabilityGroupFileName,'''','''''') + '''','NULL') + SET @Parameters += ', @FileExtensionFull = ' + ISNULL('''' + REPLACE(@FileExtensionFull,'''','''''') + '''','NULL') + SET @Parameters += ', @FileExtensionDiff = ' + ISNULL('''' + REPLACE(@FileExtensionDiff,'''','''''') + '''','NULL') + SET @Parameters += ', @FileExtensionLog = ' + ISNULL('''' + REPLACE(@FileExtensionLog,'''','''''') + '''','NULL') + SET @Parameters += ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') + SET @Parameters += ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') + SET @Parameters += ', @ObjectLevelRecoveryMap = ' + ISNULL('''' + REPLACE(@ObjectLevelRecoveryMap,'''','''''') + '''','NULL') + SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') + SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') + SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') + SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -743,88 +721,62 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' END IF @@TRANCOUNT <> 0 BEGIN - SET @ErrorMessage = 'The transaction count is not 0.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The transaction count is not 0.' END IF @AmazonRDS = 1 BEGIN - SET @ErrorMessage = 'The stored procedure DatabaseBackup is not supported on Amazon RDS.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - END - - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO Logging + INSERT INTO @Errors ([Message]) + SELECT 'The stored procedure DatabaseBackup is not supported on Amazon RDS.' END ---------------------------------------------------------------------------------------------------- @@ -951,10 +903,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Databases is not supported.' END ---------------------------------------------------------------------------------------------------- @@ -1048,26 +998,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.' END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' END ---------------------------------------------------------------------------------------------------- @@ -1082,10 +1026,8 @@ BEGIN ORDER BY DatabaseName ASC IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -1098,10 +1040,8 @@ BEGIN OPTION (RECOMPILE) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END ---------------------------------------------------------------------------------------------------- @@ -1192,8 +1132,6 @@ BEGIN --// Check directories //-- ---------------------------------------------------------------------------------------------------- - SET @DirectoryCheck = 1 - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux') OR (DirectoryPath = 'NUL' AND @HostPlatform = 'Windows')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' @@ -1204,11 +1142,8 @@ BEGIN OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath <> 'NUL')) OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) BEGIN - SET @ErrorMessage = 'The value for the parameter @Directory is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - SET @DirectoryCheck = 0 + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Directory is not supported.' END IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) @@ -1223,22 +1158,17 @@ BEGIN OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorDirectory is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - SET @DirectoryCheck = 0 + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.' END IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) BEGIN - SET @ErrorMessage = 'Mirrored backup to disk is only available in Enterprise and Developer Edition.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'Mirrored backup to disk is only available in Enterprise and Developer Edition.' END - IF @DirectoryCheck = 1 + IF NOT EXISTS (SELECT * FROM @Errors WHERE [Message] IN('The value for the parameter @Directory is not supported.','The value for the parameter @MirrorDirectory is not supported.')) BEGIN WHILE (1 = 1) BEGIN @@ -1259,10 +1189,8 @@ BEGIN IF NOT EXISTS (SELECT * FROM @DirectoryInfo WHERE FileExists = 0 AND FileIsADirectory = 1 AND ParentDirectoryExists = 1) BEGIN - SET @ErrorMessage = 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.' END UPDATE @Directories @@ -1344,20 +1272,16 @@ BEGIN OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @URL is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @URL is not supported.' END IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath NOT LIKE 'https://%/%') OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MirrorURL is not supported.' END ---------------------------------------------------------------------------------------------------- @@ -1445,567 +1369,426 @@ BEGIN IF @BackupType NOT IN ('FULL','DIFF','LOG') OR @BackupType IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @BackupType is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @BackupType is not supported.' END IF SERVERPROPERTY('EngineEdition') = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN - SET @ErrorMessage = 'SQL Database Managed Instance only supports COPY_ONLY full backups.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.' END IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Verify is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Verify is not supported.' END IF @Verify = 'Y' AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN - SET @ErrorMessage = 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.' END IF @CleanupTime < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupTime is not supported.' END IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.' END IF @CleanupTime IS NOT NULL AND @HostPlatform = 'Linux' BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.' END IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.' END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.' END IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.' END IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CleanupMode is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CleanupMode is not supported.' END IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @Compress is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Compress is not supported.' END IF @CopyOnly NOT IN ('Y','N') OR @CopyOnly IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CopyOnly is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CopyOnly is not supported.' END IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @ChangeBackupType is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @ChangeBackupType is not supported.' END IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN - SET @ErrorMessage = 'The value for the parameter @BackupSoftware is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @BackupSoftware is not supported.' END IF @BackupSoftware = 'LITESPEED' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_backup_database') BEGIN - SET @ErrorMessage = 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.' END IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN - SET @ErrorMessage = 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.' END IF @BackupSoftware = 'SQLSAFE' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_ss_backup') BEGIN - SET @ErrorMessage = 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.' END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'PC' AND [name] = 'emc_run_backup') BEGIN - SET @ErrorMessage = 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.' END IF @CheckSum NOT IN ('Y','N') OR @CheckSum IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @CheckSum is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CheckSum is not supported.' END IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @BlockSize is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @BlockSize is not supported.' END IF @BufferCount <= 0 OR @BufferCount > 2147483647 OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE') BEGIN - SET @ErrorMessage = 'The value for the parameter @BufferCount is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @BufferCount is not supported.' END IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxTransferSize is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MaxTransferSize is not supported.' END IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @NumberOfFiles is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.' END IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @CompressionLevel is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CompressionLevel is not supported.' END IF LEN(@Description) > 255 OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) BEGIN - SET @ErrorMessage = 'The value for the parameter @Description is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Description is not supported.' END IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) OR (@BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32)) OR (@BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32)) OR (@BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64)) BEGIN - SET @ErrorMessage = 'The value for the parameter @Threads is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Threads is not supported.' END IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) OR @Throttle < 1 OR @Throttle > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @Throttle is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Throttle is not supported.' END IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Encrypt is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Encrypt is not supported.' END IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @EncryptionAlgorithm is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.' END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL) OR (@ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate)) BEGIN - SET @ErrorMessage = 'The value for the parameter @ServerCertificate is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @ServerCertificate is not supported.' END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL) OR (@ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey)) BEGIN - SET @ErrorMessage = 'The value for the parameter @ServerAsymmetricKey is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.' END IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @EncryptionKey is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @EncryptionKey is not supported.' END IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL OR (@ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG') BEGIN - SET @ErrorMessage = 'The value for the parameter @ReadWriteFileGroups is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.' END IF @OverrideBackupPreference NOT IN('Y','N') OR @OverrideBackupPreference IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @OverrideBackupPreference is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @OverrideBackupPreference is not supported.' END IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL OR (@NoRecovery = 'Y' AND @BackupType <> 'LOG') OR (@NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE') BEGIN - SET @ErrorMessage = 'The value for the parameter @NoRecovery is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @NoRecovery is not supported.' END IF (@URL IS NOT NULL AND @Directory IS NOT NULL) OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@URL IS NOT NULL AND @Version < 11.03339) OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @URL is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @URL is not supported.' END IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) BEGIN - SET @ErrorMessage = 'The value for the parameter @Credential is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Credential is not supported.' END IF @MirrorCleanupTime < 0 OR (@MirrorCleanupTime IS NOT NULL AND @MirrorDirectory IS NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorCleanupTime is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MirrorCleanupTime is not supported.' END IF @MirrorCleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @MirrorCleanupMode IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorCleanupMode is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MirrorCleanupMode is not supported.' END IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @URL IS NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @MirrorURL is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MirrorURL is not supported.' END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Updateability is not supported.' END IF @AdaptiveCompression NOT IN('SIZE','SPEED') OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) BEGIN - SET @ErrorMessage = 'The value for the parameter @AdaptiveCompression is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @AdaptiveCompression is not supported.' END IF (@ModificationLevel IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN - SET @ErrorMessage = 'The value for the parameter @ModificationLevel is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @ModificationLevel is not supported.' END IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN - SET @ErrorMessage = 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' END IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN - SET @ErrorMessage = 'The value for the parameter @TimeSinceLastLogBackup is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @TimeSinceLastLogBackup is not supported.' END IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostHost is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DataDomainBoostHost is not supported.' END IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostUser is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DataDomainBoostUser is not supported.' END IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostDevicePath is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.' END IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @DataDomainBoostLockboxPath is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.' END IF @DirectoryStructure = '' BEGIN - SET @ErrorMessage = 'The value for the parameter @DirectoryStructure is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DirectoryStructure is not supported.' END IF @AvailabilityGroupDirectoryStructure = '' BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.' END IF @FileName IS NULL OR @FileName = '' OR @FileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') OR @FileName LIKE '%{DirectorySeperator}%' OR @FileName LIKE '%/%' OR @FileName LIKE '%\%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileName is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FileName is not supported.' END IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) OR @AvailabilityGroupFileName = '' OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' OR @AvailabilityGroupFileName LIKE '%/%' OR @AvailabilityGroupFileName LIKE '%\%' BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupFileName is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.' END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @FileName contains one or more tokens that are not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The parameter @FileName contains one or more tokens that are not supported.' END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' + OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - SET @ErrorMessage = 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' END IF @FileExtensionFull LIKE '%.%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileExtensionFull is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FileExtensionFull is not supported.' END IF @FileExtensionDiff LIKE '%.%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileExtensionDiff is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FileExtensionDiff is not supported.' END IF @FileExtensionLog LIKE '%.%' BEGIN - SET @ErrorMessage = 'The value for the parameter @FileExtensionLog is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FileExtensionLog is not supported.' END IF @Init NOT IN('Y','N') OR @Init IS NULL OR (@Init = 'Y' AND @BackupType = 'LOG') OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Init is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Init is not supported.' END IF @Format NOT IN('Y','N') OR @Format IS NULL OR (@Format = 'Y' AND @BackupType = 'LOG') OR (@Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - SET @ErrorMessage = 'The value for the parameter @Format is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Format is not supported.' END IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL) OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED') OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG') BEGIN - SET @ErrorMessage = 'The value for the parameter @ObjectLevelRecovery is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.' END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.' END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.' END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LogToTable is not supported.' END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Execute is not supported.' END - IF @Error <> 0 + IF EXISTS(SELECT * FROM @Errors) BEGIN - SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - SET @ReturnCode = @Error - GOTO Logging + INSERT INTO @Errors ([Message]) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.' END ---------------------------------------------------------------------------------------------------- @@ -2019,10 +1802,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -2032,10 +1813,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END ---------------------------------------------------------------------------------------------------- @@ -2044,10 +1823,36 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + END + + ---------------------------------------------------------------------------------------------------- + --// Raise errors //-- + ---------------------------------------------------------------------------------------------------- + + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + + OPEN ErrorCursor + + FETCH ErrorCursor INTO @CurrentMessage + + WHILE @@FETCH_STATUS = 0 + BEGIN + RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT + + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage + END + + CLOSE ErrorCursor + + DEALLOCATE ErrorCursor + + IF EXISTS (SELECT * FROM @Errors) + BEGIN + SET @ReturnCode = 50000 + GOTO Logging END ---------------------------------------------------------------------------------------------------- @@ -2194,7 +1999,7 @@ BEGIN BEGIN TRANSACTION UPDATE [Queue] - SET QueueStartTime = GETDATE(), + SET QueueStartTime = SYSDATETIME(), SessionID = @@SPID, RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID) @@ -2274,7 +2079,7 @@ BEGIN AND NOT EXISTS (SELECT * FROM sys.dm_exec_requests WHERE session_id = QueueDatabase.SessionID AND request_id = QueueDatabase.RequestID AND start_time = QueueDatabase.RequestStartTime) UPDATE QueueDatabase - SET DatabaseStartTime = GETDATE(), + SET DatabaseStartTime = SYSDATETIME(), DatabaseEndTime = NULL, SessionID = @@SPID, RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), @@ -2317,17 +2122,11 @@ BEGIN @CurrentDatabaseState = state_desc, @CurrentInStandby = is_in_standby, @CurrentRecoveryModel = recovery_model_desc, + @CurrentIsEncrypted = is_encrypted, @CurrentDatabaseSize = (SELECT SUM(CAST(size AS bigint)) FROM sys.master_files WHERE [type] = 0 AND database_id = sys.databases.database_id) FROM sys.databases WHERE [name] = @CurrentDatabaseName - IF @Version >= 10 - BEGIN - SET @CurrentCommand06 = 'SELECT @ParamIsEncrypted = is_encrypted FROM sys.databases WHERE name = @ParamDatabaseName' - - EXECUTE sp_executesql @stmt = @CurrentCommand06, @params = N'@ParamDatabaseName nvarchar(max), @ParamIsEncrypted bit OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamIsEncrypted = @CurrentIsEncrypted OUTPUT - END - SELECT @CurrentMaxTransferSize = CASE WHEN @MaxTransferSize IS NOT NULL THEN @MaxTransferSize WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND @Version >= 13.04446 THEN 65537 @@ -2367,13 +2166,6 @@ BEGIN AND [type] = 0 AND [file_id] = 1 - -- Workaround for a bug in SQL Server 2005 - IF @Version >= 9 AND @Version < 10 - AND EXISTS(SELECT * FROM sys.master_files WHERE database_id = DB_ID(@CurrentDatabaseName) AND [type] = 0 AND [file_id] = 1 AND differential_base_lsn IS NOT NULL AND differential_base_guid IS NOT NULL AND differential_base_time IS NULL) - BEGIN - SET @CurrentDifferentialBaseLSN = NULL - END - IF @CurrentDatabaseState = 'ONLINE' BEGIN SELECT @CurrentLogLSN = last_log_backup_lsn @@ -2442,7 +2234,7 @@ BEGIN SET @CurrentLogShippingRole = 'SECONDARY' END - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) @@ -2546,7 +2338,7 @@ BEGIN AND NOT ((@CurrentLogShippingRole = 'PRIMARY' AND @CurrentLogShippingRole IS NOT NULL) AND @CurrentBackupType = 'LOG') AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') - AND NOT (@CurrentBackupType = 'LOG' AND @LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NOT NULL AND NOT(@CurrentLogSizeSinceLastLogBackup >= @LogSizeSinceLastLogBackup OR @CurrentLogSizeSinceLastLogBackup IS NULL OR DATEDIFF(SECOND,@CurrentLastLogBackup,GETDATE()) >= @TimeSinceLastLogBackup OR @CurrentLastLogBackup IS NULL)) + AND NOT (@CurrentBackupType = 'LOG' AND @LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NOT NULL AND NOT(@CurrentLogSizeSinceLastLogBackup >= @LogSizeSinceLastLogBackup OR @CurrentLogSizeSinceLastLogBackup IS NULL OR DATEDIFF(SECOND,@CurrentLastLogBackup,SYSDATETIME()) >= @TimeSinceLastLogBackup OR @CurrentLastLogBackup IS NULL)) BEGIN IF @CurrentBackupType = 'LOG' AND (@CleanupTime IS NOT NULL OR @MirrorCleanupTime IS NOT NULL) @@ -2559,7 +2351,7 @@ BEGIN AND database_name = @CurrentDatabaseName END - SET @CurrentDate = GETDATE() + SET @CurrentDate = SYSDATETIME() INSERT INTO @CurrentCleanupDates (CleanupDate) SELECT @CurrentDate @@ -2749,6 +2541,7 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,@CurrentDate) AS nvarchar),6)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),3))) END @@ -2896,6 +2689,7 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,@CurrentDate) AS nvarchar),3)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,@CurrentDate) AS nvarchar),6)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',@CurrentNumberOfFiles) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar),4))) @@ -3088,7 +2882,7 @@ BEGIN IF @CleanupMode = 'BEFORE_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@CleanupTime),GETDATE()), 0 + SELECT DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 0 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -3104,7 +2898,7 @@ BEGIN IF @MirrorCleanupMode = 'BEFORE_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@MirrorCleanupTime),GETDATE()), 1 + SELECT DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 1 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -3150,21 +2944,21 @@ BEGIN BEGIN SET @CurrentCommandType02 = 'xp_slssqlmaint' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN SET @CurrentCommandType02 = 'sqbutility' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' + SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN SET @CurrentCommandType02 = 'xp_ss_delete' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END EXECUTE @CurrentCommandOutput02 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand02, @CommandType = @CurrentCommandType02, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -3204,54 +2998,54 @@ BEGIN WHEN @CurrentBackupType = 'LOG' THEN 'BACKUP LOG ' + QUOTENAME(@CurrentDatabaseName) END - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ' READ_WRITE_FILEGROUPS' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ' READ_WRITE_FILEGROUPS' - SET @CurrentCommand03 = @CurrentCommand03 + ' TO' + SET @CurrentCommand03 += ' TO' - SELECT @CurrentCommand03 = @CurrentCommand03 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand03 += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SET @CurrentCommand03 = @CurrentCommand03 + ' MIRROR TO' + SET @CurrentCommand03 += ' MIRROR TO' - SELECT @CurrentCommand03 = @CurrentCommand03 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand03 += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 1 ORDER BY FilePath ASC END - SET @CurrentCommand03 = @CurrentCommand03 + ' WITH ' - IF @CheckSum = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand03 = @CurrentCommand03 + 'NO_CHECKSUM' + SET @CurrentCommand03 += ' WITH ' + IF @CheckSum = 'Y' SET @CurrentCommand03 += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand03 += 'NO_CHECKSUM' IF @Version >= 10 BEGIN - SET @CurrentCommand03 = @CurrentCommand03 + CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND @Version >= 13 AND @CurrentMaxTransferSize > 65536)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END + SET @CurrentCommand03 += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND @Version >= 13 AND @CurrentMaxTransferSize > 65536)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END END - IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 = @CurrentCommand03 + ', DIFFERENTIAL' + IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 += ', DIFFERENTIAL' IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SET @CurrentCommand03 = @CurrentCommand03 + ', FORMAT' + SET @CurrentCommand03 += ', FORMAT' END - IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', COPY_ONLY' - IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 = @CurrentCommand03 + ', NORECOVERY' - IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', INIT' - IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', FORMAT' - IF @BlockSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) - IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar) - IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' - IF @Encrypt = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', ENCRYPTION (ALGORITHM = ' + UPPER(@EncryptionAlgorithm) + ', ' - IF @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + 'SERVER CERTIFICATE = ' + QUOTENAME(@ServerCertificate) - IF @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + 'SERVER ASYMMETRIC KEY = ' + QUOTENAME(@ServerAsymmetricKey) - IF @Encrypt = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ')' - IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' + IF @CopyOnly = 'Y' SET @CurrentCommand03 += ', COPY_ONLY' + IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 += ', NORECOVERY' + IF @Init = 'Y' SET @CurrentCommand03 += ', INIT' + IF @Format = 'Y' SET @CurrentCommand03 += ', FORMAT' + IF @BlockSize IS NOT NULL SET @CurrentCommand03 += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) + IF @BufferCount IS NOT NULL SET @CurrentCommand03 += ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) + IF @Description IS NOT NULL SET @CurrentCommand03 += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' + IF @Encrypt = 'Y' SET @CurrentCommand03 += ', ENCRYPTION (ALGORITHM = ' + UPPER(@EncryptionAlgorithm) + ', ' + IF @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL SET @CurrentCommand03 += 'SERVER CERTIFICATE = ' + QUOTENAME(@ServerCertificate) + IF @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL SET @CurrentCommand03 += 'SERVER ASYMMETRIC KEY = ' + QUOTENAME(@ServerAsymmetricKey) + IF @Encrypt = 'Y' SET @CurrentCommand03 += ')' + IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand03 += ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' END IF @BackupSoftware = 'LITESPEED' @@ -3266,40 +3060,40 @@ BEGIN WHEN @CurrentBackupType = 'LOG' THEN 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_backup_log @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' END - SELECT @CurrentCommand03 = @CurrentCommand03 + ', @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand03 += ', @filename = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SELECT @CurrentCommand03 = @CurrentCommand03 + ', @mirror = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand03 += ', @mirror = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 1 ORDER BY FilePath ASC END - SET @CurrentCommand03 = @CurrentCommand03 + ', @with = ''' - IF @CheckSum = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand03 = @CurrentCommand03 + 'NO_CHECKSUM' - IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 = @CurrentCommand03 + ', DIFFERENTIAL' - IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', COPY_ONLY' - IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 = @CurrentCommand03 + ', NORECOVERY' - IF @BlockSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) - SET @CurrentCommand03 = @CurrentCommand03 + '''' - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ', @read_write_filegroups = 1' - IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) - IF @AdaptiveCompression IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @adaptivecompression = ''' + CASE WHEN @AdaptiveCompression = 'SIZE' THEN 'Size' WHEN @AdaptiveCompression = 'SPEED' THEN 'Speed' END + '''' - IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @buffercount = ' + CAST(@BufferCount AS nvarchar) - IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @maxtransfersize = ' + CAST(@CurrentMaxTransferSize AS nvarchar) - IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @threads = ' + CAST(@Threads AS nvarchar) - IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @init = 1' - IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @format = 1' - IF @Throttle IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @throttle = ' + CAST(@Throttle AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' - IF @ObjectLevelRecoveryMap = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @olrmap = 1' - - IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @cryptlevel = ' + CASE + SET @CurrentCommand03 += ', @with = ''' + IF @CheckSum = 'Y' SET @CurrentCommand03 += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand03 += 'NO_CHECKSUM' + IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 += ', DIFFERENTIAL' + IF @CopyOnly = 'Y' SET @CurrentCommand03 += ', COPY_ONLY' + IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 += ', NORECOVERY' + IF @BlockSize IS NOT NULL SET @CurrentCommand03 += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) + SET @CurrentCommand03 += '''' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ', @read_write_filegroups = 1' + IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 += ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) + IF @AdaptiveCompression IS NOT NULL SET @CurrentCommand03 += ', @adaptivecompression = ''' + CASE WHEN @AdaptiveCompression = 'SIZE' THEN 'Size' WHEN @AdaptiveCompression = 'SPEED' THEN 'Speed' END + '''' + IF @BufferCount IS NOT NULL SET @CurrentCommand03 += ', @buffercount = ' + CAST(@BufferCount AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 += ', @maxtransfersize = ' + CAST(@CurrentMaxTransferSize AS nvarchar) + IF @Threads IS NOT NULL SET @CurrentCommand03 += ', @threads = ' + CAST(@Threads AS nvarchar) + IF @Init = 'Y' SET @CurrentCommand03 += ', @init = 1' + IF @Format = 'Y' SET @CurrentCommand03 += ', @format = 1' + IF @Throttle IS NOT NULL SET @CurrentCommand03 += ', @throttle = ' + CAST(@Throttle AS nvarchar) + IF @Description IS NOT NULL SET @CurrentCommand03 += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' + IF @ObjectLevelRecoveryMap = 'Y' SET @CurrentCommand03 += ', @olrmap = 1' + + IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 += ', @cryptlevel = ' + CASE WHEN @EncryptionAlgorithm = 'RC2_40' THEN '0' WHEN @EncryptionAlgorithm = 'RC2_56' THEN '1' WHEN @EncryptionAlgorithm = 'RC2_112' THEN '2' @@ -3311,8 +3105,8 @@ BEGIN WHEN @EncryptionAlgorithm = 'AES_256' THEN '8' END - IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand03 = @CurrentCommand03 + ' IF @ReturnCode <> 0 RAISERROR(''Error performing LiteSpeed backup.'', 16, 1)' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand03 += ' IF @ReturnCode <> 0 RAISERROR(''Error performing LiteSpeed backup.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -3324,40 +3118,40 @@ BEGIN WHEN @CurrentBackupType = 'LOG' THEN 'BACKUP LOG ' + QUOTENAME(@CurrentDatabaseName) END - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ' READ_WRITE_FILEGROUPS' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ' READ_WRITE_FILEGROUPS' - SET @CurrentCommand03 = @CurrentCommand03 + ' TO' + SET @CurrentCommand03 += ' TO' - SELECT @CurrentCommand03 = @CurrentCommand03 + ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand03 += ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC - SET @CurrentCommand03 = @CurrentCommand03 + ' WITH ' + SET @CurrentCommand03 += ' WITH ' IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SET @CurrentCommand03 = @CurrentCommand03 + ' MIRRORFILE' + ' = N''' + REPLACE((SELECT FilePath FROM @CurrentFiles WHERE Mirror = 1),'''','''''') + ''', ' + SET @CurrentCommand03 += ' MIRRORFILE' + ' = N''' + REPLACE((SELECT FilePath FROM @CurrentFiles WHERE Mirror = 1),'''','''''') + ''', ' END - IF @CheckSum = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand03 = @CurrentCommand03 + 'NO_CHECKSUM' - IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 = @CurrentCommand03 + ', DIFFERENTIAL' - IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', COPY_ONLY' - IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 = @CurrentCommand03 + ', NORECOVERY' - IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', INIT' - IF @Format = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', FORMAT' - IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', COMPRESSION = ' + CAST(@CompressionLevel AS nvarchar) - IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', THREADCOUNT = ' + CAST(@Threads AS nvarchar) - IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' - - IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', KEYSIZE = ' + CASE + IF @CheckSum = 'Y' SET @CurrentCommand03 += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand03 += 'NO_CHECKSUM' + IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 += ', DIFFERENTIAL' + IF @CopyOnly = 'Y' SET @CurrentCommand03 += ', COPY_ONLY' + IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 += ', NORECOVERY' + IF @Init = 'Y' SET @CurrentCommand03 += ', INIT' + IF @Format = 'Y' SET @CurrentCommand03 += ', FORMAT' + IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 += ', COMPRESSION = ' + CAST(@CompressionLevel AS nvarchar) + IF @Threads IS NOT NULL SET @CurrentCommand03 += ', THREADCOUNT = ' + CAST(@Threads AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) + IF @Description IS NOT NULL SET @CurrentCommand03 += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' + + IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 += ', KEYSIZE = ' + CASE WHEN @EncryptionAlgorithm = 'AES_128' THEN '128' WHEN @EncryptionAlgorithm = 'AES_256' THEN '256' END - IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 += ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand03,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLBackup backup.'', 16, 1)' END @@ -3367,32 +3161,32 @@ BEGIN SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_backup @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' - SELECT @CurrentCommand03 = @CurrentCommand03 + ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand03 += ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC - SELECT @CurrentCommand03 = @CurrentCommand03 + ', @mirrorfile = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand03 += ', @mirrorfile = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 1 ORDER BY FilePath ASC - SET @CurrentCommand03 = @CurrentCommand03 + ', @backuptype = ' + CASE WHEN @CurrentBackupType = 'FULL' THEN '''Full''' WHEN @CurrentBackupType = 'DIFF' THEN '''Differential''' WHEN @CurrentBackupType = 'LOG' THEN '''Log''' END - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ', @readwritefilegroups = 1' - SET @CurrentCommand03 = @CurrentCommand03 + ', @checksum = ' + CASE WHEN @CheckSum = 'Y' THEN '1' WHEN @CheckSum = 'N' THEN '0' END - SET @CurrentCommand03 = @CurrentCommand03 + ', @copyonly = ' + CASE WHEN @CopyOnly = 'Y' THEN '1' WHEN @CopyOnly = 'N' THEN '0' END - IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) - IF @Threads IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @threads = ' + CAST(@Threads AS nvarchar) - IF @Init = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ', @overwrite = 1' - IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' + SET @CurrentCommand03 += ', @backuptype = ' + CASE WHEN @CurrentBackupType = 'FULL' THEN '''Full''' WHEN @CurrentBackupType = 'DIFF' THEN '''Differential''' WHEN @CurrentBackupType = 'LOG' THEN '''Log''' END + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ', @readwritefilegroups = 1' + SET @CurrentCommand03 += ', @checksum = ' + CASE WHEN @CheckSum = 'Y' THEN '1' WHEN @CheckSum = 'N' THEN '0' END + SET @CurrentCommand03 += ', @copyonly = ' + CASE WHEN @CopyOnly = 'Y' THEN '1' WHEN @CopyOnly = 'N' THEN '0' END + IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 += ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) + IF @Threads IS NOT NULL SET @CurrentCommand03 += ', @threads = ' + CAST(@Threads AS nvarchar) + IF @Init = 'Y' SET @CurrentCommand03 += ', @overwrite = 1' + IF @Description IS NOT NULL SET @CurrentCommand03 += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' - IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @encryptiontype = N''' + CASE + IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 += ', @encryptiontype = N''' + CASE WHEN @EncryptionAlgorithm = 'AES_128' THEN 'AES128' WHEN @EncryptionAlgorithm = 'AES_256' THEN 'AES256' END + '''' - IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ', @encryptedbackuppassword = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand03 = @CurrentCommand03 + ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 += ', @encryptedbackuppassword = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand03 += ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' @@ -3401,41 +3195,41 @@ BEGIN SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.emc_run_backup ''' - SET @CurrentCommand03 = @CurrentCommand03 + ' -c ' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar) END + SET @CurrentCommand03 += ' -c ' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar) END - SET @CurrentCommand03 = @CurrentCommand03 + ' -l ' + CASE + SET @CurrentCommand03 += ' -l ' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'full' WHEN @CurrentBackupType = 'DIFF' THEN 'diff' WHEN @CurrentBackupType = 'LOG' THEN 'incr' END - IF @NoRecovery = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ' -H' + IF @NoRecovery = 'Y' SET @CurrentCommand03 += ' -H' - IF @CleanupTime IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -y +' + CAST(@CleanupTime/24 + CASE WHEN @CleanupTime%24 > 0 THEN 1 ELSE 0 END AS nvarchar) + 'd' + IF @CleanupTime IS NOT NULL SET @CurrentCommand03 += ' -y +' + CAST(@CleanupTime/24 + CASE WHEN @CleanupTime%24 > 0 THEN 1 ELSE 0 END AS nvarchar) + 'd' - IF @CheckSum = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ' -k' + IF @CheckSum = 'Y' SET @CurrentCommand03 += ' -k' - SET @CurrentCommand03 = @CurrentCommand03 + ' -S ' + CAST(@CurrentNumberOfFiles AS nvarchar) + SET @CurrentCommand03 += ' -S ' + CAST(@CurrentNumberOfFiles AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -b "' + REPLACE(@Description,'''','''''') + '"' + IF @Description IS NOT NULL SET @CurrentCommand03 += ' -b "' + REPLACE(@Description,'''','''''') + '"' - IF @BufferCount IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -O "BUFFERCOUNT=' + CAST(@BufferCount AS nvarchar) + '"' + IF @BufferCount IS NOT NULL SET @CurrentCommand03 += ' -O "BUFFERCOUNT=' + CAST(@BufferCount AS nvarchar) + '"' - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 = @CurrentCommand03 + ' -O "READ_WRITE_FILEGROUPS"' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ' -O "READ_WRITE_FILEGROUPS"' - IF @DataDomainBoostHost IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_HOST=' + REPLACE(@DataDomainBoostHost,'''','''''') + '"' - IF @DataDomainBoostUser IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_USER=' + REPLACE(@DataDomainBoostUser,'''','''''') + '"' - IF @DataDomainBoostDevicePath IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DEVICE_PATH=' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '"' - IF @DataDomainBoostLockboxPath IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_DFA_SI_DD_LOCKBOX_PATH=' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '"' - SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_SKIP_NON_BACKUPABLE_STATE_DB=TRUE"' - IF @CopyOnly = 'Y' SET @CurrentCommand03 = @CurrentCommand03 + ' -a "NSR_COPY_ONLY=TRUE"' + IF @DataDomainBoostHost IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DD_HOST=' + REPLACE(@DataDomainBoostHost,'''','''''') + '"' + IF @DataDomainBoostUser IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DD_USER=' + REPLACE(@DataDomainBoostUser,'''','''''') + '"' + IF @DataDomainBoostDevicePath IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DEVICE_PATH=' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '"' + IF @DataDomainBoostLockboxPath IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DD_LOCKBOX_PATH=' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '"' + SET @CurrentCommand03 += ' -a "NSR_SKIP_NON_BACKUPABLE_STATE_DB=TRUE"' + IF @CopyOnly = 'Y' SET @CurrentCommand03 += ' -a "NSR_COPY_ONLY=TRUE"' - IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand03 = @CurrentCommand03 + ' "MSSQL' + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' - IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand03 = @CurrentCommand03 + ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar) + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' + IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand03 += ' "MSSQL' + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' + IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand03 += ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar) + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' - SET @CurrentCommand03 = @CurrentCommand03 + '''' + SET @CurrentCommand03 += '''' - SET @CurrentCommand03 = @CurrentCommand03 + ' IF @ReturnCode <> 0 RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' + SET @CurrentCommand03 += ' IF @ReturnCode <> 0 RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' END EXECUTE @CurrentCommandOutput03 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand03, @CommandType = @CurrentCommandType03, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -3466,15 +3260,15 @@ BEGIN SET @CurrentCommand04 = 'RESTORE VERIFYONLY FROM' - SELECT @CurrentCommand04 = @CurrentCommand04 + ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand04 += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 = @CurrentCommand04 + ' WITH ' - IF @CheckSum = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand04 = @CurrentCommand04 + 'NO_CHECKSUM' - IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand04 = @CurrentCommand04 + ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' + SET @CurrentCommand04 += ' WITH ' + IF @CheckSum = 'Y' SET @CurrentCommand04 += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand04 += 'NO_CHECKSUM' + IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand04 += ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' END IF @BackupSoftware = 'LITESPEED' @@ -3483,18 +3277,18 @@ BEGIN SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_restore_verifyonly' - SELECT @CurrentCommand04 = @CurrentCommand04 + ' @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand04 += ' @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 = @CurrentCommand04 + ', @with = ''' - IF @CheckSum = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand04 = @CurrentCommand04 + 'NO_CHECKSUM' - SET @CurrentCommand04 = @CurrentCommand04 + '''' - IF @EncryptionKey IS NOT NULL SET @CurrentCommand04 = @CurrentCommand04 + ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand04 += ', @with = ''' + IF @CheckSum = 'Y' SET @CurrentCommand04 += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand04 += 'NO_CHECKSUM' + SET @CurrentCommand04 += '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand04 += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand04 = @CurrentCommand04 + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying LiteSpeed backup.'', 16, 1)' + SET @CurrentCommand04 += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying LiteSpeed backup.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -3503,15 +3297,15 @@ BEGIN SET @CurrentCommand04 = 'RESTORE VERIFYONLY FROM' - SELECT @CurrentCommand04 = @CurrentCommand04 + ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand04 += ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 = @CurrentCommand04 + ' WITH ' - IF @CheckSum = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand04 = @CurrentCommand04 + 'NO_CHECKSUM' - IF @EncryptionKey IS NOT NULL SET @CurrentCommand04 = @CurrentCommand04 + ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand04 += ' WITH ' + IF @CheckSum = 'Y' SET @CurrentCommand04 += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand04 += 'NO_CHECKSUM' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand04 += ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand04,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLBackup backup.'', 16, 1)' END @@ -3522,12 +3316,12 @@ BEGIN SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_verify @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' - SELECT @CurrentCommand04 = @CurrentCommand04 + ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand04 += ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 = @CurrentCommand04 + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' + SET @CurrentCommand04 += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' END EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -3554,7 +3348,7 @@ BEGIN IF @CleanupMode = 'AFTER_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@CleanupTime),GETDATE()), 0 + SELECT DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 0 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -3570,7 +3364,7 @@ BEGIN IF @MirrorCleanupMode = 'AFTER_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@MirrorCleanupTime),GETDATE()), 1 + SELECT DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 1 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -3617,21 +3411,21 @@ BEGIN BEGIN SET @CurrentCommandType05 = 'xp_slssqlmaint' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN SET @CurrentCommandType05 = 'sqbutility' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' + SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN SET @CurrentCommandType05 = 'xp_ss_delete' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,GETDATE()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -3669,7 +3463,7 @@ BEGIN IF @DatabasesInParallel = 'Y' BEGIN UPDATE dbo.QueueDatabase - SET DatabaseEndTime = GETDATE() + SET DatabaseEndTime = SYSDATETIME() WHERE QueueID = @QueueID AND DatabaseName = @CurrentDatabaseName END @@ -3724,7 +3518,6 @@ BEGIN SET @CurrentModifiedExtentPageCount = NULL SET @CurrentCommand03 = NULL - SET @CurrentCommand06 = NULL SET @CurrentCommand07 = NULL SET @CurrentCommandOutput03 = NULL @@ -3744,7 +3537,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- Logging: - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT @@ -3797,7 +3590,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-03 23:04:49 //-- + --// Version: 2020-01-05 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3808,18 +3601,16 @@ BEGIN DECLARE @ErrorMessage nvarchar(max) DECLARE @Severity int - DECLARE @StartTime datetime - DECLARE @SchemaName nvarchar(max) - DECLARE @ObjectName nvarchar(max) - DECLARE @VersionTimestamp nvarchar(max) + DECLARE @StartTime datetime2 = SYSDATETIME() + DECLARE @SchemaName nvarchar(max) = OBJECT_SCHEMA_NAME(@@PROCID) + DECLARE @ObjectName nvarchar(max) = OBJECT_NAME(@@PROCID) + DECLARE @VersionTimestamp nvarchar(max) = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) DECLARE @Parameters nvarchar(max) - DECLARE @Version numeric(18,10) DECLARE @HostPlatform nvarchar(max) - DECLARE @AmazonRDS bit DECLARE @QueueID int - DECLARE @QueueStartTime datetime + DECLARE @QueueStartTime datetime2 DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -3874,15 +3665,20 @@ BEGIN DECLARE @CurrentCommandType08 nvarchar(max) DECLARE @CurrentCommandType09 nvarchar(max) + DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, + [Message] nvarchar(max)) + + DECLARE @CurrentMessage nvarchar(max) + DECLARE @tmpDatabases TABLE (ID int IDENTITY, DatabaseName nvarchar(max), DatabaseType nvarchar(max), AvailabilityGroup bit, [Snapshot] bit, StartPosition int, - LastCommandTime datetime, + LastCommandTime datetime2, DatabaseSize bigint, - LastGoodCheckDbTime datetime, + LastGoodCheckDbTime datetime2, [Order] int, Selected bit, Completed bit, @@ -3940,17 +3736,12 @@ BEGIN DECLARE @SelectedCheckCommands TABLE (CheckCommand nvarchar(max)) - DECLARE @Error int - DECLARE @ReturnCode int + DECLARE @Error int = 0 + DECLARE @ReturnCode int = 0 - DECLARE @EmptyLine nvarchar(max) + DECLARE @EmptyLine nvarchar(max) = CHAR(9) - SET @Error = 0 - SET @ReturnCode = 0 - - SET @EmptyLine = CHAR(9) - - SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) + DECLARE @Version numeric(18,10) = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) IF @Version >= 14 BEGIN @@ -3962,36 +3753,31 @@ BEGIN SET @HostPlatform = 'Windows' END - SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartTime = GETDATE() - SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) - SET @ObjectName = OBJECT_NAME(@@PROCID) - SET @VersionTimestamp = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) - SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @CheckCommands = ' + ISNULL('''' + REPLACE(@CheckCommands,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @PhysicalOnly = ' + ISNULL('''' + REPLACE(@PhysicalOnly,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @NoIndex = ' + ISNULL('''' + REPLACE(@NoIndex,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @ExtendedLogicalChecks = ' + ISNULL('''' + REPLACE(@ExtendedLogicalChecks,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @TabLock = ' + ISNULL('''' + REPLACE(@TabLock,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FileGroups = ' + ISNULL('''' + REPLACE(@FileGroups,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Objects = ' + ISNULL('''' + REPLACE(@Objects,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @AvailabilityGroupReplicas = ' + ISNULL('''' + REPLACE(@AvailabilityGroupReplicas,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @Parameters += ', @CheckCommands = ' + ISNULL('''' + REPLACE(@CheckCommands,'''','''''') + '''','NULL') + SET @Parameters += ', @PhysicalOnly = ' + ISNULL('''' + REPLACE(@PhysicalOnly,'''','''''') + '''','NULL') + SET @Parameters += ', @NoIndex = ' + ISNULL('''' + REPLACE(@NoIndex,'''','''''') + '''','NULL') + SET @Parameters += ', @ExtendedLogicalChecks = ' + ISNULL('''' + REPLACE(@ExtendedLogicalChecks,'''','''''') + '''','NULL') + SET @Parameters += ', @TabLock = ' + ISNULL('''' + REPLACE(@TabLock,'''','''''') + '''','NULL') + SET @Parameters += ', @FileGroups = ' + ISNULL('''' + REPLACE(@FileGroups,'''','''''') + '''','NULL') + SET @Parameters += ', @Objects = ' + ISNULL('''' + REPLACE(@Objects,'''','''''') + '''','NULL') + SET @Parameters += ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') + SET @Parameters += ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') + SET @Parameters += ', @AvailabilityGroupReplicas = ' + ISNULL('''' + REPLACE(@AvailabilityGroupReplicas,'''','''''') + '''','NULL') + SET @Parameters += ', @Updateability = ' + ISNULL('''' + REPLACE(@Updateability,'''','''''') + '''','NULL') + SET @Parameters += ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') + SET @Parameters += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') + SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') + SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') + SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') + SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -4028,80 +3814,56 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' END IF @@TRANCOUNT <> 0 BEGIN - SET @ErrorMessage = 'The transaction count is not 0.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - END - - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO Logging + INSERT INTO @Errors ([Message]) + SELECT 'The transaction count is not 0.' END ---------------------------------------------------------------------------------------------------- @@ -4228,10 +3990,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Databases is not supported.' END ---------------------------------------------------------------------------------------------------- @@ -4325,26 +4085,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.' END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' END ---------------------------------------------------------------------------------------------------- @@ -4482,147 +4236,110 @@ BEGIN IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) OR EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) OR NOT EXISTS (SELECT * FROM @SelectedCheckCommands) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG'))) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE'))) BEGIN - SET @ErrorMessage = 'The value for the parameter @CheckCommands is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @CheckCommands is not supported.' END IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @PhysicalOnly is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @PhysicalOnly is not supported.' END IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @NoIndex is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @NoIndex is not supported.' END IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL OR (@ExtendedLogicalChecks = 'Y' AND NOT @Version >= 10) OR (@PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y') BEGIN - SET @ErrorMessage = 'The value for the parameter @ExtendedLogicalChecks is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @ExtendedLogicalChecks is not supported.' END IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @TabLock is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @TabLock is not supported.' END IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) OR (@FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups)) OR (@FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP')) BEGIN - SET @ErrorMessage = 'The value for the parameter @FileGroups is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FileGroups is not supported.' END IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) OR (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) OR (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Objects is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Objects is not supported.' END IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MaxDOP is not supported.' END IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroupReplicas is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @AvailabilityGroupReplicas is not supported.' END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Updateability is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Updateability is not supported.' END IF @TimeLimit < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @TimeLimit is not supported.' END IF @LockTimeout < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LockTimeout is not supported.' END IF @LockMessageSeverity NOT IN(10,16) BEGIN - SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.' END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.' END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.' END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LogToTable is not supported.' END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Execute is not supported.' END - IF @Error <> 0 + IF EXISTS(SELECT * FROM @Errors) BEGIN - SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - SET @ReturnCode = @Error - GOTO Logging + INSERT INTO @Errors ([Message]) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.' END ---------------------------------------------------------------------------------------------------- @@ -4636,10 +4353,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -4649,10 +4364,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -4662,10 +4375,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -4675,10 +4386,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -4689,10 +4398,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -4703,10 +4410,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END ---------------------------------------------------------------------------------------------------- @@ -4715,10 +4420,36 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SET @ErrorMessage = 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + END + + ---------------------------------------------------------------------------------------------------- + --// Raise errors //-- + ---------------------------------------------------------------------------------------------------- + + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + + OPEN ErrorCursor + + FETCH ErrorCursor INTO @CurrentMessage + + WHILE @@FETCH_STATUS = 0 + BEGIN + RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT + + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage + END + + CLOSE ErrorCursor + + DEALLOCATE ErrorCursor + + IF EXISTS (SELECT * FROM @Errors) + BEGIN + SET @ReturnCode = 50000 + GOTO Logging END ---------------------------------------------------------------------------------------------------- @@ -4735,7 +4466,7 @@ BEGIN IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') BEGIN UPDATE tmpDatabases - SET LastGoodCheckDbTime = NULLIF(CAST(DATABASEPROPERTYEX (DatabaseName,'LastGoodCheckDbTime') AS datetime),'1900-01-01 00:00:00.000') + SET LastGoodCheckDbTime = NULLIF(CAST(DATABASEPROPERTYEX (DatabaseName,'LastGoodCheckDbTime') AS datetime2),'1900-01-01 00:00:00.000') FROM @tmpDatabases tmpDatabases END @@ -4890,7 +4621,7 @@ BEGIN BEGIN TRANSACTION UPDATE [Queue] - SET QueueStartTime = GETDATE(), + SET QueueStartTime = SYSDATETIME(), SessionID = @@SPID, RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID) @@ -4970,7 +4701,7 @@ BEGIN AND NOT EXISTS (SELECT * FROM sys.dm_exec_requests WHERE session_id = QueueDatabase.SessionID AND request_id = QueueDatabase.RequestID AND start_time = QueueDatabase.RequestStartTime) UPDATE QueueDatabase - SET DatabaseStartTime = GETDATE(), + SET DatabaseStartTime = SYSDATETIME(), DatabaseEndTime = NULL, SessionID = @@SPID, RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), @@ -5049,7 +4780,7 @@ BEGIN WHERE database_id = DB_ID(@CurrentDatabaseName) END - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) @@ -5111,20 +4842,20 @@ BEGIN BEGIN -- Check database - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKDB') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKDB') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType01 = 'DBCC_CHECKDB' SET @CurrentCommand01 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand01 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand01 = @CurrentCommand01 + 'DBCC CHECKDB (' + QUOTENAME(@CurrentDatabaseName) - IF @NoIndex = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', NOINDEX' - SET @CurrentCommand01 = @CurrentCommand01 + ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'N' SET @CurrentCommand01 = @CurrentCommand01 + ', DATA_PURITY' - IF @PhysicalOnly = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', PHYSICAL_ONLY' - IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', EXTENDED_LOGICAL_CHECKS' - IF @TabLock = 'Y' SET @CurrentCommand01 = @CurrentCommand01 + ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand01 = @CurrentCommand01 + ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + SET @CurrentCommand01 += 'DBCC CHECKDB (' + QUOTENAME(@CurrentDatabaseName) + IF @NoIndex = 'Y' SET @CurrentCommand01 += ', NOINDEX' + SET @CurrentCommand01 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @PhysicalOnly = 'N' SET @CurrentCommand01 += ', DATA_PURITY' + IF @PhysicalOnly = 'Y' SET @CurrentCommand01 += ', PHYSICAL_ONLY' + IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand01 += ', EXTENDED_LOGICAL_CHECKS' + IF @TabLock = 'Y' SET @CurrentCommand01 += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand01 += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -5133,7 +4864,7 @@ BEGIN END -- Check filegroups - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand02 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' @@ -5198,7 +4929,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + WHILE (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SELECT TOP 1 @CurrentFGID = ID, @CurrentFileGroupID = FileGroupID, @@ -5216,7 +4947,7 @@ BEGIN -- Does the filegroup exist? SET @CurrentCommand03 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM sys.filegroups filegroups WHERE [type] <> ''FX'' AND filegroups.data_space_id = @ParamFileGroupID AND filegroups.[name] = @ParamFileGroupName) BEGIN SET @ParamFileGroupExists = 1 END' + SET @CurrentCommand03 += 'IF EXISTS(SELECT * FROM sys.filegroups filegroups WHERE [type] <> ''FX'' AND filegroups.data_space_id = @ParamFileGroupID AND filegroups.[name] = @ParamFileGroupName) BEGIN SET @ParamFileGroupExists = 1 END' BEGIN TRY EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand03, @params = N'@ParamFileGroupID int, @ParamFileGroupName sysname, @ParamFileGroupExists bit OUTPUT', @ParamFileGroupID = @CurrentFileGroupID, @ParamFileGroupName = @CurrentFileGroupName, @ParamFileGroupExists = @CurrentFileGroupExists OUTPUT @@ -5241,12 +4972,12 @@ BEGIN SET @CurrentCommand04 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand04 = @CurrentCommand04 + 'DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) - IF @NoIndex = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + ', NOINDEX' - SET @CurrentCommand04 = @CurrentCommand04 + ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + ', PHYSICAL_ONLY' - IF @TabLock = 'Y' SET @CurrentCommand04 = @CurrentCommand04 + ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand04 = @CurrentCommand04 + ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + SET @CurrentCommand04 += 'DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) + IF @NoIndex = 'Y' SET @CurrentCommand04 += ', NOINDEX' + SET @CurrentCommand04 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @PhysicalOnly = 'Y' SET @CurrentCommand04 += ', PHYSICAL_ONLY' + IF @TabLock = 'Y' SET @CurrentCommand04 += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand04 += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -5275,15 +5006,15 @@ BEGIN END -- Check disk space allocation structures - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKALLOC') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKALLOC') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType05 = 'DBCC_CHECKALLOC' SET @CurrentCommand05 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand05 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand05 = @CurrentCommand05 + 'DBCC CHECKALLOC (' + QUOTENAME(@CurrentDatabaseName) - SET @CurrentCommand05 = @CurrentCommand05 + ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @TabLock = 'Y' SET @CurrentCommand05 = @CurrentCommand05 + ', TABLOCK' + SET @CurrentCommand05 += 'DBCC CHECKALLOC (' + QUOTENAME(@CurrentDatabaseName) + SET @CurrentCommand05 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @TabLock = 'Y' SET @CurrentCommand05 += ', TABLOCK' EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -5292,7 +5023,7 @@ BEGIN END -- Check objects - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand06 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' @@ -5358,7 +5089,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + WHILE (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SELECT TOP 1 @CurrentOID = ID, @CurrentSchemaID = SchemaID, @@ -5379,7 +5110,7 @@ BEGIN -- Does the object exist? SET @CurrentCommand07 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand07 = @CurrentCommand07 + 'IF EXISTS(SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType) BEGIN SET @ParamObjectExists = 1 END' + SET @CurrentCommand07 += 'IF EXISTS(SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType) BEGIN SET @ParamObjectExists = 1 END' BEGIN TRY EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand07, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamObjectExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamObjectExists = @CurrentObjectExists OUTPUT @@ -5404,14 +5135,14 @@ BEGIN SET @CurrentCommand08 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand08 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand08 = @CurrentCommand08 + 'DBCC CHECKTABLE (''' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + '''' - IF @NoIndex = 'Y' SET @CurrentCommand08 = @CurrentCommand08 + ', NOINDEX' - SET @CurrentCommand08 = @CurrentCommand08 + ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'N' SET @CurrentCommand08 = @CurrentCommand08 + ', DATA_PURITY' - IF @PhysicalOnly = 'Y' SET @CurrentCommand08 = @CurrentCommand08 + ', PHYSICAL_ONLY' - IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand08 = @CurrentCommand08 + ', EXTENDED_LOGICAL_CHECKS' - IF @TabLock = 'Y' SET @CurrentCommand08 = @CurrentCommand08 + ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand08 = @CurrentCommand08 + ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + SET @CurrentCommand08 += 'DBCC CHECKTABLE (''' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + '''' + IF @NoIndex = 'Y' SET @CurrentCommand08 += ', NOINDEX' + SET @CurrentCommand08 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @PhysicalOnly = 'N' SET @CurrentCommand08 += ', DATA_PURITY' + IF @PhysicalOnly = 'Y' SET @CurrentCommand08 += ', PHYSICAL_ONLY' + IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand08 += ', EXTENDED_LOGICAL_CHECKS' + IF @TabLock = 'Y' SET @CurrentCommand08 += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand08 += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) EXECUTE @CurrentCommandOutput08 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand08, @CommandType = @CurrentCommandType08, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -5443,14 +5174,14 @@ BEGIN END -- Check catalog - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType09 = 'DBCC_CHECKCATALOG' SET @CurrentCommand09 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand09 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand09 = @CurrentCommand09 + 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) - SET @CurrentCommand09 = @CurrentCommand09 + ') WITH NO_INFOMSGS' + SET @CurrentCommand09 += 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) + SET @CurrentCommand09 += ') WITH NO_INFOMSGS' EXECUTE @CurrentCommandOutput09 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand09, @CommandType = @CurrentCommandType09, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -5472,7 +5203,7 @@ BEGIN IF @DatabasesInParallel = 'Y' BEGIN UPDATE dbo.QueueDatabase - SET DatabaseEndTime = GETDATE() + SET DatabaseEndTime = SYSDATETIME() WHERE QueueID = @QueueID AND DatabaseName = @CurrentDatabaseName END @@ -5528,7 +5259,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- Logging: - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT @@ -5596,7 +5327,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-03 23:04:49 //-- + --// Version: 2020-01-05 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5611,20 +5342,18 @@ BEGIN DECLARE @ErrorMessage nvarchar(max) DECLARE @Severity int - DECLARE @StartTime datetime - DECLARE @SchemaName nvarchar(max) - DECLARE @ObjectName nvarchar(max) - DECLARE @VersionTimestamp nvarchar(max) + DECLARE @StartTime datetime2 = SYSDATETIME() + DECLARE @SchemaName nvarchar(max) = OBJECT_SCHEMA_NAME(@@PROCID) + DECLARE @ObjectName nvarchar(max) = OBJECT_NAME(@@PROCID) + DECLARE @VersionTimestamp nvarchar(max) = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) DECLARE @Parameters nvarchar(max) - DECLARE @Version numeric(18,10) DECLARE @HostPlatform nvarchar(max) - DECLARE @AmazonRDS bit DECLARE @PartitionLevelStatistics bit DECLARE @QueueID int - DECLARE @QueueStartTime datetime + DECLARE @QueueStartTime datetime2 DECLARE @CurrentDBID int DECLARE @CurrentDatabaseName nvarchar(max) @@ -5662,6 +5391,11 @@ BEGIN DECLARE @CurrentExtendedInfo06 xml DECLARE @CurrentExtendedInfo07 xml + DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, + [Message] nvarchar(max)) + + DECLARE @CurrentMessage nvarchar(max) + DECLARE @CurrentIxID int DECLARE @CurrentIxOrder int DECLARE @CurrentSchemaID int @@ -5702,7 +5436,7 @@ BEGIN DECLARE @CurrentUpdateStatistics nvarchar(max) DECLARE @CurrentStatisticsSample int DECLARE @CurrentStatisticsResample nvarchar(max) - DECLARE @CurrentDelay datetime + DECLARE @CurrentDelay datetime2 DECLARE @tmpDatabases TABLE (ID int IDENTITY, DatabaseName nvarchar(max), @@ -5800,17 +5534,12 @@ BEGIN DECLARE @CurrentUpdateStatisticsArgument nvarchar(max) DECLARE @CurrentUpdateStatisticsWithClause nvarchar(max) - DECLARE @Error int - DECLARE @ReturnCode int - - DECLARE @EmptyLine nvarchar(max) + DECLARE @Error int = 0 + DECLARE @ReturnCode int = 0 - SET @Error = 0 - SET @ReturnCode = 0 + DECLARE @EmptyLine nvarchar(max) = CHAR(9) - SET @EmptyLine = CHAR(9) - - SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) + DECLARE @Version numeric(18,10) = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) IF @Version >= 14 BEGIN @@ -5822,50 +5551,45 @@ BEGIN SET @HostPlatform = 'Windows' END - SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @StartTime = GETDATE() - SET @SchemaName = (SELECT schemas.name FROM sys.schemas schemas INNER JOIN sys.objects objects ON schemas.[schema_id] = objects.[schema_id] WHERE [object_id] = @@PROCID) - SET @ObjectName = OBJECT_NAME(@@PROCID) - SET @VersionTimestamp = SUBSTRING(OBJECT_DEFINITION(@@PROCID),CHARINDEX('--// Version: ',OBJECT_DEFINITION(@@PROCID)) + LEN('--// Version: ') + 1, 19) - SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FragmentationLow = ' + ISNULL('''' + REPLACE(@FragmentationLow,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FragmentationMedium = ' + ISNULL('''' + REPLACE(@FragmentationMedium,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FragmentationHigh = ' + ISNULL('''' + REPLACE(@FragmentationHigh,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @FragmentationLevel1 = ' + ISNULL(CAST(@FragmentationLevel1 AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @FragmentationLevel2 = ' + ISNULL(CAST(@FragmentationLevel2 AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @MinNumberOfPages = ' + ISNULL(CAST(@MinNumberOfPages AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @MaxNumberOfPages = ' + ISNULL(CAST(@MaxNumberOfPages AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @SortInTempdb = ' + ISNULL('''' + REPLACE(@SortInTempdb,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @PadIndex = ' + ISNULL('''' + REPLACE(@PadIndex,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @LOBCompaction = ' + ISNULL('''' + REPLACE(@LOBCompaction,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @UpdateStatistics = ' + ISNULL('''' + REPLACE(@UpdateStatistics,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @StatisticsModificationLevel = ' + ISNULL(CAST(@StatisticsModificationLevel AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @StatisticsResample = ' + ISNULL('''' + REPLACE(@StatisticsResample,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @PartitionLevel = ' + ISNULL('''' + REPLACE(@PartitionLevel,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @MSShippedObjects = ' + ISNULL('''' + REPLACE(@MSShippedObjects,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Indexes = ' + ISNULL('''' + REPLACE(@Indexes,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @WaitAtLowPriorityAbortAfterWait = ' + ISNULL('''' + REPLACE(@WaitAtLowPriorityAbortAfterWait,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Resumable = ' + ISNULL('''' + REPLACE(@Resumable,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') - SET @Parameters = @Parameters + ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') - SET @Parameters = @Parameters + ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + SET @Parameters += ', @FragmentationLow = ' + ISNULL('''' + REPLACE(@FragmentationLow,'''','''''') + '''','NULL') + SET @Parameters += ', @FragmentationMedium = ' + ISNULL('''' + REPLACE(@FragmentationMedium,'''','''''') + '''','NULL') + SET @Parameters += ', @FragmentationHigh = ' + ISNULL('''' + REPLACE(@FragmentationHigh,'''','''''') + '''','NULL') + SET @Parameters += ', @FragmentationLevel1 = ' + ISNULL(CAST(@FragmentationLevel1 AS nvarchar),'NULL') + SET @Parameters += ', @FragmentationLevel2 = ' + ISNULL(CAST(@FragmentationLevel2 AS nvarchar),'NULL') + SET @Parameters += ', @MinNumberOfPages = ' + ISNULL(CAST(@MinNumberOfPages AS nvarchar),'NULL') + SET @Parameters += ', @MaxNumberOfPages = ' + ISNULL(CAST(@MaxNumberOfPages AS nvarchar),'NULL') + SET @Parameters += ', @SortInTempdb = ' + ISNULL('''' + REPLACE(@SortInTempdb,'''','''''') + '''','NULL') + SET @Parameters += ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar),'NULL') + SET @Parameters += ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar),'NULL') + SET @Parameters += ', @PadIndex = ' + ISNULL('''' + REPLACE(@PadIndex,'''','''''') + '''','NULL') + SET @Parameters += ', @LOBCompaction = ' + ISNULL('''' + REPLACE(@LOBCompaction,'''','''''') + '''','NULL') + SET @Parameters += ', @UpdateStatistics = ' + ISNULL('''' + REPLACE(@UpdateStatistics,'''','''''') + '''','NULL') + SET @Parameters += ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') + SET @Parameters += ', @StatisticsModificationLevel = ' + ISNULL(CAST(@StatisticsModificationLevel AS nvarchar),'NULL') + SET @Parameters += ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar),'NULL') + SET @Parameters += ', @StatisticsResample = ' + ISNULL('''' + REPLACE(@StatisticsResample,'''','''''') + '''','NULL') + SET @Parameters += ', @PartitionLevel = ' + ISNULL('''' + REPLACE(@PartitionLevel,'''','''''') + '''','NULL') + SET @Parameters += ', @MSShippedObjects = ' + ISNULL('''' + REPLACE(@MSShippedObjects,'''','''''') + '''','NULL') + SET @Parameters += ', @Indexes = ' + ISNULL('''' + REPLACE(@Indexes,'''','''''') + '''','NULL') + SET @Parameters += ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') + SET @Parameters += ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar),'NULL') + SET @Parameters += ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar),'NULL') + SET @Parameters += ', @WaitAtLowPriorityAbortAfterWait = ' + ISNULL('''' + REPLACE(@WaitAtLowPriorityAbortAfterWait,'''','''''') + '''','NULL') + SET @Parameters += ', @Resumable = ' + ISNULL('''' + REPLACE(@Resumable,'''','''''') + '''','NULL') + SET @Parameters += ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') + SET @Parameters += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') + SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') + SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') + SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') + SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') + SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -5902,80 +5626,56 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'ANSI_NULLS has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - SET @ErrorMessage = 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - SET @ErrorMessage = 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' END 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') BEGIN - SET @ErrorMessage = 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - SET @ErrorMessage = 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - SET @ErrorMessage = 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' END IF @@TRANCOUNT <> 0 BEGIN - SET @ErrorMessage = 'The transaction count is not 0.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - END - - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - GOTO Logging + INSERT INTO @Errors ([Message]) + SELECT 'The transaction count is not 0.' END ---------------------------------------------------------------------------------------------------- @@ -6101,10 +5801,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - SET @ErrorMessage = 'The value for the parameter @Databases is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Databases is not supported.' END ---------------------------------------------------------------------------------------------------- @@ -6198,26 +5896,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - SET @ErrorMessage = 'The value for the parameter @AvailabilityGroups is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.' END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - SET @ErrorMessage = 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' END ---------------------------------------------------------------------------------------------------- @@ -6351,277 +6043,208 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationLow is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FragmentationLow is not supported.' END IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationMedium is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FragmentationMedium is not supported.' END IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'High' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationHigh is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FragmentationHigh is not supported.' END IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 >= @FragmentationLevel2 OR @FragmentationLevel1 IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationLevel1 is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FragmentationLevel1 is not supported.' END IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 <= @FragmentationLevel1 OR @FragmentationLevel2 IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @FragmentationLevel2 is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FragmentationLevel2 is not supported.' END IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @MinNumberOfPages is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MinNumberOfPages is not supported.' END IF @MaxNumberOfPages < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxNumberOfPages is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MaxNumberOfPages is not supported.' END IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @SortInTempdb is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @SortInTempdb is not supported.' END IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN - SET @ErrorMessage = 'The value for the parameter @MaxDOP is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MaxDOP is not supported.' END IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @FillFactor is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @FillFactor is not supported.' END IF @PadIndex NOT IN('Y','N') BEGIN - SET @ErrorMessage = 'The value for the parameter @PadIndex is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @PadIndex is not supported.' END IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LOBCompaction is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LOBCompaction is not supported.' END IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN - SET @ErrorMessage = 'The value for the parameter @UpdateStatistics is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @UpdateStatistics is not supported.' END IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @OnlyModifiedStatistics is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @OnlyModifiedStatistics is not supported.' END IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @StatisticsModificationLevel is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @StatisticsModificationLevel is not supported.' END IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.' END IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN - SET @ErrorMessage = 'The value for the parameter @StatisticsSample is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @StatisticsSample is not supported.' END IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL OR (@StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @StatisticsResample is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @StatisticsResample is not supported.' END IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @PartitionLevel is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @PartitionLevel is not supported.' END IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @MSShippedObjects is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MSShippedObjects is not supported.' END IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) OR (@Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes)) BEGIN - SET @ErrorMessage = 'The value for the parameter @Indexes is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Indexes is not supported.' END IF @TimeLimit < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @TimeLimit is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @TimeLimit is not supported.' END IF @Delay < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @Delay is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Delay is not supported.' END IF @WaitAtLowPriorityMaxDuration < 0 OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @WaitAtLowPriorityAbortAfterWait IS NULL) OR (@WaitAtLowPriorityMaxDuration IS NULL AND @WaitAtLowPriorityAbortAfterWait IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.' END IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) BEGIN - SET @ErrorMessage = 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.' END IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL OR (@Resumable = 'Y' AND NOT (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8))) BEGIN - SET @ErrorMessage = 'The value for the parameter @Resumable is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Resumable is not supported.' END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN - SET @ErrorMessage = 'You can only specify one of the parameters @Resumable and @SortInTempdb.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.' END IF @LockTimeout < 0 BEGIN - SET @ErrorMessage = 'The value for the parameter @LockTimeout is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LockTimeout is not supported.' END IF @LockMessageSeverity NOT IN(10,16) BEGIN - SET @ErrorMessage = 'The value for the parameter @LockMessageSeverity is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.' END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabaseOrder is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.' END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - SET @ErrorMessage = 'The value for the parameter @DatabasesInParallel is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.' END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @LogToTable is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @LogToTable is not supported.' END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - SET @ErrorMessage = 'The value for the parameter @Execute is not supported.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @Execute is not supported.' END - IF @Error <> 0 + IF EXISTS(SELECT * FROM @Errors) BEGIN - SET @ErrorMessage = 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.' - RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - SET @ReturnCode = @Error - GOTO Logging + INSERT INTO @Errors ([Message]) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.' END ---------------------------------------------------------------------------------------------------- @@ -6635,10 +6258,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -6648,10 +6269,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -6661,10 +6280,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' END SET @ErrorMessage = '' @@ -6675,10 +6292,36 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - SET @ErrorMessage = 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + INSERT INTO @Errors ([Message]) + SELECT 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + END + + ---------------------------------------------------------------------------------------------------- + --// Raise errors //-- + ---------------------------------------------------------------------------------------------------- + + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + + OPEN ErrorCursor + + FETCH ErrorCursor INTO @CurrentMessage + + WHILE @@FETCH_STATUS = 0 + BEGIN + RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT + + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage + END + + CLOSE ErrorCursor + + DEALLOCATE ErrorCursor + + IF EXISTS (SELECT * FROM @Errors) + BEGIN + SET @ReturnCode = 50000 + GOTO Logging END ---------------------------------------------------------------------------------------------------- @@ -6792,7 +6435,7 @@ BEGIN BEGIN TRANSACTION UPDATE [Queue] - SET QueueStartTime = GETDATE(), + SET QueueStartTime = SYSDATETIME(), SessionID = @@SPID, RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), RequestStartTime = (SELECT start_time FROM sys.dm_exec_requests WHERE session_id = @@SPID) @@ -6872,7 +6515,7 @@ BEGIN AND NOT EXISTS (SELECT * FROM sys.dm_exec_requests WHERE session_id = QueueDatabase.SessionID AND request_id = QueueDatabase.RequestID AND start_time = QueueDatabase.RequestStartTime) UPDATE QueueDatabase - SET DatabaseStartTime = GETDATE(), + SET DatabaseStartTime = SYSDATETIME(), DatabaseEndTime = NULL, SessionID = @@SPID, RequestID = (SELECT request_id FROM sys.dm_exec_requests WHERE session_id = @@SPID), @@ -6945,7 +6588,7 @@ BEGIN WHERE database_id = DB_ID(@CurrentDatabaseName) END - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) @@ -6995,7 +6638,7 @@ BEGIN BEGIN -- Select indexes in the current database - IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, IsComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' @@ -7197,7 +6840,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - WHILE (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + WHILE (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SELECT TOP 1 @CurrentIxID = ID, @CurrentIxOrder = [Order], @@ -7246,8 +6889,8 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand02 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - IF @CurrentIsPartition = 0 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' - IF @CurrentIsPartition = 1 SET @CurrentCommand02 = @CurrentCommand02 + 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' + IF @CurrentIsPartition = 0 SET @CurrentCommand02 += 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' + IF @CurrentIsPartition = 1 SET @CurrentCommand02 += 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' BEGIN TRY EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand02, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT @@ -7280,7 +6923,7 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand03 = @CurrentCommand03 + 'IF EXISTS(SELECT * FROM sys.stats stats INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' + SET @CurrentCommand03 += 'IF EXISTS(SELECT * FROM sys.stats stats INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' BEGIN TRY EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand03, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT @@ -7315,16 +6958,16 @@ BEGIN IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN - SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' + SET @CurrentCommand04 += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' END ELSE IF (@Version >= 10.504000 AND @Version < 11) OR @Version >= 11.03000 BEGIN - SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' + SET @CurrentCommand04 += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' END ELSE BEGIN - SET @CurrentCommand04 = @CurrentCommand04 + 'SELECT @ParamRowCount = rowcnt, @ParamModificationCounter = rowmodctr FROM sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID' + SET @CurrentCommand04 += 'SELECT @ParamRowCount = rowcnt, @ParamModificationCounter = rowmodctr FROM sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID' END BEGIN TRY @@ -7358,7 +7001,7 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand05 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand05 = @CurrentCommand05 + 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + SET @CurrentCommand05 += 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' BEGIN TRY EXECUTE sp_executesql @stmt = @CurrentCommand05, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT @@ -7493,16 +7136,16 @@ BEGIN IF @CurrentIndexID IS NOT NULL BEGIN SET @CurrentComment06 = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment06 = @CurrentComment06 + 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' - SET @CurrentComment06 = @CurrentComment06 + 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 = @CurrentComment06 + 'NewLOB: ' + CASE WHEN @CurrentIsNewLOB = 1 THEN 'Yes' WHEN @CurrentIsNewLOB = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 = @CurrentComment06 + 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 11 SET @CurrentComment06 = @CurrentComment06 + 'ColumnStore: ' + CASE WHEN @CurrentIsColumnStore = 1 THEN 'Yes' WHEN @CurrentIsColumnStore = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 = @CurrentComment06 + 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 = @CurrentComment06 + 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 = @CurrentComment06 + 'AllowPageLocks: ' + CASE WHEN @CurrentAllowPageLocks = 1 THEN 'Yes' WHEN @CurrentAllowPageLocks = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 = @CurrentComment06 + 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar),'N/A') + ', ' - SET @CurrentComment06 = @CurrentComment06 + 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar),'N/A') + SET @CurrentComment06 += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' + SET @CurrentComment06 += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 += 'NewLOB: ' + CASE WHEN @CurrentIsNewLOB = 1 THEN 'Yes' WHEN @CurrentIsNewLOB = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 11 SET @CurrentComment06 += 'ColumnStore: ' + CASE WHEN @CurrentIsColumnStore = 1 THEN 'Yes' WHEN @CurrentIsColumnStore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 += 'AllowPageLocks: ' + CASE WHEN @CurrentAllowPageLocks = 1 THEN 'Yes' WHEN @CurrentAllowPageLocks = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment06 += 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar),'N/A') + ', ' + SET @CurrentComment06 += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar),'N/A') END IF @CurrentIndexID IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) @@ -7517,11 +7160,11 @@ BEGIN IF @CurrentStatisticsID IS NOT NULL BEGIN SET @CurrentComment07 = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment07 = @CurrentComment07 + 'IndexType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' - IF @CurrentIndexID IS NOT NULL SET @CurrentComment07 = @CurrentComment07 + 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' - SET @CurrentComment07 = @CurrentComment07 + 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Y' WHEN @CurrentIsIncremental = 0 THEN 'N' ELSE 'N/A' END + ', ' - SET @CurrentComment07 = @CurrentComment07 + 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' - SET @CurrentComment07 = @CurrentComment07 + 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') + SET @CurrentComment07 += 'IndexType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' + IF @CurrentIndexID IS NOT NULL SET @CurrentComment07 += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' + SET @CurrentComment07 += 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Y' WHEN @CurrentIsIncremental = 0 THEN 'N' ELSE 'N/A' END + ', ' + SET @CurrentComment07 += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' + SET @CurrentComment07 += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') END IF @CurrentStatisticsID IS NOT NULL AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) @@ -7532,17 +7175,17 @@ BEGIN ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END - IF @CurrentIndexID IS NOT NULL AND @CurrentAction IS NOT NULL AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF @CurrentIndexID IS NOT NULL AND @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType06 = 'ALTER_INDEX' SET @CurrentCommand06 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand06 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand06 = @CurrentCommand06 + 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) - IF @CurrentResumableIndexOperation = 1 SET @CurrentCommand06 = @CurrentCommand06 + ' RESUME' - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' REBUILD' - IF @CurrentAction IN('INDEX_REORGANIZE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' REORGANIZE' - IF @CurrentIsPartition = 1 AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 = @CurrentCommand06 + ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) + SET @CurrentCommand06 += 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + IF @CurrentResumableIndexOperation = 1 SET @CurrentCommand06 += ' RESUME' + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 += ' REBUILD' + IF @CurrentAction IN('INDEX_REORGANIZE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 += ' REORGANIZE' + IF @CurrentIsPartition = 1 AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 += ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN @@ -7595,7 +7238,7 @@ BEGIN IF (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsTimestamp = 0 AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'MAX_DURATION = ' + CAST(DATEDIFF(MINUTE,GETDATE(),DATEADD(ss,@TimeLimit,@StartTime)) AS nvarchar(max)) + SELECT 'MAX_DURATION = ' + CAST(DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) AS nvarchar(max)) END IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' @@ -7627,7 +7270,7 @@ BEGIN BREAK END - SET @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + @CurrentAlterIndexArgument + ', ' + SET @CurrentAlterIndexWithClause += @CurrentAlterIndexArgument + ', ' UPDATE @CurrentAlterIndexWithClauseArguments SET Added = 1 @@ -7641,7 +7284,7 @@ BEGIN SET @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + ')' END - IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand06 = @CurrentCommand06 + @CurrentAlterIndexWithClause + IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand06 += @CurrentAlterIndexWithClause EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment06, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo06, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -7657,13 +7300,13 @@ BEGIN SET @CurrentMaxDOP = @MaxDOP - IF @CurrentStatisticsID IS NOT NULL AND @CurrentUpdateStatistics = 'Y' AND (GETDATE() < DATEADD(ss,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF @CurrentStatisticsID IS NOT NULL AND @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommandType07 = 'UPDATE_STATISTICS' SET @CurrentCommand07 = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand07 = @CurrentCommand07 + 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) + SET @CurrentCommand07 += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) BEGIN @@ -7722,9 +7365,9 @@ BEGIN SET @CurrentUpdateStatisticsWithClause = LEFT(@CurrentUpdateStatisticsWithClause,LEN(@CurrentUpdateStatisticsWithClause) - 1) END - IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + @CurrentUpdateStatisticsWithClause + IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand07 += @CurrentUpdateStatisticsWithClause - IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand07 = @CurrentCommand07 + ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand07 += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -7829,7 +7472,7 @@ BEGIN IF @DatabasesInParallel = 'Y' BEGIN UPDATE dbo.QueueDatabase - SET DatabaseEndTime = GETDATE() + SET DatabaseEndTime = SYSDATETIME() WHERE QueueID = @QueueID AND DatabaseName = @CurrentDatabaseName END @@ -7870,7 +7513,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- Logging: - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,GETDATE(),120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT @@ -7894,9 +7537,7 @@ BEGIN DECLARE @LogToTable nvarchar(max) DECLARE @DatabaseName nvarchar(max) - DECLARE @Version numeric(18,10) DECLARE @HostPlatform nvarchar(max) - DECLARE @AmazonRDS bit DECLARE @DirectorySeparator nvarchar(max) DECLARE @LogDirectory nvarchar(max) @@ -7936,9 +7577,9 @@ BEGIN DECLARE @CurrentJobStepDatabaseName nvarchar(max) DECLARE @CurrentOutputFileName nvarchar(max) - SET @Version = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) + DECLARE @Version numeric(18,10) = CAST(LEFT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - 1) + '.' + REPLACE(RIGHT(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)), LEN(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max))) - CHARINDEX('.',CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)))),'.','') AS numeric(18,10)) - SET @AmazonRDS = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END IF @Version >= 14 BEGIN @@ -7955,22 +7596,11 @@ BEGIN WHEN @HostPlatform = 'Linux' THEN '/' END - IF @Version >= 9.002047 - BEGIN - SET @TokenServer = '$' + '(ESCAPE_SQUOTE(SRVR))' - SET @TokenJobID = '$' + '(ESCAPE_SQUOTE(JOBID))' - SET @TokenStepID = '$' + '(ESCAPE_SQUOTE(STEPID))' - SET @TokenDate = '$' + '(ESCAPE_SQUOTE(DATE))' - SET @TokenTime = '$' + '(ESCAPE_SQUOTE(TIME))' - END - ELSE - BEGIN - SET @TokenServer = '$' + '(SRVR)' - SET @TokenJobID = '$' + '(JOBID)' - SET @TokenStepID = '$' + '(STEPID)' - SET @TokenDate = '$' + '(DATE)' - SET @TokenTime = '$' + '(TIME)' - END + SET @TokenServer = '$' + '(ESCAPE_SQUOTE(SRVR))' + SET @TokenJobID = '$' + '(ESCAPE_SQUOTE(JOBID))' + SET @TokenStepID = '$' + '(ESCAPE_SQUOTE(STEPID))' + SET @TokenDate = '$' + '(ESCAPE_SQUOTE(DATE))' + SET @TokenTime = '$' + '(ESCAPE_SQUOTE(TIME))' IF @Version >= 13 BEGIN diff --git a/Queue.sql b/Queue.sql index 3d8f6f38..e8374df6 100644 --- a/Queue.sql +++ b/Queue.sql @@ -9,7 +9,7 @@ CREATE TABLE [dbo].[Queue]( [SchemaName] [sysname] NOT NULL, [ObjectName] [sysname] NOT NULL, [Parameters] [nvarchar](max) NOT NULL, - [QueueStartTime] [datetime] NULL, + [QueueStartTime] [datetime2](7) NULL, [SessionID] [smallint] NULL, [RequestID] [int] NULL, [RequestStartTime] [datetime] NULL, diff --git a/QueueDatabase.sql b/QueueDatabase.sql index 53d1170b..a80d1877 100644 --- a/QueueDatabase.sql +++ b/QueueDatabase.sql @@ -8,8 +8,8 @@ CREATE TABLE [dbo].[QueueDatabase]( [QueueID] [int] NOT NULL, [DatabaseName] [sysname] NOT NULL, [DatabaseOrder] [int] NULL, - [DatabaseStartTime] [datetime] NULL, - [DatabaseEndTime] [datetime] NULL, + [DatabaseStartTime] [datetime2](7) NULL, + [DatabaseEndTime] [datetime2](7) NULL, [SessionID] [smallint] NULL, [RequestID] [int] NULL, [RequestStartTime] [datetime] NULL, From fe763590d1cfb7340988cb0dc939fc0a8b6bf5b3 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 5 Jan 2020 15:30:51 +0100 Subject: [PATCH 141/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 74829d81..a2627564 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ You can also download the objects as separate scripts: Note that you always need CommandExecute; DatabaseBackup, DatabaseIntegrityCheck, and IndexOptimize are using it. You need CommandLog if you are going to use the option to log commands to a table. -Supported versions: SQL Server 2005, SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, SQL Server 2019, Azure SQL Database, and Azure SQL Database Managed Instance +Supported versions: SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, SQL Server 2019, Azure SQL Database, and Azure SQL Database Managed Instance ## Documentation From 455a7800fe8639cca98e79c254d6943ec789449d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 6 Jan 2020 16:41:21 +0100 Subject: [PATCH 142/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 27 +++++++++++---------------- 5 files changed, 15 insertions(+), 20 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index af7b60d7..363b1329 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-05 15:00:38 //-- + --// Version: 2020-01-06 16:38:06 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 534d6583..7b472445 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -75,7 +75,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-05 15:00:38 //-- + --// Version: 2020-01-06 16:38:06 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 133ec756..0eef9cc5 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-05 15:00:38 //-- + --// Version: 2020-01-06 16:38:06 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 55735ef5..643e74b7 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-05 15:00:38 //-- + --// Version: 2020-01-06 16:38:06 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 32c5987b..33f1e257 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-05 15:00:38 +Version: 2020-01-06 16:38:06 You can contact me by e-mail at ola@hallengren.com. @@ -23,18 +23,13 @@ USE [master] -- Specify the database in which the objects will be created. SET NOCOUNT ON -DECLARE @CreateJobs nvarchar(max) -DECLARE @BackupDirectory nvarchar(max) -DECLARE @CleanupTime int -DECLARE @OutputFileDirectory nvarchar(max) -DECLARE @LogToTable nvarchar(max) -DECLARE @ErrorMessage nvarchar(max) +DECLARE @CreateJobs nvarchar(max) = 'Y' -- Specify whether jobs should be created. +DECLARE @BackupDirectory nvarchar(max) = NULL -- Specify the backup root directory. If no directory is specified, the default backup directory is used. +DECLARE @CleanupTime int = NULL -- Time in hours, after which backup files are deleted. If no time is specified, then no backup files are deleted. +DECLARE @OutputFileDirectory nvarchar(max) = NULL -- Specify the output file directory. If no directory is specified, then the SQL Server error log directory is used. +DECLARE @LogToTable nvarchar(max) = 'Y' -- Log commands to a table. -SET @CreateJobs = 'Y' -- Specify whether jobs should be created. -SET @BackupDirectory = NULL -- Specify the backup root directory. If no directory is specified, the default backup directory is used. -SET @CleanupTime = NULL -- Time in hours, after which backup files are deleted. If no time is specified, then no backup files are deleted. -SET @OutputFileDirectory = NULL -- Specify the output file directory. If no directory is specified, then the SQL Server error log directory is used. -SET @LogToTable = 'Y' -- Log commands to a table. +DECLARE @ErrorMessage nvarchar(max) IF IS_SRVROLEMEMBER('sysadmin') = 0 AND NOT (DB_ID('rdsadmin') IS NOT NULL AND SUSER_SNAME(0x01) = 'rdsa') BEGIN @@ -127,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-05 15:00:38 //-- + --// Version: 2020-01-06 16:38:06 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -430,7 +425,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-05 15:00:38 //-- + --// Version: 2020-01-06 16:38:06 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3590,7 +3585,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-05 15:00:38 //-- + --// Version: 2020-01-06 16:38:06 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5327,7 +5322,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-05 15:00:38 //-- + --// Version: 2020-01-06 16:38:06 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From ab81421a8e7b8a0d6617bea89e5e4fe6c70f16bd Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 6 Jan 2020 19:50:46 +0100 Subject: [PATCH 143/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 8 ++++---- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 16 ++++++++-------- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 363b1329..42e92aa2 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 16:38:06 //-- + --// Version: 2020-01-06 19:43:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 7b472445..be80eb97 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -75,7 +75,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 16:38:06 //-- + --// Version: 2020-01-06 19:43:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 0eef9cc5..9ea17ccc 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -37,7 +37,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 16:38:06 //-- + --// Version: 2020-01-06 19:43:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1304,7 +1304,7 @@ BEGIN IF @TabLock = 'Y' SET @CurrentCommand01 += ', TABLOCK' IF @MaxDOP IS NOT NULL SET @CurrentCommand01 += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) - EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput01 = @Error IF @CurrentCommandOutput01 <> 0 SET @ReturnCode = @CurrentCommandOutput01 @@ -1463,7 +1463,7 @@ BEGIN SET @CurrentCommand05 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' IF @TabLock = 'Y' SET @CurrentCommand05 += ', TABLOCK' - EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput05 = @Error IF @CurrentCommandOutput05 <> 0 SET @ReturnCode = @CurrentCommandOutput05 @@ -1630,7 +1630,7 @@ BEGIN SET @CurrentCommand09 += 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) SET @CurrentCommand09 += ') WITH NO_INFOMSGS' - EXECUTE @CurrentCommandOutput09 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand09, @CommandType = @CurrentCommandType09, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput09 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand09, @CommandType = @CurrentCommandType09, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput09 = @Error IF @CurrentCommandOutput09 <> 0 SET @ReturnCode = @CurrentCommandOutput09 diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 643e74b7..83548301 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -51,7 +51,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 16:38:06 //-- + --// Version: 2020-01-06 19:43:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 33f1e257..e4e8e131 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-06 16:38:06 +Version: 2020-01-06 19:43:36 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 16:38:06 //-- + --// Version: 2020-01-06 19:43:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -425,7 +425,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 16:38:06 //-- + --// Version: 2020-01-06 19:43:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3585,7 +3585,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 16:38:06 //-- + --// Version: 2020-01-06 19:43:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4852,7 +4852,7 @@ BEGIN IF @TabLock = 'Y' SET @CurrentCommand01 += ', TABLOCK' IF @MaxDOP IS NOT NULL SET @CurrentCommand01 += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) - EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput01 = @Error IF @CurrentCommandOutput01 <> 0 SET @ReturnCode = @CurrentCommandOutput01 @@ -5011,7 +5011,7 @@ BEGIN SET @CurrentCommand05 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' IF @TabLock = 'Y' SET @CurrentCommand05 += ', TABLOCK' - EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput05 = @Error IF @CurrentCommandOutput05 <> 0 SET @ReturnCode = @CurrentCommandOutput05 @@ -5178,7 +5178,7 @@ BEGIN SET @CurrentCommand09 += 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) SET @CurrentCommand09 += ') WITH NO_INFOMSGS' - EXECUTE @CurrentCommandOutput09 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand09, @CommandType = @CurrentCommandType09, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput09 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand09, @CommandType = @CurrentCommandType09, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput09 = @Error IF @CurrentCommandOutput09 <> 0 SET @ReturnCode = @CurrentCommandOutput09 @@ -5322,7 +5322,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 16:38:06 //-- + --// Version: 2020-01-06 19:43:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From bec09a7258cf1b97acd8da4f612ca9ac1f0871b0 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 8 Jan 2020 21:00:08 +0100 Subject: [PATCH 144/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 78 +++++++------ DatabaseIntegrityCheck.sql | 68 ++++++----- IndexOptimize.sql | 76 +++++++------ MaintenanceSolution.sql | 226 ++++++++++++++++++++----------------- 5 files changed, 249 insertions(+), 201 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 42e92aa2..3d31b6bc 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 19:43:36 //-- + --// Version: 2020-01-08 20:52:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index be80eb97..34881cf1 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -62,6 +62,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @Init nvarchar(max) = 'N', @Format nvarchar(max) = 'N', @ObjectLevelRecoveryMap nvarchar(max) = 'N', +@StringDelimiter nvarchar(max) = ',', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -75,7 +76,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 19:43:36 //-- + --// Version: 2020-01-08 20:52:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -326,6 +327,7 @@ BEGIN SET @Parameters += ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') SET @Parameters += ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') SET @Parameters += ', @ObjectLevelRecoveryMap = ' + ISNULL('''' + REPLACE(@ObjectLevelRecoveryMap,'''','''''') + '''','NULL') + SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -431,21 +433,21 @@ BEGIN SET @Databases = REPLACE(@Databases, CHAR(10), '') SET @Databases = REPLACE(@Databases, CHAR(13), '') - WHILE CHARINDEX(', ',@Databases) > 0 SET @Databases = REPLACE(@Databases,', ',',') - WHILE CHARINDEX(' ,',@Databases) > 0 SET @Databases = REPLACE(@Databases,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @Databases) > 0 SET @Databases = REPLACE(@Databases, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @Databases) > 0 SET @Databases = REPLACE(@Databases, ' ' + @StringDelimiter, @StringDelimiter) SET @Databases = LTRIM(RTRIM(@Databases)); WITH Databases1 (StartPosition, EndPosition, DatabaseItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Databases, 1), 0), LEN(@Databases) + 1) AS EndPosition, - SUBSTRING(@Databases, 1, ISNULL(NULLIF(CHARINDEX(',', @Databases, 1), 0), LEN(@Databases) + 1) - 1) AS DatabaseItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, 1), 0), LEN(@Databases) + 1) AS EndPosition, + SUBSTRING(@Databases, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, 1), 0), LEN(@Databases) + 1) - 1) AS DatabaseItem WHERE @Databases IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) AS EndPosition, - SUBSTRING(@Databases, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) - EndPosition - 1) AS DatabaseItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) AS EndPosition, + SUBSTRING(@Databases, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) - EndPosition - 1) AS DatabaseItem FROM Databases1 WHERE EndPosition < LEN(@Databases) + 1 ), @@ -562,21 +564,21 @@ BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(13), '') - WHILE CHARINDEX(', ',@AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups,', ',',') - WHILE CHARINDEX(' ,',@AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, ' ' + @StringDelimiter, @StringDelimiter) SET @AvailabilityGroups = LTRIM(RTRIM(@AvailabilityGroups)); WITH AvailabilityGroups1 (StartPosition, EndPosition, AvailabilityGroupItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, - SUBSTRING(@AvailabilityGroups, 1, ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) - 1) AS AvailabilityGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, + SUBSTRING(@AvailabilityGroups, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) - 1) AS AvailabilityGroupItem WHERE @AvailabilityGroups IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, - SUBSTRING(@AvailabilityGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) - EndPosition - 1) AS AvailabilityGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, + SUBSTRING(@AvailabilityGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) - EndPosition - 1) AS AvailabilityGroupItem FROM AvailabilityGroups1 WHERE EndPosition < LEN(@AvailabilityGroups) + 1 ), @@ -717,21 +719,21 @@ BEGIN SET @Directory = REPLACE(@Directory, CHAR(10), '') SET @Directory = REPLACE(@Directory, CHAR(13), '') - WHILE CHARINDEX(', ',@Directory) > 0 SET @Directory = REPLACE(@Directory,', ',',') - WHILE CHARINDEX(' ,',@Directory) > 0 SET @Directory = REPLACE(@Directory,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @Directory) > 0 SET @Directory = REPLACE(@Directory, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @Directory) > 0 SET @Directory = REPLACE(@Directory, ' ' + @StringDelimiter, @StringDelimiter) SET @Directory = LTRIM(RTRIM(@Directory)); WITH Directories (StartPosition, EndPosition, Directory) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Directory, 1), 0), LEN(@Directory) + 1) AS EndPosition, - SUBSTRING(@Directory, 1, ISNULL(NULLIF(CHARINDEX(',', @Directory, 1), 0), LEN(@Directory) + 1) - 1) AS Directory + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, 1), 0), LEN(@Directory) + 1) AS EndPosition, + SUBSTRING(@Directory, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, 1), 0), LEN(@Directory) + 1) - 1) AS Directory WHERE @Directory IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) AS EndPosition, - SUBSTRING(@Directory, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) - EndPosition - 1) AS Directory + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) AS EndPosition, + SUBSTRING(@Directory, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) - EndPosition - 1) AS Directory FROM Directories WHERE EndPosition < LEN(@Directory) + 1 ) @@ -755,13 +757,13 @@ BEGIN WITH Directories (StartPosition, EndPosition, Directory) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @MirrorDirectory, 1), 0), LEN(@MirrorDirectory) + 1) AS EndPosition, - SUBSTRING(@MirrorDirectory, 1, ISNULL(NULLIF(CHARINDEX(',', @MirrorDirectory, 1), 0), LEN(@MirrorDirectory) + 1) - 1) AS Directory + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorDirectory, 1), 0), LEN(@MirrorDirectory) + 1) AS EndPosition, + SUBSTRING(@MirrorDirectory, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorDirectory, 1), 0), LEN(@MirrorDirectory) + 1) - 1) AS Directory WHERE @MirrorDirectory IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @MirrorDirectory, EndPosition + 1), 0), LEN(@MirrorDirectory) + 1) AS EndPosition, - SUBSTRING(@MirrorDirectory, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @MirrorDirectory, EndPosition + 1), 0), LEN(@MirrorDirectory) + 1) - EndPosition - 1) AS Directory + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorDirectory, EndPosition + 1), 0), LEN(@MirrorDirectory) + 1) AS EndPosition, + SUBSTRING(@MirrorDirectory, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorDirectory, EndPosition + 1), 0), LEN(@MirrorDirectory) + 1) - EndPosition - 1) AS Directory FROM Directories WHERE EndPosition < LEN(@MirrorDirectory) + 1 ) @@ -856,21 +858,21 @@ BEGIN SET @URL = REPLACE(@URL, CHAR(10), '') SET @URL = REPLACE(@URL, CHAR(13), '') - WHILE CHARINDEX(', ',@URL) > 0 SET @URL = REPLACE(@URL,', ',',') - WHILE CHARINDEX(' ,',@URL) > 0 SET @URL = REPLACE(@URL,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @URL) > 0 SET @URL = REPLACE(@URL, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @URL) > 0 SET @URL = REPLACE(@URL, ' ' + @StringDelimiter, @StringDelimiter) SET @URL = LTRIM(RTRIM(@URL)); WITH URLs (StartPosition, EndPosition, [URL]) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @URL, 1), 0), LEN(@URL) + 1) AS EndPosition, - SUBSTRING(@URL, 1, ISNULL(NULLIF(CHARINDEX(',', @URL, 1), 0), LEN(@URL) + 1) - 1) AS [URL] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @URL, 1), 0), LEN(@URL) + 1) AS EndPosition, + SUBSTRING(@URL, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @URL, 1), 0), LEN(@URL) + 1) - 1) AS [URL] WHERE @URL IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @URL, EndPosition + 1), 0), LEN(@URL) + 1) AS EndPosition, - SUBSTRING(@URL, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @URL, EndPosition + 1), 0), LEN(@URL) + 1) - EndPosition - 1) AS [URL] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @URL, EndPosition + 1), 0), LEN(@URL) + 1) AS EndPosition, + SUBSTRING(@URL, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @URL, EndPosition + 1), 0), LEN(@URL) + 1) - EndPosition - 1) AS [URL] FROM URLs WHERE EndPosition < LEN(@URL) + 1 ) @@ -884,21 +886,21 @@ BEGIN SET @MirrorURL = REPLACE(@MirrorURL, CHAR(10), '') SET @MirrorURL = REPLACE(@MirrorURL, CHAR(13), '') - WHILE CHARINDEX(', ',@MirrorURL) > 0 SET @MirrorURL = REPLACE(@MirrorURL,', ',',') - WHILE CHARINDEX(' ,',@MirrorURL) > 0 SET @MirrorURL = REPLACE(@MirrorURL,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @MirrorURL) > 0 SET @MirrorURL = REPLACE(@MirrorURL, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter ,@MirrorURL) > 0 SET @MirrorURL = REPLACE(@MirrorURL, ' ' + @StringDelimiter, @StringDelimiter) SET @MirrorURL = LTRIM(RTRIM(@MirrorURL)); WITH URLs (StartPosition, EndPosition, [URL]) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, 1), 0), LEN(@MirrorURL) + 1) AS EndPosition, - SUBSTRING(@MirrorURL, 1, ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, 1), 0), LEN(@MirrorURL) + 1) - 1) AS [URL] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorURL, 1), 0), LEN(@MirrorURL) + 1) AS EndPosition, + SUBSTRING(@MirrorURL, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorURL, 1), 0), LEN(@MirrorURL) + 1) - 1) AS [URL] WHERE @MirrorURL IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, EndPosition + 1), 0), LEN(@MirrorURL) + 1) AS EndPosition, - SUBSTRING(@MirrorURL, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, EndPosition + 1), 0), LEN(@MirrorURL) + 1) - EndPosition - 1) AS [URL] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorURL, EndPosition + 1), 0), LEN(@MirrorURL) + 1) AS EndPosition, + SUBSTRING(@MirrorURL, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorURL, EndPosition + 1), 0), LEN(@MirrorURL) + 1) - EndPosition - 1) AS [URL] FROM URLs WHERE EndPosition < LEN(@MirrorURL) + 1 ) @@ -1406,6 +1408,12 @@ BEGIN SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.' END + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @StringDelimiter is not supported.' + END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message]) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 9ea17ccc..0cb91474 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -24,6 +24,7 @@ ALTER PROCEDURE [dbo].[DatabaseIntegrityCheck] @TimeLimit int = NULL, @LockTimeout int = NULL, @LockMessageSeverity int = 16, +@StringDelimiter nvarchar(max) = ',', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -37,7 +38,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 19:43:36 //-- + --// Version: 2020-01-08 20:52:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -221,6 +222,7 @@ BEGIN SET @Parameters += ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') SET @Parameters += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') + SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -320,21 +322,21 @@ BEGIN SET @Databases = REPLACE(@Databases, CHAR(10), '') SET @Databases = REPLACE(@Databases, CHAR(13), '') - WHILE CHARINDEX(', ',@Databases) > 0 SET @Databases = REPLACE(@Databases,', ',',') - WHILE CHARINDEX(' ,',@Databases) > 0 SET @Databases = REPLACE(@Databases,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @Databases) > 0 SET @Databases = REPLACE(@Databases, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @Databases) > 0 SET @Databases = REPLACE(@Databases, ' ' + @StringDelimiter, @StringDelimiter) SET @Databases = LTRIM(RTRIM(@Databases)); WITH Databases1 (StartPosition, EndPosition, DatabaseItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Databases, 1), 0), LEN(@Databases) + 1) AS EndPosition, - SUBSTRING(@Databases, 1, ISNULL(NULLIF(CHARINDEX(',', @Databases, 1), 0), LEN(@Databases) + 1) - 1) AS DatabaseItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, 1), 0), LEN(@Databases) + 1) AS EndPosition, + SUBSTRING(@Databases, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, 1), 0), LEN(@Databases) + 1) - 1) AS DatabaseItem WHERE @Databases IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) AS EndPosition, - SUBSTRING(@Databases, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) - EndPosition - 1) AS DatabaseItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) AS EndPosition, + SUBSTRING(@Databases, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) - EndPosition - 1) AS DatabaseItem FROM Databases1 WHERE EndPosition < LEN(@Databases) + 1 ), @@ -451,21 +453,21 @@ BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(13), '') - WHILE CHARINDEX(', ',@AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups,', ',',') - WHILE CHARINDEX(' ,',@AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, ' ' + @StringDelimiter, @StringDelimiter) SET @AvailabilityGroups = LTRIM(RTRIM(@AvailabilityGroups)); WITH AvailabilityGroups1 (StartPosition, EndPosition, AvailabilityGroupItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, - SUBSTRING(@AvailabilityGroups, 1, ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) - 1) AS AvailabilityGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, + SUBSTRING(@AvailabilityGroups, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) - 1) AS AvailabilityGroupItem WHERE @AvailabilityGroups IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, - SUBSTRING(@AvailabilityGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) - EndPosition - 1) AS AvailabilityGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, + SUBSTRING(@AvailabilityGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) - EndPosition - 1) AS AvailabilityGroupItem FROM AvailabilityGroups1 WHERE EndPosition < LEN(@AvailabilityGroups) + 1 ), @@ -555,21 +557,21 @@ BEGIN SET @FileGroups = REPLACE(@FileGroups, CHAR(10), '') SET @FileGroups = REPLACE(@FileGroups, CHAR(13), '') - WHILE CHARINDEX(', ',@FileGroups) > 0 SET @FileGroups = REPLACE(@FileGroups,', ',',') - WHILE CHARINDEX(' ,',@FileGroups) > 0 SET @FileGroups = REPLACE(@FileGroups,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @FileGroups) > 0 SET @FileGroups = REPLACE(@FileGroups, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @FileGroups) > 0 SET @FileGroups = REPLACE(@FileGroups, ' ' + @StringDelimiter, @StringDelimiter) SET @FileGroups = LTRIM(RTRIM(@FileGroups)); WITH FileGroups1 (StartPosition, EndPosition, FileGroupItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FileGroups, 1), 0), LEN(@FileGroups) + 1) AS EndPosition, - SUBSTRING(@FileGroups, 1, ISNULL(NULLIF(CHARINDEX(',', @FileGroups, 1), 0), LEN(@FileGroups) + 1) - 1) AS FileGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FileGroups, 1), 0), LEN(@FileGroups) + 1) AS EndPosition, + SUBSTRING(@FileGroups, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FileGroups, 1), 0), LEN(@FileGroups) + 1) - 1) AS FileGroupItem WHERE @FileGroups IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FileGroups, EndPosition + 1), 0), LEN(@FileGroups) + 1) AS EndPosition, - SUBSTRING(@FileGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @FileGroups, EndPosition + 1), 0), LEN(@FileGroups) + 1) - EndPosition - 1) AS FileGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FileGroups, EndPosition + 1), 0), LEN(@FileGroups) + 1) AS EndPosition, + SUBSTRING(@FileGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FileGroups, EndPosition + 1), 0), LEN(@FileGroups) + 1) - EndPosition - 1) AS FileGroupItem FROM FileGroups1 WHERE EndPosition < LEN(@FileGroups) + 1 ), @@ -607,21 +609,21 @@ BEGIN SET @Objects = REPLACE(@Objects, CHAR(10), '') SET @Objects = REPLACE(@Objects, CHAR(13), '') - WHILE CHARINDEX(', ',@Objects) > 0 SET @Objects = REPLACE(@Objects,', ',',') - WHILE CHARINDEX(' ,',@Objects) > 0 SET @Objects = REPLACE(@Objects,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @Objects) > 0 SET @Objects = REPLACE(@Objects, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @Objects) > 0 SET @Objects = REPLACE(@Objects, ' ' + @StringDelimiter, @StringDelimiter) SET @Objects = LTRIM(RTRIM(@Objects)); WITH Objects1 (StartPosition, EndPosition, ObjectItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Objects, 1), 0), LEN(@Objects) + 1) AS EndPosition, - SUBSTRING(@Objects, 1, ISNULL(NULLIF(CHARINDEX(',', @Objects, 1), 0), LEN(@Objects) + 1) - 1) AS ObjectItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Objects, 1), 0), LEN(@Objects) + 1) AS EndPosition, + SUBSTRING(@Objects, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Objects, 1), 0), LEN(@Objects) + 1) - 1) AS ObjectItem WHERE @Objects IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Objects, EndPosition + 1), 0), LEN(@Objects) + 1) AS EndPosition, - SUBSTRING(@Objects, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @Objects, EndPosition + 1), 0), LEN(@Objects) + 1) - EndPosition - 1) AS ObjectItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Objects, EndPosition + 1), 0), LEN(@Objects) + 1) AS EndPosition, + SUBSTRING(@Objects, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Objects, EndPosition + 1), 0), LEN(@Objects) + 1) - EndPosition - 1) AS ObjectItem FROM Objects1 WHERE EndPosition < LEN(@Objects) + 1 ), @@ -657,18 +659,18 @@ BEGIN --// Select check commands //-- ---------------------------------------------------------------------------------------------------- - SET @CheckCommands = REPLACE(@CheckCommands,', ',','); + SET @CheckCommands = REPLACE(@CheckCommands, @StringDelimiter + ' ', @StringDelimiter); WITH CheckCommands (StartPosition, EndPosition, CheckCommand) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @CheckCommands, 1), 0), LEN(@CheckCommands) + 1) AS EndPosition, - SUBSTRING(@CheckCommands, 1, ISNULL(NULLIF(CHARINDEX(',', @CheckCommands, 1), 0), LEN(@CheckCommands) + 1) - 1) AS CheckCommand + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @CheckCommands, 1), 0), LEN(@CheckCommands) + 1) AS EndPosition, + SUBSTRING(@CheckCommands, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @CheckCommands, 1), 0), LEN(@CheckCommands) + 1) - 1) AS CheckCommand WHERE @CheckCommands IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @CheckCommands, EndPosition + 1), 0), LEN(@CheckCommands) + 1) AS EndPosition, - SUBSTRING(@CheckCommands, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @CheckCommands, EndPosition + 1), 0), LEN(@CheckCommands) + 1) - EndPosition - 1) AS CheckCommand + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @CheckCommands, EndPosition + 1), 0), LEN(@CheckCommands) + 1) AS EndPosition, + SUBSTRING(@CheckCommands, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @CheckCommands, EndPosition + 1), 0), LEN(@CheckCommands) + 1) - EndPosition - 1) AS CheckCommand FROM CheckCommands WHERE EndPosition < LEN(@CheckCommands) + 1 ) @@ -759,6 +761,12 @@ BEGIN SELECT 'The value for the parameter @LockMessageSeverity is not supported.' END + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @StringDelimiter is not supported.' + END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message]) diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 83548301..69179fdb 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -38,6 +38,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @AvailabilityGroups nvarchar(max) = NULL, @LockTimeout int = NULL, @LockMessageSeverity int = 16, +@StringDelimiter nvarchar(max) = ',', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -51,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 19:43:36 //-- + --// Version: 2020-01-08 20:52:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -310,6 +311,7 @@ BEGIN SET @Parameters += ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') + SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -409,21 +411,21 @@ BEGIN SET @Databases = REPLACE(@Databases, CHAR(10), '') SET @Databases = REPLACE(@Databases, CHAR(13), '') - WHILE CHARINDEX(', ',@Databases) > 0 SET @Databases = REPLACE(@Databases,', ',',') - WHILE CHARINDEX(' ,',@Databases) > 0 SET @Databases = REPLACE(@Databases,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @Databases) > 0 SET @Databases = REPLACE(@Databases, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @Databases) > 0 SET @Databases = REPLACE(@Databases, ' ' + @StringDelimiter, @StringDelimiter) SET @Databases = LTRIM(RTRIM(@Databases)); WITH Databases1 (StartPosition, EndPosition, DatabaseItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Databases, 1), 0), LEN(@Databases) + 1) AS EndPosition, - SUBSTRING(@Databases, 1, ISNULL(NULLIF(CHARINDEX(',', @Databases, 1), 0), LEN(@Databases) + 1) - 1) AS DatabaseItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, 1), 0), LEN(@Databases) + 1) AS EndPosition, + SUBSTRING(@Databases, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, 1), 0), LEN(@Databases) + 1) - 1) AS DatabaseItem WHERE @Databases IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) AS EndPosition, - SUBSTRING(@Databases, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) - EndPosition - 1) AS DatabaseItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) AS EndPosition, + SUBSTRING(@Databases, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) - EndPosition - 1) AS DatabaseItem FROM Databases1 WHERE EndPosition < LEN(@Databases) + 1 ), @@ -539,21 +541,21 @@ BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(13), '') - WHILE CHARINDEX(', ',@AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups,', ',',') - WHILE CHARINDEX(' ,',@AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, ' ' + @StringDelimiter, @StringDelimiter) SET @AvailabilityGroups = LTRIM(RTRIM(@AvailabilityGroups)); WITH AvailabilityGroups1 (StartPosition, EndPosition, AvailabilityGroupItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, - SUBSTRING(@AvailabilityGroups, 1, ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) - 1) AS AvailabilityGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, + SUBSTRING(@AvailabilityGroups, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) - 1) AS AvailabilityGroupItem WHERE @AvailabilityGroups IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, - SUBSTRING(@AvailabilityGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) - EndPosition - 1) AS AvailabilityGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, + SUBSTRING(@AvailabilityGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) - EndPosition - 1) AS AvailabilityGroupItem FROM AvailabilityGroups1 WHERE EndPosition < LEN(@AvailabilityGroups) + 1 ), @@ -643,21 +645,21 @@ BEGIN SET @Indexes = REPLACE(@Indexes, CHAR(10), '') SET @Indexes = REPLACE(@Indexes, CHAR(13), '') - WHILE CHARINDEX(', ',@Indexes) > 0 SET @Indexes = REPLACE(@Indexes,', ',',') - WHILE CHARINDEX(' ,',@Indexes) > 0 SET @Indexes = REPLACE(@Indexes,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @Indexes) > 0 SET @Indexes = REPLACE(@Indexes, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @Indexes) > 0 SET @Indexes = REPLACE(@Indexes, ' ' + @StringDelimiter, @StringDelimiter) SET @Indexes = LTRIM(RTRIM(@Indexes)); WITH Indexes1 (StartPosition, EndPosition, IndexItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Indexes, 1), 0), LEN(@Indexes) + 1) AS EndPosition, - SUBSTRING(@Indexes, 1, ISNULL(NULLIF(CHARINDEX(',', @Indexes, 1), 0), LEN(@Indexes) + 1) - 1) AS IndexItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Indexes, 1), 0), LEN(@Indexes) + 1) AS EndPosition, + SUBSTRING(@Indexes, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Indexes, 1), 0), LEN(@Indexes) + 1) - 1) AS IndexItem WHERE @Indexes IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Indexes, EndPosition + 1), 0), LEN(@Indexes) + 1) AS EndPosition, - SUBSTRING(@Indexes, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @Indexes, EndPosition + 1), 0), LEN(@Indexes) + 1) - EndPosition - 1) AS IndexItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Indexes, EndPosition + 1), 0), LEN(@Indexes) + 1) AS EndPosition, + SUBSTRING(@Indexes, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Indexes, EndPosition + 1), 0), LEN(@Indexes) + 1) - EndPosition - 1) AS IndexItem FROM Indexes1 WHERE EndPosition < LEN(@Indexes) + 1 ), @@ -694,18 +696,18 @@ BEGIN --// Select actions //-- ---------------------------------------------------------------------------------------------------- - SET @FragmentationLow = REPLACE(@FragmentationLow,', ',','); + SET @FragmentationLow = REPLACE(@FragmentationLow, @StringDelimiter + ' ', @StringDelimiter); WITH FragmentationLow (StartPosition, EndPosition, [Action]) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FragmentationLow, 1), 0), LEN(@FragmentationLow) + 1) AS EndPosition, - SUBSTRING(@FragmentationLow, 1, ISNULL(NULLIF(CHARINDEX(',', @FragmentationLow, 1), 0), LEN(@FragmentationLow) + 1) - 1) AS [Action] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationLow, 1), 0), LEN(@FragmentationLow) + 1) AS EndPosition, + SUBSTRING(@FragmentationLow, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationLow, 1), 0), LEN(@FragmentationLow) + 1) - 1) AS [Action] WHERE @FragmentationLow IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FragmentationLow, EndPosition + 1), 0), LEN(@FragmentationLow) + 1) AS EndPosition, - SUBSTRING(@FragmentationLow, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @FragmentationLow, EndPosition + 1), 0), LEN(@FragmentationLow) + 1) - EndPosition - 1) AS [Action] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationLow, EndPosition + 1), 0), LEN(@FragmentationLow) + 1) AS EndPosition, + SUBSTRING(@FragmentationLow, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationLow, EndPosition + 1), 0), LEN(@FragmentationLow) + 1) - EndPosition - 1) AS [Action] FROM FragmentationLow WHERE EndPosition < LEN(@FragmentationLow) + 1 ) @@ -716,18 +718,18 @@ BEGIN FROM FragmentationLow OPTION (MAXRECURSION 0) - SET @FragmentationMedium = REPLACE(@FragmentationMedium,', ',','); + SET @FragmentationMedium = REPLACE(@FragmentationMedium, @StringDelimiter + ' ', @StringDelimiter); WITH FragmentationMedium (StartPosition, EndPosition, [Action]) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FragmentationMedium, 1), 0), LEN(@FragmentationMedium) + 1) AS EndPosition, - SUBSTRING(@FragmentationMedium, 1, ISNULL(NULLIF(CHARINDEX(',', @FragmentationMedium, 1), 0), LEN(@FragmentationMedium) + 1) - 1) AS [Action] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationMedium, 1), 0), LEN(@FragmentationMedium) + 1) AS EndPosition, + SUBSTRING(@FragmentationMedium, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationMedium, 1), 0), LEN(@FragmentationMedium) + 1) - 1) AS [Action] WHERE @FragmentationMedium IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FragmentationMedium, EndPosition + 1), 0), LEN(@FragmentationMedium) + 1) AS EndPosition, - SUBSTRING(@FragmentationMedium, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @FragmentationMedium, EndPosition + 1), 0), LEN(@FragmentationMedium) + 1) - EndPosition - 1) AS [Action] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationMedium, EndPosition + 1), 0), LEN(@FragmentationMedium) + 1) AS EndPosition, + SUBSTRING(@FragmentationMedium, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationMedium, EndPosition + 1), 0), LEN(@FragmentationMedium) + 1) - EndPosition - 1) AS [Action] FROM FragmentationMedium WHERE EndPosition < LEN(@FragmentationMedium) + 1 ) @@ -738,18 +740,18 @@ BEGIN FROM FragmentationMedium OPTION (MAXRECURSION 0) - SET @FragmentationHigh = REPLACE(@FragmentationHigh,', ',','); + SET @FragmentationHigh = REPLACE(@FragmentationHigh, @StringDelimiter + ' ', @StringDelimiter); WITH FragmentationHigh (StartPosition, EndPosition, [Action]) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FragmentationHigh, 1), 0), LEN(@FragmentationHigh) + 1) AS EndPosition, - SUBSTRING(@FragmentationHigh, 1, ISNULL(NULLIF(CHARINDEX(',', @FragmentationHigh, 1), 0), LEN(@FragmentationHigh) + 1) - 1) AS [Action] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationHigh, 1), 0), LEN(@FragmentationHigh) + 1) AS EndPosition, + SUBSTRING(@FragmentationHigh, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationHigh, 1), 0), LEN(@FragmentationHigh) + 1) - 1) AS [Action] WHERE @FragmentationHigh IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FragmentationHigh, EndPosition + 1), 0), LEN(@FragmentationHigh) + 1) AS EndPosition, - SUBSTRING(@FragmentationHigh, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @FragmentationHigh, EndPosition + 1), 0), LEN(@FragmentationHigh) + 1) - EndPosition - 1) AS [Action] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationHigh, EndPosition + 1), 0), LEN(@FragmentationHigh) + 1) AS EndPosition, + SUBSTRING(@FragmentationHigh, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationHigh, EndPosition + 1), 0), LEN(@FragmentationHigh) + 1) - EndPosition - 1) AS [Action] FROM FragmentationHigh WHERE EndPosition < LEN(@FragmentationHigh) + 1 ) @@ -941,6 +943,12 @@ BEGIN SELECT 'The value for the parameter @LockMessageSeverity is not supported.' END + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @StringDelimiter is not supported.' + END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message]) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index e4e8e131..a5c8fea6 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-06 19:43:36 +Version: 2020-01-08 20:52:41 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 19:43:36 //-- + --// Version: 2020-01-08 20:52:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -412,6 +412,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @Init nvarchar(max) = 'N', @Format nvarchar(max) = 'N', @ObjectLevelRecoveryMap nvarchar(max) = 'N', +@StringDelimiter nvarchar(max) = ',', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -425,7 +426,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 19:43:36 //-- + --// Version: 2020-01-08 20:52:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -676,6 +677,7 @@ BEGIN SET @Parameters += ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') SET @Parameters += ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') SET @Parameters += ', @ObjectLevelRecoveryMap = ' + ISNULL('''' + REPLACE(@ObjectLevelRecoveryMap,'''','''''') + '''','NULL') + SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -781,21 +783,21 @@ BEGIN SET @Databases = REPLACE(@Databases, CHAR(10), '') SET @Databases = REPLACE(@Databases, CHAR(13), '') - WHILE CHARINDEX(', ',@Databases) > 0 SET @Databases = REPLACE(@Databases,', ',',') - WHILE CHARINDEX(' ,',@Databases) > 0 SET @Databases = REPLACE(@Databases,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @Databases) > 0 SET @Databases = REPLACE(@Databases, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @Databases) > 0 SET @Databases = REPLACE(@Databases, ' ' + @StringDelimiter, @StringDelimiter) SET @Databases = LTRIM(RTRIM(@Databases)); WITH Databases1 (StartPosition, EndPosition, DatabaseItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Databases, 1), 0), LEN(@Databases) + 1) AS EndPosition, - SUBSTRING(@Databases, 1, ISNULL(NULLIF(CHARINDEX(',', @Databases, 1), 0), LEN(@Databases) + 1) - 1) AS DatabaseItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, 1), 0), LEN(@Databases) + 1) AS EndPosition, + SUBSTRING(@Databases, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, 1), 0), LEN(@Databases) + 1) - 1) AS DatabaseItem WHERE @Databases IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) AS EndPosition, - SUBSTRING(@Databases, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) - EndPosition - 1) AS DatabaseItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) AS EndPosition, + SUBSTRING(@Databases, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) - EndPosition - 1) AS DatabaseItem FROM Databases1 WHERE EndPosition < LEN(@Databases) + 1 ), @@ -912,21 +914,21 @@ BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(13), '') - WHILE CHARINDEX(', ',@AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups,', ',',') - WHILE CHARINDEX(' ,',@AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, ' ' + @StringDelimiter, @StringDelimiter) SET @AvailabilityGroups = LTRIM(RTRIM(@AvailabilityGroups)); WITH AvailabilityGroups1 (StartPosition, EndPosition, AvailabilityGroupItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, - SUBSTRING(@AvailabilityGroups, 1, ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) - 1) AS AvailabilityGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, + SUBSTRING(@AvailabilityGroups, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) - 1) AS AvailabilityGroupItem WHERE @AvailabilityGroups IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, - SUBSTRING(@AvailabilityGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) - EndPosition - 1) AS AvailabilityGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, + SUBSTRING(@AvailabilityGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) - EndPosition - 1) AS AvailabilityGroupItem FROM AvailabilityGroups1 WHERE EndPosition < LEN(@AvailabilityGroups) + 1 ), @@ -1067,21 +1069,21 @@ BEGIN SET @Directory = REPLACE(@Directory, CHAR(10), '') SET @Directory = REPLACE(@Directory, CHAR(13), '') - WHILE CHARINDEX(', ',@Directory) > 0 SET @Directory = REPLACE(@Directory,', ',',') - WHILE CHARINDEX(' ,',@Directory) > 0 SET @Directory = REPLACE(@Directory,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @Directory) > 0 SET @Directory = REPLACE(@Directory, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @Directory) > 0 SET @Directory = REPLACE(@Directory, ' ' + @StringDelimiter, @StringDelimiter) SET @Directory = LTRIM(RTRIM(@Directory)); WITH Directories (StartPosition, EndPosition, Directory) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Directory, 1), 0), LEN(@Directory) + 1) AS EndPosition, - SUBSTRING(@Directory, 1, ISNULL(NULLIF(CHARINDEX(',', @Directory, 1), 0), LEN(@Directory) + 1) - 1) AS Directory + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, 1), 0), LEN(@Directory) + 1) AS EndPosition, + SUBSTRING(@Directory, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, 1), 0), LEN(@Directory) + 1) - 1) AS Directory WHERE @Directory IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) AS EndPosition, - SUBSTRING(@Directory, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) - EndPosition - 1) AS Directory + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) AS EndPosition, + SUBSTRING(@Directory, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) - EndPosition - 1) AS Directory FROM Directories WHERE EndPosition < LEN(@Directory) + 1 ) @@ -1105,13 +1107,13 @@ BEGIN WITH Directories (StartPosition, EndPosition, Directory) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @MirrorDirectory, 1), 0), LEN(@MirrorDirectory) + 1) AS EndPosition, - SUBSTRING(@MirrorDirectory, 1, ISNULL(NULLIF(CHARINDEX(',', @MirrorDirectory, 1), 0), LEN(@MirrorDirectory) + 1) - 1) AS Directory + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorDirectory, 1), 0), LEN(@MirrorDirectory) + 1) AS EndPosition, + SUBSTRING(@MirrorDirectory, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorDirectory, 1), 0), LEN(@MirrorDirectory) + 1) - 1) AS Directory WHERE @MirrorDirectory IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @MirrorDirectory, EndPosition + 1), 0), LEN(@MirrorDirectory) + 1) AS EndPosition, - SUBSTRING(@MirrorDirectory, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @MirrorDirectory, EndPosition + 1), 0), LEN(@MirrorDirectory) + 1) - EndPosition - 1) AS Directory + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorDirectory, EndPosition + 1), 0), LEN(@MirrorDirectory) + 1) AS EndPosition, + SUBSTRING(@MirrorDirectory, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorDirectory, EndPosition + 1), 0), LEN(@MirrorDirectory) + 1) - EndPosition - 1) AS Directory FROM Directories WHERE EndPosition < LEN(@MirrorDirectory) + 1 ) @@ -1206,21 +1208,21 @@ BEGIN SET @URL = REPLACE(@URL, CHAR(10), '') SET @URL = REPLACE(@URL, CHAR(13), '') - WHILE CHARINDEX(', ',@URL) > 0 SET @URL = REPLACE(@URL,', ',',') - WHILE CHARINDEX(' ,',@URL) > 0 SET @URL = REPLACE(@URL,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @URL) > 0 SET @URL = REPLACE(@URL, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @URL) > 0 SET @URL = REPLACE(@URL, ' ' + @StringDelimiter, @StringDelimiter) SET @URL = LTRIM(RTRIM(@URL)); WITH URLs (StartPosition, EndPosition, [URL]) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @URL, 1), 0), LEN(@URL) + 1) AS EndPosition, - SUBSTRING(@URL, 1, ISNULL(NULLIF(CHARINDEX(',', @URL, 1), 0), LEN(@URL) + 1) - 1) AS [URL] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @URL, 1), 0), LEN(@URL) + 1) AS EndPosition, + SUBSTRING(@URL, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @URL, 1), 0), LEN(@URL) + 1) - 1) AS [URL] WHERE @URL IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @URL, EndPosition + 1), 0), LEN(@URL) + 1) AS EndPosition, - SUBSTRING(@URL, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @URL, EndPosition + 1), 0), LEN(@URL) + 1) - EndPosition - 1) AS [URL] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @URL, EndPosition + 1), 0), LEN(@URL) + 1) AS EndPosition, + SUBSTRING(@URL, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @URL, EndPosition + 1), 0), LEN(@URL) + 1) - EndPosition - 1) AS [URL] FROM URLs WHERE EndPosition < LEN(@URL) + 1 ) @@ -1234,21 +1236,21 @@ BEGIN SET @MirrorURL = REPLACE(@MirrorURL, CHAR(10), '') SET @MirrorURL = REPLACE(@MirrorURL, CHAR(13), '') - WHILE CHARINDEX(', ',@MirrorURL) > 0 SET @MirrorURL = REPLACE(@MirrorURL,', ',',') - WHILE CHARINDEX(' ,',@MirrorURL) > 0 SET @MirrorURL = REPLACE(@MirrorURL,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @MirrorURL) > 0 SET @MirrorURL = REPLACE(@MirrorURL, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter ,@MirrorURL) > 0 SET @MirrorURL = REPLACE(@MirrorURL, ' ' + @StringDelimiter, @StringDelimiter) SET @MirrorURL = LTRIM(RTRIM(@MirrorURL)); WITH URLs (StartPosition, EndPosition, [URL]) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, 1), 0), LEN(@MirrorURL) + 1) AS EndPosition, - SUBSTRING(@MirrorURL, 1, ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, 1), 0), LEN(@MirrorURL) + 1) - 1) AS [URL] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorURL, 1), 0), LEN(@MirrorURL) + 1) AS EndPosition, + SUBSTRING(@MirrorURL, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorURL, 1), 0), LEN(@MirrorURL) + 1) - 1) AS [URL] WHERE @MirrorURL IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, EndPosition + 1), 0), LEN(@MirrorURL) + 1) AS EndPosition, - SUBSTRING(@MirrorURL, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @MirrorURL, EndPosition + 1), 0), LEN(@MirrorURL) + 1) - EndPosition - 1) AS [URL] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorURL, EndPosition + 1), 0), LEN(@MirrorURL) + 1) AS EndPosition, + SUBSTRING(@MirrorURL, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @MirrorURL, EndPosition + 1), 0), LEN(@MirrorURL) + 1) - EndPosition - 1) AS [URL] FROM URLs WHERE EndPosition < LEN(@MirrorURL) + 1 ) @@ -1756,6 +1758,12 @@ BEGIN SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.' END + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @StringDelimiter is not supported.' + END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message]) @@ -3572,6 +3580,7 @@ ALTER PROCEDURE [dbo].[DatabaseIntegrityCheck] @TimeLimit int = NULL, @LockTimeout int = NULL, @LockMessageSeverity int = 16, +@StringDelimiter nvarchar(max) = ',', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -3585,7 +3594,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 19:43:36 //-- + --// Version: 2020-01-08 20:52:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3769,6 +3778,7 @@ BEGIN SET @Parameters += ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar),'NULL') SET @Parameters += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') + SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -3868,21 +3878,21 @@ BEGIN SET @Databases = REPLACE(@Databases, CHAR(10), '') SET @Databases = REPLACE(@Databases, CHAR(13), '') - WHILE CHARINDEX(', ',@Databases) > 0 SET @Databases = REPLACE(@Databases,', ',',') - WHILE CHARINDEX(' ,',@Databases) > 0 SET @Databases = REPLACE(@Databases,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @Databases) > 0 SET @Databases = REPLACE(@Databases, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @Databases) > 0 SET @Databases = REPLACE(@Databases, ' ' + @StringDelimiter, @StringDelimiter) SET @Databases = LTRIM(RTRIM(@Databases)); WITH Databases1 (StartPosition, EndPosition, DatabaseItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Databases, 1), 0), LEN(@Databases) + 1) AS EndPosition, - SUBSTRING(@Databases, 1, ISNULL(NULLIF(CHARINDEX(',', @Databases, 1), 0), LEN(@Databases) + 1) - 1) AS DatabaseItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, 1), 0), LEN(@Databases) + 1) AS EndPosition, + SUBSTRING(@Databases, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, 1), 0), LEN(@Databases) + 1) - 1) AS DatabaseItem WHERE @Databases IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) AS EndPosition, - SUBSTRING(@Databases, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) - EndPosition - 1) AS DatabaseItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) AS EndPosition, + SUBSTRING(@Databases, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) - EndPosition - 1) AS DatabaseItem FROM Databases1 WHERE EndPosition < LEN(@Databases) + 1 ), @@ -3999,21 +4009,21 @@ BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(13), '') - WHILE CHARINDEX(', ',@AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups,', ',',') - WHILE CHARINDEX(' ,',@AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, ' ' + @StringDelimiter, @StringDelimiter) SET @AvailabilityGroups = LTRIM(RTRIM(@AvailabilityGroups)); WITH AvailabilityGroups1 (StartPosition, EndPosition, AvailabilityGroupItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, - SUBSTRING(@AvailabilityGroups, 1, ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) - 1) AS AvailabilityGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, + SUBSTRING(@AvailabilityGroups, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) - 1) AS AvailabilityGroupItem WHERE @AvailabilityGroups IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, - SUBSTRING(@AvailabilityGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) - EndPosition - 1) AS AvailabilityGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, + SUBSTRING(@AvailabilityGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) - EndPosition - 1) AS AvailabilityGroupItem FROM AvailabilityGroups1 WHERE EndPosition < LEN(@AvailabilityGroups) + 1 ), @@ -4103,21 +4113,21 @@ BEGIN SET @FileGroups = REPLACE(@FileGroups, CHAR(10), '') SET @FileGroups = REPLACE(@FileGroups, CHAR(13), '') - WHILE CHARINDEX(', ',@FileGroups) > 0 SET @FileGroups = REPLACE(@FileGroups,', ',',') - WHILE CHARINDEX(' ,',@FileGroups) > 0 SET @FileGroups = REPLACE(@FileGroups,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @FileGroups) > 0 SET @FileGroups = REPLACE(@FileGroups, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @FileGroups) > 0 SET @FileGroups = REPLACE(@FileGroups, ' ' + @StringDelimiter, @StringDelimiter) SET @FileGroups = LTRIM(RTRIM(@FileGroups)); WITH FileGroups1 (StartPosition, EndPosition, FileGroupItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FileGroups, 1), 0), LEN(@FileGroups) + 1) AS EndPosition, - SUBSTRING(@FileGroups, 1, ISNULL(NULLIF(CHARINDEX(',', @FileGroups, 1), 0), LEN(@FileGroups) + 1) - 1) AS FileGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FileGroups, 1), 0), LEN(@FileGroups) + 1) AS EndPosition, + SUBSTRING(@FileGroups, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FileGroups, 1), 0), LEN(@FileGroups) + 1) - 1) AS FileGroupItem WHERE @FileGroups IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FileGroups, EndPosition + 1), 0), LEN(@FileGroups) + 1) AS EndPosition, - SUBSTRING(@FileGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @FileGroups, EndPosition + 1), 0), LEN(@FileGroups) + 1) - EndPosition - 1) AS FileGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FileGroups, EndPosition + 1), 0), LEN(@FileGroups) + 1) AS EndPosition, + SUBSTRING(@FileGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FileGroups, EndPosition + 1), 0), LEN(@FileGroups) + 1) - EndPosition - 1) AS FileGroupItem FROM FileGroups1 WHERE EndPosition < LEN(@FileGroups) + 1 ), @@ -4155,21 +4165,21 @@ BEGIN SET @Objects = REPLACE(@Objects, CHAR(10), '') SET @Objects = REPLACE(@Objects, CHAR(13), '') - WHILE CHARINDEX(', ',@Objects) > 0 SET @Objects = REPLACE(@Objects,', ',',') - WHILE CHARINDEX(' ,',@Objects) > 0 SET @Objects = REPLACE(@Objects,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @Objects) > 0 SET @Objects = REPLACE(@Objects, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @Objects) > 0 SET @Objects = REPLACE(@Objects, ' ' + @StringDelimiter, @StringDelimiter) SET @Objects = LTRIM(RTRIM(@Objects)); WITH Objects1 (StartPosition, EndPosition, ObjectItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Objects, 1), 0), LEN(@Objects) + 1) AS EndPosition, - SUBSTRING(@Objects, 1, ISNULL(NULLIF(CHARINDEX(',', @Objects, 1), 0), LEN(@Objects) + 1) - 1) AS ObjectItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Objects, 1), 0), LEN(@Objects) + 1) AS EndPosition, + SUBSTRING(@Objects, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Objects, 1), 0), LEN(@Objects) + 1) - 1) AS ObjectItem WHERE @Objects IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Objects, EndPosition + 1), 0), LEN(@Objects) + 1) AS EndPosition, - SUBSTRING(@Objects, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @Objects, EndPosition + 1), 0), LEN(@Objects) + 1) - EndPosition - 1) AS ObjectItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Objects, EndPosition + 1), 0), LEN(@Objects) + 1) AS EndPosition, + SUBSTRING(@Objects, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Objects, EndPosition + 1), 0), LEN(@Objects) + 1) - EndPosition - 1) AS ObjectItem FROM Objects1 WHERE EndPosition < LEN(@Objects) + 1 ), @@ -4205,18 +4215,18 @@ BEGIN --// Select check commands //-- ---------------------------------------------------------------------------------------------------- - SET @CheckCommands = REPLACE(@CheckCommands,', ',','); + SET @CheckCommands = REPLACE(@CheckCommands, @StringDelimiter + ' ', @StringDelimiter); WITH CheckCommands (StartPosition, EndPosition, CheckCommand) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @CheckCommands, 1), 0), LEN(@CheckCommands) + 1) AS EndPosition, - SUBSTRING(@CheckCommands, 1, ISNULL(NULLIF(CHARINDEX(',', @CheckCommands, 1), 0), LEN(@CheckCommands) + 1) - 1) AS CheckCommand + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @CheckCommands, 1), 0), LEN(@CheckCommands) + 1) AS EndPosition, + SUBSTRING(@CheckCommands, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @CheckCommands, 1), 0), LEN(@CheckCommands) + 1) - 1) AS CheckCommand WHERE @CheckCommands IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @CheckCommands, EndPosition + 1), 0), LEN(@CheckCommands) + 1) AS EndPosition, - SUBSTRING(@CheckCommands, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @CheckCommands, EndPosition + 1), 0), LEN(@CheckCommands) + 1) - EndPosition - 1) AS CheckCommand + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @CheckCommands, EndPosition + 1), 0), LEN(@CheckCommands) + 1) AS EndPosition, + SUBSTRING(@CheckCommands, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @CheckCommands, EndPosition + 1), 0), LEN(@CheckCommands) + 1) - EndPosition - 1) AS CheckCommand FROM CheckCommands WHERE EndPosition < LEN(@CheckCommands) + 1 ) @@ -4307,6 +4317,12 @@ BEGIN SELECT 'The value for the parameter @LockMessageSeverity is not supported.' END + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @StringDelimiter is not supported.' + END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message]) @@ -5309,6 +5325,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @AvailabilityGroups nvarchar(max) = NULL, @LockTimeout int = NULL, @LockMessageSeverity int = 16, +@StringDelimiter nvarchar(max) = ',', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @LogToTable nvarchar(max) = 'N', @@ -5322,7 +5339,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-06 19:43:36 //-- + --// Version: 2020-01-08 20:52:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5581,6 +5598,7 @@ BEGIN SET @Parameters += ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') SET @Parameters += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar),'NULL') SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar),'NULL') + SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') @@ -5680,21 +5698,21 @@ BEGIN SET @Databases = REPLACE(@Databases, CHAR(10), '') SET @Databases = REPLACE(@Databases, CHAR(13), '') - WHILE CHARINDEX(', ',@Databases) > 0 SET @Databases = REPLACE(@Databases,', ',',') - WHILE CHARINDEX(' ,',@Databases) > 0 SET @Databases = REPLACE(@Databases,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @Databases) > 0 SET @Databases = REPLACE(@Databases, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @Databases) > 0 SET @Databases = REPLACE(@Databases, ' ' + @StringDelimiter, @StringDelimiter) SET @Databases = LTRIM(RTRIM(@Databases)); WITH Databases1 (StartPosition, EndPosition, DatabaseItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Databases, 1), 0), LEN(@Databases) + 1) AS EndPosition, - SUBSTRING(@Databases, 1, ISNULL(NULLIF(CHARINDEX(',', @Databases, 1), 0), LEN(@Databases) + 1) - 1) AS DatabaseItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, 1), 0), LEN(@Databases) + 1) AS EndPosition, + SUBSTRING(@Databases, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, 1), 0), LEN(@Databases) + 1) - 1) AS DatabaseItem WHERE @Databases IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) AS EndPosition, - SUBSTRING(@Databases, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) - EndPosition - 1) AS DatabaseItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) AS EndPosition, + SUBSTRING(@Databases, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Databases, EndPosition + 1), 0), LEN(@Databases) + 1) - EndPosition - 1) AS DatabaseItem FROM Databases1 WHERE EndPosition < LEN(@Databases) + 1 ), @@ -5810,21 +5828,21 @@ BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(13), '') - WHILE CHARINDEX(', ',@AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups,', ',',') - WHILE CHARINDEX(' ,',@AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @AvailabilityGroups) > 0 SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, ' ' + @StringDelimiter, @StringDelimiter) SET @AvailabilityGroups = LTRIM(RTRIM(@AvailabilityGroups)); WITH AvailabilityGroups1 (StartPosition, EndPosition, AvailabilityGroupItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, - SUBSTRING(@AvailabilityGroups, 1, ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) - 1) AS AvailabilityGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, + SUBSTRING(@AvailabilityGroups, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, 1), 0), LEN(@AvailabilityGroups) + 1) - 1) AS AvailabilityGroupItem WHERE @AvailabilityGroups IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, - SUBSTRING(@AvailabilityGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) - EndPosition - 1) AS AvailabilityGroupItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) AS EndPosition, + SUBSTRING(@AvailabilityGroups, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @AvailabilityGroups, EndPosition + 1), 0), LEN(@AvailabilityGroups) + 1) - EndPosition - 1) AS AvailabilityGroupItem FROM AvailabilityGroups1 WHERE EndPosition < LEN(@AvailabilityGroups) + 1 ), @@ -5914,21 +5932,21 @@ BEGIN SET @Indexes = REPLACE(@Indexes, CHAR(10), '') SET @Indexes = REPLACE(@Indexes, CHAR(13), '') - WHILE CHARINDEX(', ',@Indexes) > 0 SET @Indexes = REPLACE(@Indexes,', ',',') - WHILE CHARINDEX(' ,',@Indexes) > 0 SET @Indexes = REPLACE(@Indexes,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @Indexes) > 0 SET @Indexes = REPLACE(@Indexes, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @Indexes) > 0 SET @Indexes = REPLACE(@Indexes, ' ' + @StringDelimiter, @StringDelimiter) SET @Indexes = LTRIM(RTRIM(@Indexes)); WITH Indexes1 (StartPosition, EndPosition, IndexItem) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Indexes, 1), 0), LEN(@Indexes) + 1) AS EndPosition, - SUBSTRING(@Indexes, 1, ISNULL(NULLIF(CHARINDEX(',', @Indexes, 1), 0), LEN(@Indexes) + 1) - 1) AS IndexItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Indexes, 1), 0), LEN(@Indexes) + 1) AS EndPosition, + SUBSTRING(@Indexes, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Indexes, 1), 0), LEN(@Indexes) + 1) - 1) AS IndexItem WHERE @Indexes IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @Indexes, EndPosition + 1), 0), LEN(@Indexes) + 1) AS EndPosition, - SUBSTRING(@Indexes, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @Indexes, EndPosition + 1), 0), LEN(@Indexes) + 1) - EndPosition - 1) AS IndexItem + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Indexes, EndPosition + 1), 0), LEN(@Indexes) + 1) AS EndPosition, + SUBSTRING(@Indexes, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Indexes, EndPosition + 1), 0), LEN(@Indexes) + 1) - EndPosition - 1) AS IndexItem FROM Indexes1 WHERE EndPosition < LEN(@Indexes) + 1 ), @@ -5965,18 +5983,18 @@ BEGIN --// Select actions //-- ---------------------------------------------------------------------------------------------------- - SET @FragmentationLow = REPLACE(@FragmentationLow,', ',','); + SET @FragmentationLow = REPLACE(@FragmentationLow, @StringDelimiter + ' ', @StringDelimiter); WITH FragmentationLow (StartPosition, EndPosition, [Action]) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FragmentationLow, 1), 0), LEN(@FragmentationLow) + 1) AS EndPosition, - SUBSTRING(@FragmentationLow, 1, ISNULL(NULLIF(CHARINDEX(',', @FragmentationLow, 1), 0), LEN(@FragmentationLow) + 1) - 1) AS [Action] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationLow, 1), 0), LEN(@FragmentationLow) + 1) AS EndPosition, + SUBSTRING(@FragmentationLow, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationLow, 1), 0), LEN(@FragmentationLow) + 1) - 1) AS [Action] WHERE @FragmentationLow IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FragmentationLow, EndPosition + 1), 0), LEN(@FragmentationLow) + 1) AS EndPosition, - SUBSTRING(@FragmentationLow, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @FragmentationLow, EndPosition + 1), 0), LEN(@FragmentationLow) + 1) - EndPosition - 1) AS [Action] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationLow, EndPosition + 1), 0), LEN(@FragmentationLow) + 1) AS EndPosition, + SUBSTRING(@FragmentationLow, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationLow, EndPosition + 1), 0), LEN(@FragmentationLow) + 1) - EndPosition - 1) AS [Action] FROM FragmentationLow WHERE EndPosition < LEN(@FragmentationLow) + 1 ) @@ -5987,18 +6005,18 @@ BEGIN FROM FragmentationLow OPTION (MAXRECURSION 0) - SET @FragmentationMedium = REPLACE(@FragmentationMedium,', ',','); + SET @FragmentationMedium = REPLACE(@FragmentationMedium, @StringDelimiter + ' ', @StringDelimiter); WITH FragmentationMedium (StartPosition, EndPosition, [Action]) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FragmentationMedium, 1), 0), LEN(@FragmentationMedium) + 1) AS EndPosition, - SUBSTRING(@FragmentationMedium, 1, ISNULL(NULLIF(CHARINDEX(',', @FragmentationMedium, 1), 0), LEN(@FragmentationMedium) + 1) - 1) AS [Action] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationMedium, 1), 0), LEN(@FragmentationMedium) + 1) AS EndPosition, + SUBSTRING(@FragmentationMedium, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationMedium, 1), 0), LEN(@FragmentationMedium) + 1) - 1) AS [Action] WHERE @FragmentationMedium IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FragmentationMedium, EndPosition + 1), 0), LEN(@FragmentationMedium) + 1) AS EndPosition, - SUBSTRING(@FragmentationMedium, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @FragmentationMedium, EndPosition + 1), 0), LEN(@FragmentationMedium) + 1) - EndPosition - 1) AS [Action] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationMedium, EndPosition + 1), 0), LEN(@FragmentationMedium) + 1) AS EndPosition, + SUBSTRING(@FragmentationMedium, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationMedium, EndPosition + 1), 0), LEN(@FragmentationMedium) + 1) - EndPosition - 1) AS [Action] FROM FragmentationMedium WHERE EndPosition < LEN(@FragmentationMedium) + 1 ) @@ -6009,18 +6027,18 @@ BEGIN FROM FragmentationMedium OPTION (MAXRECURSION 0) - SET @FragmentationHigh = REPLACE(@FragmentationHigh,', ',','); + SET @FragmentationHigh = REPLACE(@FragmentationHigh, @StringDelimiter + ' ', @StringDelimiter); WITH FragmentationHigh (StartPosition, EndPosition, [Action]) AS ( SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FragmentationHigh, 1), 0), LEN(@FragmentationHigh) + 1) AS EndPosition, - SUBSTRING(@FragmentationHigh, 1, ISNULL(NULLIF(CHARINDEX(',', @FragmentationHigh, 1), 0), LEN(@FragmentationHigh) + 1) - 1) AS [Action] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationHigh, 1), 0), LEN(@FragmentationHigh) + 1) AS EndPosition, + SUBSTRING(@FragmentationHigh, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationHigh, 1), 0), LEN(@FragmentationHigh) + 1) - 1) AS [Action] WHERE @FragmentationHigh IS NOT NULL UNION ALL SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(',', @FragmentationHigh, EndPosition + 1), 0), LEN(@FragmentationHigh) + 1) AS EndPosition, - SUBSTRING(@FragmentationHigh, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(',', @FragmentationHigh, EndPosition + 1), 0), LEN(@FragmentationHigh) + 1) - EndPosition - 1) AS [Action] + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationHigh, EndPosition + 1), 0), LEN(@FragmentationHigh) + 1) AS EndPosition, + SUBSTRING(@FragmentationHigh, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @FragmentationHigh, EndPosition + 1), 0), LEN(@FragmentationHigh) + 1) - EndPosition - 1) AS [Action] FROM FragmentationHigh WHERE EndPosition < LEN(@FragmentationHigh) + 1 ) @@ -6212,6 +6230,12 @@ BEGIN SELECT 'The value for the parameter @LockMessageSeverity is not supported.' END + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @StringDelimiter is not supported.' + END + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message]) From f257fc0e6881689d1ecb656f284924a0b89c7d93 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 9 Jan 2020 23:14:27 +0100 Subject: [PATCH 145/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 144 +++++++++++++++++++++++++++-------- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 152 ++++++++++++++++++++++++++++--------- 5 files changed, 229 insertions(+), 73 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 3d31b6bc..fe2dbf0a 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-08 20:52:41 //-- + --// Version: 2020-01-09 23:10:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 34881cf1..c403c789 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -24,6 +24,8 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @BufferCount int = NULL, @MaxTransferSize int = NULL, @NumberOfFiles int = NULL, +@MinBackupSizeForMultipleFiles int = NULL, +@MaxFileSize int = NULL, @CompressionLevel int = NULL, @Description nvarchar(max) = NULL, @Threads int = NULL, @@ -76,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-08 20:52:41 //-- + --// Version: 2020-01-09 23:10:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -289,6 +291,8 @@ BEGIN SET @Parameters += ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar),'NULL') SET @Parameters += ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar),'NULL') SET @Parameters += ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar),'NULL') + SET @Parameters += ', @MinBackupSizeForMultipleFiles = ' + ISNULL(CAST(@MinBackupSizeForMultipleFiles AS nvarchar),'NULL') + SET @Parameters += ', @MaxFileSize = ' + ISNULL(CAST(@MaxFileSize AS nvarchar),'NULL') SET @Parameters += ', @CompressionLevel = ' + ISNULL(CAST(@CompressionLevel AS nvarchar),'NULL') SET @Parameters += ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL') SET @Parameters += ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar),'NULL') @@ -989,25 +993,10 @@ BEGIN IF @Compress IS NULL BEGIN - SELECT @Compress = CASE - WHEN @BackupSoftware IS NULL AND EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression default' AND value_in_use = 1) THEN 'Y' - WHEN @BackupSoftware IS NULL AND NOT EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression default' AND value_in_use = 1) THEN 'N' - WHEN @BackupSoftware IS NOT NULL AND (@CompressionLevel IS NULL OR @CompressionLevel > 0) THEN 'Y' - WHEN @BackupSoftware IS NOT NULL AND @CompressionLevel = 0 THEN 'N' - END - END - - ---------------------------------------------------------------------------------------------------- - --// Get number of files //-- - ---------------------------------------------------------------------------------------------------- - - IF @NumberOfFiles IS NULL - BEGIN - SELECT @NumberOfFiles = CASE - WHEN @BackupSoftware = 'DATA_DOMAIN_BOOST' THEN 1 - WHEN @URL IS NOT NULL THEN (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) - ELSE (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) - END + SELECT @Compress = CASE WHEN @BackupSoftware IS NULL AND EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression default' AND value_in_use = 1) THEN 'Y' + WHEN @BackupSoftware IS NULL AND NOT EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression default' AND value_in_use = 1) THEN 'N' + WHEN @BackupSoftware IS NOT NULL AND (@CompressionLevel IS NULL OR @CompressionLevel > 0) THEN 'Y' + WHEN @BackupSoftware IS NOT NULL AND @CompressionLevel = 0 THEN 'N' END END ---------------------------------------------------------------------------------------------------- @@ -1158,12 +1147,60 @@ BEGIN SELECT 'The value for the parameter @MaxTransferSize is not supported.' END - IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 + IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN INSERT INTO @Errors ([Message]) SELECT 'The value for the parameter @NumberOfFiles is not supported.' END + IF @MinBackupSizeForMultipleFiles <= 0 + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported.' + END + + IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @NumberOfFiles IS NULL + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.' + END + + IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @BackupType = 'DIFF' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.' + END + + IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @BackupType = 'LOG' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.' + END + + IF @MaxFileSize <= 0 + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MaxFileSize is not supported.' + END + + IF @MaxFileSize IS NOT NULL AND @NumberOfFiles IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The parameters @MaxFileSize and @NumberOfFiles cannot be used together.' + END + + IF @MaxFileSize IS NOT NULL AND @BackupType = 'DIFF' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.' + END + + IF @MaxFileSize IS NOT NULL AND @BackupType = 'LOG' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.' + END + IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message]) @@ -1278,24 +1315,30 @@ BEGIN SELECT 'The value for the parameter @AdaptiveCompression is not supported.' END - IF (@ModificationLevel IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') + IF (@ModificationLevel IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count')) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN INSERT INTO @Errors ([Message]) SELECT 'The value for the parameter @ModificationLevel is not supported.' END - IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb')) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN INSERT INTO @Errors ([Message]) SELECT 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' END - IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_backup_time')) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN INSERT INTO @Errors ([Message]) SELECT 'The value for the parameter @TimeSinceLastLogBackup is not supported.' END + IF (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The parameters @TimeSinceLastLogBackup and @LogSizeSinceLastLogBackup can only be used together.' + END + IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message]) @@ -1414,7 +1457,19 @@ BEGIN SELECT 'The value for the parameter @StringDelimiter is not supported.' END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.' + END + + IF @DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabaseOrder is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.' + END + + IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 BEGIN INSERT INTO @Errors ([Message]) SELECT 'The value for the parameter @DatabaseOrder is not supported.' @@ -1826,7 +1881,7 @@ BEGIN WHERE database_id = DB_ID(@CurrentDatabaseName) END - IF @CurrentDatabaseState = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND @ChangeBackupType = 'Y' AND @ModificationLevel IS NOT NULL + IF @CurrentDatabaseState = 'ONLINE' AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) BEGIN SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' @@ -1847,7 +1902,7 @@ BEGIN END END - IF @CurrentDatabaseState = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) + IF @CurrentDatabaseState = 'ONLINE' AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN SELECT @CurrentLastLogBackup = log_backup_time, @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb @@ -1869,9 +1924,32 @@ BEGIN BEGIN SET @CurrentBackupType = 'FULL' END - END + END; - SET @CurrentNumberOfFiles = @NumberOfFiles + WITH CurrentDatabase AS + ( + SELECT BackupSize = CASE WHEN @CurrentBackupType = 'FULL' THEN COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) + WHEN @CurrentBackupType = 'DIFF' THEN CAST(@CurrentModifiedExtentPageCount AS bigint) * 8192 + WHEN @CurrentBackupType = 'LOG' THEN CAST(@CurrentLogSizeSinceLastLogBackup * 1024 * 1024 AS bigint) + END, + MaxNumberOfFiles = CASE WHEN @BackupSoftware IN('SQLBACKUP','DATA_DOMAIN_BOOST') THEN 32 ELSE 64 END, + CASE WHEN (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) > 0 THEN (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) ELSE (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) END AS NumberOfDirectories, + CAST(@MinBackupSizeForMultipleFiles AS bigint) * 1024 * 1024 AS MinBackupSizeForMultipleFiles, + CAST(@MaxFileSize AS bigint) * 1024 * 1024 AS MaxFileSize + ) + SELECT @CurrentNumberOfFiles = CASE WHEN @NumberOfFiles IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' THEN 1 + WHEN @NumberOfFiles IS NULL AND @MaxFileSize IS NULL THEN NumberOfDirectories + WHEN @NumberOfFiles = 1 THEN @NumberOfFiles + WHEN @NumberOfFiles > 1 AND (BackupSize >= MinBackupSizeForMultipleFiles OR MinBackupSizeForMultipleFiles IS NULL OR BackupSize IS NULL) THEN @NumberOfFiles + WHEN @NumberOfFiles > 1 AND (BackupSize < MinBackupSizeForMultipleFiles) THEN NumberOfDirectories + WHEN @NumberOfFiles IS NULL AND @MaxFileSize IS NOT NULL AND BackupSize IS NULL THEN NumberOfDirectories + WHEN @NumberOfFiles IS NULL AND @MaxFileSize IS NOT NULL THEN (SELECT MIN(NumberOfFilesInEachDirectory) + FROM (SELECT ((BackupSize / NumberOfDirectories) / MaxFileSize + CASE WHEN (BackupSize / NumberOfDirectories) % MaxFileSize = 0 THEN 0 ELSE 1 END) AS NumberOfFilesInEachDirectory + UNION + SELECT MaxNumberOfFiles / NumberOfDirectories) Files) * NumberOfDirectories + END + + FROM CurrentDatabase SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring @@ -1956,16 +2034,16 @@ BEGIN SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentBackupType IN('DIFF','FULL') AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) + IF @CurrentBackupType IN('DIFF','FULL') AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') BEGIN - SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar),'N/A') + SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar) + ' (' + CAST(@CurrentAllocatedExtentPageCount * 1. * 8 / 1024 AS nvarchar) + ' MB)','N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Modified extent page count: ' + ISNULL(CAST(@CurrentModifiedExtentPageCount AS nvarchar),'N/A') + SET @DatabaseMessage = 'Modified extent page count: ' + ISNULL(CAST(@CurrentModifiedExtentPageCount AS nvarchar) + ' (' + CAST(@CurrentModifiedExtentPageCount * 1. * 8 / 1024 AS nvarchar) + ' MB)','N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - IF @CurrentBackupType = 'LOG' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) + IF @CurrentBackupType = 'LOG' AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),NULLIF(@CurrentLastLogBackup,'1900-01-01'),120),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 0cb91474..430a6c01 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -38,7 +38,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-08 20:52:41 //-- + --// Version: 2020-01-09 23:10:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 69179fdb..9fbb454a 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-08 20:52:41 //-- + --// Version: 2020-01-09 23:10:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index a5c8fea6..a119c528 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-08 20:52:41 +Version: 2020-01-09 23:10:28 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-08 20:52:41 //-- + --// Version: 2020-01-09 23:10:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -374,6 +374,8 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @BufferCount int = NULL, @MaxTransferSize int = NULL, @NumberOfFiles int = NULL, +@MinBackupSizeForMultipleFiles int = NULL, +@MaxFileSize int = NULL, @CompressionLevel int = NULL, @Description nvarchar(max) = NULL, @Threads int = NULL, @@ -426,7 +428,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-08 20:52:41 //-- + --// Version: 2020-01-09 23:10:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -639,6 +641,8 @@ BEGIN SET @Parameters += ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar),'NULL') SET @Parameters += ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar),'NULL') SET @Parameters += ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar),'NULL') + SET @Parameters += ', @MinBackupSizeForMultipleFiles = ' + ISNULL(CAST(@MinBackupSizeForMultipleFiles AS nvarchar),'NULL') + SET @Parameters += ', @MaxFileSize = ' + ISNULL(CAST(@MaxFileSize AS nvarchar),'NULL') SET @Parameters += ', @CompressionLevel = ' + ISNULL(CAST(@CompressionLevel AS nvarchar),'NULL') SET @Parameters += ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL') SET @Parameters += ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar),'NULL') @@ -1339,25 +1343,10 @@ BEGIN IF @Compress IS NULL BEGIN - SELECT @Compress = CASE - WHEN @BackupSoftware IS NULL AND EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression default' AND value_in_use = 1) THEN 'Y' - WHEN @BackupSoftware IS NULL AND NOT EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression default' AND value_in_use = 1) THEN 'N' - WHEN @BackupSoftware IS NOT NULL AND (@CompressionLevel IS NULL OR @CompressionLevel > 0) THEN 'Y' - WHEN @BackupSoftware IS NOT NULL AND @CompressionLevel = 0 THEN 'N' - END - END - - ---------------------------------------------------------------------------------------------------- - --// Get number of files //-- - ---------------------------------------------------------------------------------------------------- - - IF @NumberOfFiles IS NULL - BEGIN - SELECT @NumberOfFiles = CASE - WHEN @BackupSoftware = 'DATA_DOMAIN_BOOST' THEN 1 - WHEN @URL IS NOT NULL THEN (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) - ELSE (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) - END + SELECT @Compress = CASE WHEN @BackupSoftware IS NULL AND EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression default' AND value_in_use = 1) THEN 'Y' + WHEN @BackupSoftware IS NULL AND NOT EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression default' AND value_in_use = 1) THEN 'N' + WHEN @BackupSoftware IS NOT NULL AND (@CompressionLevel IS NULL OR @CompressionLevel > 0) THEN 'Y' + WHEN @BackupSoftware IS NOT NULL AND @CompressionLevel = 0 THEN 'N' END END ---------------------------------------------------------------------------------------------------- @@ -1508,12 +1497,60 @@ BEGIN SELECT 'The value for the parameter @MaxTransferSize is not supported.' END - IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles IS NULL OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 + IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN INSERT INTO @Errors ([Message]) SELECT 'The value for the parameter @NumberOfFiles is not supported.' END + IF @MinBackupSizeForMultipleFiles <= 0 + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported.' + END + + IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @NumberOfFiles IS NULL + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.' + END + + IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @BackupType = 'DIFF' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.' + END + + IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @BackupType = 'LOG' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.' + END + + IF @MaxFileSize <= 0 + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MaxFileSize is not supported.' + END + + IF @MaxFileSize IS NOT NULL AND @NumberOfFiles IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The parameters @MaxFileSize and @NumberOfFiles cannot be used together.' + END + + IF @MaxFileSize IS NOT NULL AND @BackupType = 'DIFF' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.' + END + + IF @MaxFileSize IS NOT NULL AND @BackupType = 'LOG' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.' + END + IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message]) @@ -1628,24 +1665,30 @@ BEGIN SELECT 'The value for the parameter @AdaptiveCompression is not supported.' END - IF (@ModificationLevel IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') + IF (@ModificationLevel IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count')) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN INSERT INTO @Errors ([Message]) SELECT 'The value for the parameter @ModificationLevel is not supported.' END - IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NULL) OR (@LogSizeSinceLastLogBackup IS NULL AND @TimeSinceLastLogBackup IS NOT NULL) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb')) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN INSERT INTO @Errors ([Message]) SELECT 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' END - IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026)) OR (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_backup_time')) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN INSERT INTO @Errors ([Message]) SELECT 'The value for the parameter @TimeSinceLastLogBackup is not supported.' END + IF (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The parameters @TimeSinceLastLogBackup and @LogSizeSinceLastLogBackup can only be used together.' + END + IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message]) @@ -1764,7 +1807,19 @@ BEGIN SELECT 'The value for the parameter @StringDelimiter is not supported.' END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') OR (@DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.' + END + + IF @DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') + BEGIN + INSERT INTO @Errors ([Message]) + SELECT 'The value for the parameter @DatabaseOrder is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.' + END + + IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 BEGIN INSERT INTO @Errors ([Message]) SELECT 'The value for the parameter @DatabaseOrder is not supported.' @@ -2176,7 +2231,7 @@ BEGIN WHERE database_id = DB_ID(@CurrentDatabaseName) END - IF @CurrentDatabaseState = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND @ChangeBackupType = 'Y' AND @ModificationLevel IS NOT NULL + IF @CurrentDatabaseState = 'ONLINE' AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) BEGIN SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' @@ -2197,7 +2252,7 @@ BEGIN END END - IF @CurrentDatabaseState = 'ONLINE' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) + IF @CurrentDatabaseState = 'ONLINE' AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN SELECT @CurrentLastLogBackup = log_backup_time, @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb @@ -2219,9 +2274,32 @@ BEGIN BEGIN SET @CurrentBackupType = 'FULL' END - END + END; - SET @CurrentNumberOfFiles = @NumberOfFiles + WITH CurrentDatabase AS + ( + SELECT BackupSize = CASE WHEN @CurrentBackupType = 'FULL' THEN COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) + WHEN @CurrentBackupType = 'DIFF' THEN CAST(@CurrentModifiedExtentPageCount AS bigint) * 8192 + WHEN @CurrentBackupType = 'LOG' THEN CAST(@CurrentLogSizeSinceLastLogBackup * 1024 * 1024 AS bigint) + END, + MaxNumberOfFiles = CASE WHEN @BackupSoftware IN('SQLBACKUP','DATA_DOMAIN_BOOST') THEN 32 ELSE 64 END, + CASE WHEN (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) > 0 THEN (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) ELSE (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) END AS NumberOfDirectories, + CAST(@MinBackupSizeForMultipleFiles AS bigint) * 1024 * 1024 AS MinBackupSizeForMultipleFiles, + CAST(@MaxFileSize AS bigint) * 1024 * 1024 AS MaxFileSize + ) + SELECT @CurrentNumberOfFiles = CASE WHEN @NumberOfFiles IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' THEN 1 + WHEN @NumberOfFiles IS NULL AND @MaxFileSize IS NULL THEN NumberOfDirectories + WHEN @NumberOfFiles = 1 THEN @NumberOfFiles + WHEN @NumberOfFiles > 1 AND (BackupSize >= MinBackupSizeForMultipleFiles OR MinBackupSizeForMultipleFiles IS NULL OR BackupSize IS NULL) THEN @NumberOfFiles + WHEN @NumberOfFiles > 1 AND (BackupSize < MinBackupSizeForMultipleFiles) THEN NumberOfDirectories + WHEN @NumberOfFiles IS NULL AND @MaxFileSize IS NOT NULL AND BackupSize IS NULL THEN NumberOfDirectories + WHEN @NumberOfFiles IS NULL AND @MaxFileSize IS NOT NULL THEN (SELECT MIN(NumberOfFilesInEachDirectory) + FROM (SELECT ((BackupSize / NumberOfDirectories) / MaxFileSize + CASE WHEN (BackupSize / NumberOfDirectories) % MaxFileSize = 0 THEN 0 ELSE 1 END) AS NumberOfFilesInEachDirectory + UNION + SELECT MaxNumberOfFiles / NumberOfDirectories) Files) * NumberOfDirectories + END + + FROM CurrentDatabase SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring @@ -2306,16 +2384,16 @@ BEGIN SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentBackupType IN('DIFF','FULL') AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) + IF @CurrentBackupType IN('DIFF','FULL') AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') BEGIN - SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar),'N/A') + SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar) + ' (' + CAST(@CurrentAllocatedExtentPageCount * 1. * 8 / 1024 AS nvarchar) + ' MB)','N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Modified extent page count: ' + ISNULL(CAST(@CurrentModifiedExtentPageCount AS nvarchar),'N/A') + SET @DatabaseMessage = 'Modified extent page count: ' + ISNULL(CAST(@CurrentModifiedExtentPageCount AS nvarchar) + ' (' + CAST(@CurrentModifiedExtentPageCount * 1. * 8 / 1024 AS nvarchar) + ' MB)','N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - IF @CurrentBackupType = 'LOG' AND ((@Version >= 12.06024 AND @Version < 13) OR @Version >= 13.05026) + IF @CurrentBackupType = 'LOG' AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),NULLIF(@CurrentLastLogBackup,'1900-01-01'),120),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -3594,7 +3672,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-08 20:52:41 //-- + --// Version: 2020-01-09 23:10:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5339,7 +5417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-08 20:52:41 //-- + --// Version: 2020-01-09 23:10:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 517fea10b074850aa9c40daa8aaebeca7be86bdd Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 10 Jan 2020 22:42:00 +0100 Subject: [PATCH 146/188] Add files via upload --- .gitattributes | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..df745445 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# linguist overrides +*.sql linguist-language=TSQL From 365dd022ad160dede860d345bba8e6d80a265f3b Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 11 Jan 2020 12:56:56 +0100 Subject: [PATCH 147/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 915 ++++++++++--------- DatabaseIntegrityCheck.sql | 394 ++++---- IndexOptimize.sql | 428 +++++---- MaintenanceSolution.sql | 1741 ++++++++++++++++++------------------ 5 files changed, 1729 insertions(+), 1751 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index fe2dbf0a..d58b5483 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-09 23:10:28 //-- + --// Version: 2020-01-11 12:40:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index c403c789..808cba6b 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-09 23:10:28 //-- + --// Version: 2020-01-11 12:40:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -157,29 +157,17 @@ BEGIN DECLARE @CurrentAllocatedExtentPageCount bigint DECLARE @CurrentModifiedExtentPageCount bigint - DECLARE @CurrentCommand01 nvarchar(max) - DECLARE @CurrentCommand02 nvarchar(max) - DECLARE @CurrentCommand03 nvarchar(max) - DECLARE @CurrentCommand04 nvarchar(max) - DECLARE @CurrentCommand05 nvarchar(max) - DECLARE @CurrentCommand07 nvarchar(max) - - DECLARE @CurrentCommandOutput01 int - DECLARE @CurrentCommandOutput02 int - DECLARE @CurrentCommandOutput03 int - DECLARE @CurrentCommandOutput04 int - DECLARE @CurrentCommandOutput05 int - - DECLARE @CurrentCommandType01 nvarchar(max) - DECLARE @CurrentCommandType02 nvarchar(max) - DECLARE @CurrentCommandType03 nvarchar(max) - DECLARE @CurrentCommandType04 nvarchar(max) - DECLARE @CurrentCommandType05 nvarchar(max) + DECLARE @CurrentDatabaseContext nvarchar(max) + DECLARE @CurrentCommand nvarchar(max) + DECLARE @CurrentCommandOutput int + DECLARE @CurrentCommandType nvarchar(max) DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, - [Message] nvarchar(max)) + [Message] nvarchar(max) NOT NULL, + Severity int NOT NULL) DECLARE @CurrentMessage nvarchar(max) + DECLARE @CurrentSeverity int DECLARE @Directories TABLE (ID int PRIMARY KEY, DirectoryPath nvarchar(max), @@ -225,6 +213,8 @@ BEGIN StartPosition int, Selected bit) + DECLARE @CurrentBackupOutput bit + DECLARE @CurrentBackupSet TABLE (ID int IDENTITY PRIMARY KEY, Mirror bit, VerifyCompleted bit, @@ -372,62 +362,62 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16 END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16 END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16 END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 END 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') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16 END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16 END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16 END IF @@TRANCOUNT <> 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The transaction count is not 0.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The transaction count is not 0.', 16 END IF @AmazonRDS = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The stored procedure DatabaseBackup is not supported on Amazon RDS.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The stored procedure DatabaseBackup is not supported on Amazon RDS.', 16 END ---------------------------------------------------------------------------------------------------- @@ -554,8 +544,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Databases is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Databases is not supported.', 16 END ---------------------------------------------------------------------------------------------------- @@ -649,20 +639,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16 END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16 END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16 END ---------------------------------------------------------------------------------------------------- @@ -677,8 +667,8 @@ BEGIN ORDER BY DatabaseName ASC IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 16 END SET @ErrorMessage = '' @@ -691,8 +681,8 @@ BEGIN OPTION (RECOMPILE) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 16 END ---------------------------------------------------------------------------------------------------- @@ -793,8 +783,8 @@ BEGIN OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath <> 'NUL')) OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Directory is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Directory is not supported.', 16 END IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) @@ -809,14 +799,14 @@ BEGIN OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MirrorDirectory is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16 END IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'Mirrored backup to disk is only available in Enterprise and Developer Edition.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'Mirrored backup to disk is only available in Enterprise and Developer Edition.', 16 END IF NOT EXISTS (SELECT * FROM @Errors WHERE [Message] IN('The value for the parameter @Directory is not supported.','The value for the parameter @MirrorDirectory is not supported.')) @@ -840,8 +830,8 @@ BEGIN IF NOT EXISTS (SELECT * FROM @DirectoryInfo WHERE FileExists = 0 AND FileIsADirectory = 1 AND ParentDirectoryExists = 1) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.', 16 END UPDATE @Directories @@ -923,16 +913,16 @@ BEGIN OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @URL is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @URL is not supported.', 16 END IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath NOT LIKE 'https://%/%') OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MirrorURL is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16 END ---------------------------------------------------------------------------------------------------- @@ -1005,498 +995,498 @@ BEGIN IF @BackupType NOT IN ('FULL','DIFF','LOG') OR @BackupType IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @BackupType is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @BackupType is not supported.', 16 END IF SERVERPROPERTY('EngineEdition') = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.', 16 END IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Verify is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Verify is not supported.', 16 END IF @Verify = 'Y' AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.', 16 END IF @CleanupTime < 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupTime is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupTime is not supported.', 16 END IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.', 16 END IF @CleanupTime IS NOT NULL AND @HostPlatform = 'Linux' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.', 16 END IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.', 16 END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.', 16 END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.', 16 END IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.', 16 END IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupMode is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupMode is not supported.', 16 END IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Compress is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Compress is not supported.', 16 END IF @CopyOnly NOT IN ('Y','N') OR @CopyOnly IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CopyOnly is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CopyOnly is not supported.', 16 END IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @ChangeBackupType is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @ChangeBackupType is not supported.', 16 END IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @BackupSoftware is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @BackupSoftware is not supported.', 16 END IF @BackupSoftware = 'LITESPEED' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_backup_database') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.', 16 END IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.', 16 END IF @BackupSoftware = 'SQLSAFE' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_ss_backup') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.', 16 END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'PC' AND [name] = 'emc_run_backup') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.', 16 END IF @CheckSum NOT IN ('Y','N') OR @CheckSum IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CheckSum is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CheckSum is not supported.', 16 END IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @BlockSize is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @BlockSize is not supported.', 16 END IF @BufferCount <= 0 OR @BufferCount > 2147483647 OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @BufferCount is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @BufferCount is not supported.', 16 END IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MaxTransferSize is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16 END IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @NumberOfFiles is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16 END IF @MinBackupSizeForMultipleFiles <= 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported.', 16 END IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @NumberOfFiles IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.', 16 END IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @BackupType = 'DIFF' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.', 16 END IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @BackupType = 'LOG' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16 END IF @MaxFileSize <= 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MaxFileSize is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MaxFileSize is not supported.', 16 END IF @MaxFileSize IS NOT NULL AND @NumberOfFiles IS NOT NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The parameters @MaxFileSize and @NumberOfFiles cannot be used together.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The parameters @MaxFileSize and @NumberOfFiles cannot be used together.', 16 END IF @MaxFileSize IS NOT NULL AND @BackupType = 'DIFF' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.', 16 END IF @MaxFileSize IS NOT NULL AND @BackupType = 'LOG' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16 END IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CompressionLevel is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CompressionLevel is not supported.', 16 END IF LEN(@Description) > 255 OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Description is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Description is not supported.', 16 END IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) OR (@BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32)) OR (@BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32)) OR (@BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Threads is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Threads is not supported.', 16 END IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) OR @Throttle < 1 OR @Throttle > 100 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Throttle is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Throttle is not supported.', 16 END IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Encrypt is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Encrypt is not supported.', 16 END IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16 END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL) OR (@ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @ServerCertificate is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @ServerCertificate is not supported.', 16 END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL) OR (@ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.', 16 END IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @EncryptionKey is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @EncryptionKey is not supported.', 16 END IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL OR (@ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.', 16 END IF @OverrideBackupPreference NOT IN('Y','N') OR @OverrideBackupPreference IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @OverrideBackupPreference is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @OverrideBackupPreference is not supported.', 16 END IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL OR (@NoRecovery = 'Y' AND @BackupType <> 'LOG') OR (@NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @NoRecovery is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @NoRecovery is not supported.', 16 END IF (@URL IS NOT NULL AND @Directory IS NOT NULL) OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@URL IS NOT NULL AND @Version < 11.03339) OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @URL is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @URL is not supported.', 16 END IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Credential is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Credential is not supported.', 16 END IF @MirrorCleanupTime < 0 OR (@MirrorCleanupTime IS NOT NULL AND @MirrorDirectory IS NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MirrorCleanupTime is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MirrorCleanupTime is not supported.', 16 END IF @MirrorCleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @MirrorCleanupMode IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MirrorCleanupMode is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MirrorCleanupMode is not supported.', 16 END IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @URL IS NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MirrorURL is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16 END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Updateability is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Updateability is not supported.', 16 END IF @AdaptiveCompression NOT IN('SIZE','SPEED') OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @AdaptiveCompression is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @AdaptiveCompression is not supported.', 16 END IF (@ModificationLevel IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count')) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @ModificationLevel is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @ModificationLevel is not supported.', 16 END IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb')) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.', 16 END IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_backup_time')) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @TimeSinceLastLogBackup is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @TimeSinceLastLogBackup is not supported.', 16 END IF (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The parameters @TimeSinceLastLogBackup and @LogSizeSinceLastLogBackup can only be used together.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The parameters @TimeSinceLastLogBackup and @LogSizeSinceLastLogBackup can only be used together.', 16 END IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DataDomainBoostHost is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16 END IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DataDomainBoostUser is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16 END IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16 END IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16 END IF @DirectoryStructure = '' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DirectoryStructure is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DirectoryStructure is not supported.', 16 END IF @AvailabilityGroupDirectoryStructure = '' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.', 16 END IF @FileName IS NULL OR @FileName = '' OR @FileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') OR @FileName LIKE '%{DirectorySeperator}%' OR @FileName LIKE '%/%' OR @FileName LIKE '%\%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FileName is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FileName is not supported.', 16 END IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) OR @AvailabilityGroupFileName = '' OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' OR @AvailabilityGroupFileName LIKE '%/%' OR @AvailabilityGroupFileName LIKE '%\%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16 END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The parameter @DirectoryStructure contains one or more tokens that are not supported.', 16 END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.', 16 END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The parameter @FileName contains one or more tokens that are not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The parameter @FileName contains one or more tokens that are not supported.', 16 END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.', 16 END IF @FileExtensionFull LIKE '%.%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FileExtensionFull is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FileExtensionFull is not supported.', 16 END IF @FileExtensionDiff LIKE '%.%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FileExtensionDiff is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FileExtensionDiff is not supported.', 16 END IF @FileExtensionLog LIKE '%.%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FileExtensionLog is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FileExtensionLog is not supported.', 16 END IF @Init NOT IN('Y','N') OR @Init IS NULL OR (@Init = 'Y' AND @BackupType = 'LOG') OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Init is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Init is not supported.', 16 END IF @Format NOT IN('Y','N') OR @Format IS NULL OR (@Format = 'Y' AND @BackupType = 'LOG') OR (@Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Format is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Format is not supported.', 16 END IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL) OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED') OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16 END IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @StringDelimiter is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 END IF @DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabaseOrder is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabaseOrder is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16 END IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LogToTable is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LogToTable is not supported.', 16 END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Execute is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Execute is not supported.', 16 END IF EXISTS(SELECT * FROM @Errors) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.', 16 END ---------------------------------------------------------------------------------------------------- @@ -1510,8 +1500,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -1521,8 +1511,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END ---------------------------------------------------------------------------------------------------- @@ -1531,33 +1521,33 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16 END ---------------------------------------------------------------------------------------------------- --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor - FETCH ErrorCursor INTO @CurrentMessage + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity WHILE @@FETCH_STATUS = 0 BEGIN - RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR('%s', @CurrentSeverity, 1, @CurrentMessage) WITH NOWAIT RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT - FETCH NEXT FROM ErrorCursor INTO @CurrentMessage + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity END CLOSE ErrorCursor DEALLOCATE ErrorCursor - IF EXISTS (SELECT * FROM @Errors) + IF EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) BEGIN SET @ReturnCode = 50000 GOTO Logging @@ -1883,9 +1873,9 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) BEGIN - SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' + SET @CurrentCommand = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand07, @params = N'@ParamAllocatedExtentPageCount bigint OUTPUT, @ParamModifiedExtentPageCount bigint OUTPUT', @ParamAllocatedExtentPageCount = @CurrentAllocatedExtentPageCount OUTPUT, @ParamModifiedExtentPageCount = @CurrentModifiedExtentPageCount OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAllocatedExtentPageCount bigint OUTPUT, @ParamModifiedExtentPageCount bigint OUTPUT', @ParamAllocatedExtentPageCount = @CurrentAllocatedExtentPageCount OUTPUT, @ParamModifiedExtentPageCount = @CurrentModifiedExtentPageCount OUTPUT END SET @CurrentBackupType = @BackupType @@ -2587,26 +2577,29 @@ BEGIN BREAK END - SET @CurrentCommandType01 = 'xp_create_subdir' - SET @CurrentCommand01 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_create_subdir N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''' IF @ReturnCode <> 0 RAISERROR(''Error creating directory.'', 16, 1)' - EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'xp_create_subdir' + + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_create_subdir N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''' IF @ReturnCode <> 0 RAISERROR(''Error creating directory.'', 16, 1)' + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput01 = @Error - IF @CurrentCommandOutput01 <> 0 SET @ReturnCode = @CurrentCommandOutput01 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput UPDATE @CurrentDirectories SET CreateCompleted = 1, - CreateOutput = @CurrentCommandOutput01 + CreateOutput = @CurrentCommandOutput WHERE ID = @CurrentDirectoryID SET @CurrentDirectoryID = NULL SET @CurrentDirectoryPath = NULL - SET @CurrentCommand01 = NULL - - SET @CurrentCommandOutput01 = NULL - - SET @CurrentCommandType01 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL END END @@ -2666,51 +2659,58 @@ BEGIN IF @BackupSoftware IS NULL BEGIN - SET @CurrentCommandType02 = 'xp_delete_file' + SET @CurrentDatabaseContext = 'master' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' + SET @CurrentCommandType = 'xp_delete_file' + + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' BEGIN - SET @CurrentCommandType02 = 'xp_slssqlmaint' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'xp_slssqlmaint' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN - SET @CurrentCommandType02 = 'sqbutility' + SET @CurrentDatabaseContext = 'master' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' + SET @CurrentCommandType = 'sqbutility' + + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN - SET @CurrentCommandType02 = 'xp_ss_delete' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'xp_ss_delete' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END - EXECUTE @CurrentCommandOutput02 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand02, @CommandType = @CurrentCommandType02, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput02 = @Error - IF @CurrentCommandOutput02 <> 0 SET @ReturnCode = @CurrentCommandOutput02 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput UPDATE @CurrentDirectories SET CleanupCompleted = 1, - CleanupOutput = @CurrentCommandOutput02 + CleanupOutput = @CurrentCommandOutput WHERE ID = @CurrentDirectoryID SET @CurrentDirectoryID = NULL SET @CurrentDirectoryPath = NULL SET @CurrentCleanupDate = NULL - SET @CurrentCommand02 = NULL - - SET @CurrentCommandOutput02 = NULL - - SET @CurrentCommandType02 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL END END @@ -2719,112 +2719,116 @@ BEGIN BEGIN IF @BackupSoftware IS NULL BEGIN - SELECT @CurrentCommandType03 = CASE + SET @CurrentDatabaseContext = 'master' + + SELECT @CurrentCommandType = CASE WHEN @CurrentBackupType IN('DIFF','FULL') THEN 'BACKUP_DATABASE' WHEN @CurrentBackupType = 'LOG' THEN 'BACKUP_LOG' END - SELECT @CurrentCommand03 = CASE + SELECT @CurrentCommand = CASE WHEN @CurrentBackupType IN('DIFF','FULL') THEN 'BACKUP DATABASE ' + QUOTENAME(@CurrentDatabaseName) WHEN @CurrentBackupType = 'LOG' THEN 'BACKUP LOG ' + QUOTENAME(@CurrentDatabaseName) END - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ' READ_WRITE_FILEGROUPS' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand += ' READ_WRITE_FILEGROUPS' - SET @CurrentCommand03 += ' TO' + SET @CurrentCommand += ' TO' - SELECT @CurrentCommand03 += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SET @CurrentCommand03 += ' MIRROR TO' + SET @CurrentCommand += ' MIRROR TO' - SELECT @CurrentCommand03 += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 1 ORDER BY FilePath ASC END - SET @CurrentCommand03 += ' WITH ' - IF @CheckSum = 'Y' SET @CurrentCommand03 += 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand03 += 'NO_CHECKSUM' + SET @CurrentCommand += ' WITH ' + IF @CheckSum = 'Y' SET @CurrentCommand += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' IF @Version >= 10 BEGIN - SET @CurrentCommand03 += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND @Version >= 13 AND @CurrentMaxTransferSize > 65536)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END + SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND @Version >= 13 AND @CurrentMaxTransferSize > 65536)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END END - IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 += ', DIFFERENTIAL' + IF @CurrentBackupType = 'DIFF' SET @CurrentCommand += ', DIFFERENTIAL' IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SET @CurrentCommand03 += ', FORMAT' + SET @CurrentCommand += ', FORMAT' END - IF @CopyOnly = 'Y' SET @CurrentCommand03 += ', COPY_ONLY' - IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 += ', NORECOVERY' - IF @Init = 'Y' SET @CurrentCommand03 += ', INIT' - IF @Format = 'Y' SET @CurrentCommand03 += ', FORMAT' - IF @BlockSize IS NOT NULL SET @CurrentCommand03 += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) - IF @BufferCount IS NOT NULL SET @CurrentCommand03 += ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar) - IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' - IF @Encrypt = 'Y' SET @CurrentCommand03 += ', ENCRYPTION (ALGORITHM = ' + UPPER(@EncryptionAlgorithm) + ', ' - IF @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL SET @CurrentCommand03 += 'SERVER CERTIFICATE = ' + QUOTENAME(@ServerCertificate) - IF @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL SET @CurrentCommand03 += 'SERVER ASYMMETRIC KEY = ' + QUOTENAME(@ServerAsymmetricKey) - IF @Encrypt = 'Y' SET @CurrentCommand03 += ')' - IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand03 += ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' + IF @CopyOnly = 'Y' SET @CurrentCommand += ', COPY_ONLY' + IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand += ', NORECOVERY' + IF @Init = 'Y' SET @CurrentCommand += ', INIT' + IF @Format = 'Y' SET @CurrentCommand += ', FORMAT' + IF @BlockSize IS NOT NULL SET @CurrentCommand += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) + IF @BufferCount IS NOT NULL SET @CurrentCommand += ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) + IF @Description IS NOT NULL SET @CurrentCommand += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' + IF @Encrypt = 'Y' SET @CurrentCommand += ', ENCRYPTION (ALGORITHM = ' + UPPER(@EncryptionAlgorithm) + ', ' + IF @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL SET @CurrentCommand += 'SERVER CERTIFICATE = ' + QUOTENAME(@ServerCertificate) + IF @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL SET @CurrentCommand += 'SERVER ASYMMETRIC KEY = ' + QUOTENAME(@ServerAsymmetricKey) + IF @Encrypt = 'Y' SET @CurrentCommand += ')' + IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand += ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' END IF @BackupSoftware = 'LITESPEED' BEGIN - SELECT @CurrentCommandType03 = CASE + SET @CurrentDatabaseContext = 'master' + + SELECT @CurrentCommandType = CASE WHEN @CurrentBackupType IN('DIFF','FULL') THEN 'xp_backup_database' WHEN @CurrentBackupType = 'LOG' THEN 'xp_backup_log' END - SELECT @CurrentCommand03 = CASE + SELECT @CurrentCommand = CASE WHEN @CurrentBackupType IN('DIFF','FULL') THEN 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_backup_database @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' WHEN @CurrentBackupType = 'LOG' THEN 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_backup_log @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' END - SELECT @CurrentCommand03 += ', @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand += ', @filename = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SELECT @CurrentCommand03 += ', @mirror = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand += ', @mirror = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 1 ORDER BY FilePath ASC END - SET @CurrentCommand03 += ', @with = ''' - IF @CheckSum = 'Y' SET @CurrentCommand03 += 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand03 += 'NO_CHECKSUM' - IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 += ', DIFFERENTIAL' - IF @CopyOnly = 'Y' SET @CurrentCommand03 += ', COPY_ONLY' - IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 += ', NORECOVERY' - IF @BlockSize IS NOT NULL SET @CurrentCommand03 += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) - SET @CurrentCommand03 += '''' - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ', @read_write_filegroups = 1' - IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 += ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) - IF @AdaptiveCompression IS NOT NULL SET @CurrentCommand03 += ', @adaptivecompression = ''' + CASE WHEN @AdaptiveCompression = 'SIZE' THEN 'Size' WHEN @AdaptiveCompression = 'SPEED' THEN 'Speed' END + '''' - IF @BufferCount IS NOT NULL SET @CurrentCommand03 += ', @buffercount = ' + CAST(@BufferCount AS nvarchar) - IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 += ', @maxtransfersize = ' + CAST(@CurrentMaxTransferSize AS nvarchar) - IF @Threads IS NOT NULL SET @CurrentCommand03 += ', @threads = ' + CAST(@Threads AS nvarchar) - IF @Init = 'Y' SET @CurrentCommand03 += ', @init = 1' - IF @Format = 'Y' SET @CurrentCommand03 += ', @format = 1' - IF @Throttle IS NOT NULL SET @CurrentCommand03 += ', @throttle = ' + CAST(@Throttle AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' - IF @ObjectLevelRecoveryMap = 'Y' SET @CurrentCommand03 += ', @olrmap = 1' - - IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 += ', @cryptlevel = ' + CASE + SET @CurrentCommand += ', @with = ''' + IF @CheckSum = 'Y' SET @CurrentCommand += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' + IF @CurrentBackupType = 'DIFF' SET @CurrentCommand += ', DIFFERENTIAL' + IF @CopyOnly = 'Y' SET @CurrentCommand += ', COPY_ONLY' + IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand += ', NORECOVERY' + IF @BlockSize IS NOT NULL SET @CurrentCommand += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) + SET @CurrentCommand += '''' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand += ', @read_write_filegroups = 1' + IF @CompressionLevel IS NOT NULL SET @CurrentCommand += ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) + IF @AdaptiveCompression IS NOT NULL SET @CurrentCommand += ', @adaptivecompression = ''' + CASE WHEN @AdaptiveCompression = 'SIZE' THEN 'Size' WHEN @AdaptiveCompression = 'SPEED' THEN 'Speed' END + '''' + IF @BufferCount IS NOT NULL SET @CurrentCommand += ', @buffercount = ' + CAST(@BufferCount AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand += ', @maxtransfersize = ' + CAST(@CurrentMaxTransferSize AS nvarchar) + IF @Threads IS NOT NULL SET @CurrentCommand += ', @threads = ' + CAST(@Threads AS nvarchar) + IF @Init = 'Y' SET @CurrentCommand += ', @init = 1' + IF @Format = 'Y' SET @CurrentCommand += ', @format = 1' + IF @Throttle IS NOT NULL SET @CurrentCommand += ', @throttle = ' + CAST(@Throttle AS nvarchar) + IF @Description IS NOT NULL SET @CurrentCommand += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' + IF @ObjectLevelRecoveryMap = 'Y' SET @CurrentCommand += ', @olrmap = 1' + + IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand += ', @cryptlevel = ' + CASE WHEN @EncryptionAlgorithm = 'RC2_40' THEN '0' WHEN @EncryptionAlgorithm = 'RC2_56' THEN '1' WHEN @EncryptionAlgorithm = 'RC2_112' THEN '2' @@ -2836,141 +2840,148 @@ BEGIN WHEN @EncryptionAlgorithm = 'AES_256' THEN '8' END - IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand03 += ' IF @ReturnCode <> 0 RAISERROR(''Error performing LiteSpeed backup.'', 16, 1)' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error performing LiteSpeed backup.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN - SET @CurrentCommandType03 = 'sqlbackup' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'sqlbackup' - SELECT @CurrentCommand03 = CASE + SELECT @CurrentCommand = CASE WHEN @CurrentBackupType IN('DIFF','FULL') THEN 'BACKUP DATABASE ' + QUOTENAME(@CurrentDatabaseName) WHEN @CurrentBackupType = 'LOG' THEN 'BACKUP LOG ' + QUOTENAME(@CurrentDatabaseName) END - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ' READ_WRITE_FILEGROUPS' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand += ' READ_WRITE_FILEGROUPS' - SET @CurrentCommand03 += ' TO' + SET @CurrentCommand += ' TO' - SELECT @CurrentCommand03 += ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand += ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC - SET @CurrentCommand03 += ' WITH ' + SET @CurrentCommand += ' WITH ' IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SET @CurrentCommand03 += ' MIRRORFILE' + ' = N''' + REPLACE((SELECT FilePath FROM @CurrentFiles WHERE Mirror = 1),'''','''''') + ''', ' + SET @CurrentCommand += ' MIRRORFILE' + ' = N''' + REPLACE((SELECT FilePath FROM @CurrentFiles WHERE Mirror = 1),'''','''''') + ''', ' END - IF @CheckSum = 'Y' SET @CurrentCommand03 += 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand03 += 'NO_CHECKSUM' - IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 += ', DIFFERENTIAL' - IF @CopyOnly = 'Y' SET @CurrentCommand03 += ', COPY_ONLY' - IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 += ', NORECOVERY' - IF @Init = 'Y' SET @CurrentCommand03 += ', INIT' - IF @Format = 'Y' SET @CurrentCommand03 += ', FORMAT' - IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 += ', COMPRESSION = ' + CAST(@CompressionLevel AS nvarchar) - IF @Threads IS NOT NULL SET @CurrentCommand03 += ', THREADCOUNT = ' + CAST(@Threads AS nvarchar) - IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' - - IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 += ', KEYSIZE = ' + CASE + IF @CheckSum = 'Y' SET @CurrentCommand += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' + IF @CurrentBackupType = 'DIFF' SET @CurrentCommand += ', DIFFERENTIAL' + IF @CopyOnly = 'Y' SET @CurrentCommand += ', COPY_ONLY' + IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand += ', NORECOVERY' + IF @Init = 'Y' SET @CurrentCommand += ', INIT' + IF @Format = 'Y' SET @CurrentCommand += ', FORMAT' + IF @CompressionLevel IS NOT NULL SET @CurrentCommand += ', COMPRESSION = ' + CAST(@CompressionLevel AS nvarchar) + IF @Threads IS NOT NULL SET @CurrentCommand += ', THREADCOUNT = ' + CAST(@Threads AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) + IF @Description IS NOT NULL SET @CurrentCommand += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' + + IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand += ', KEYSIZE = ' + CASE WHEN @EncryptionAlgorithm = 'AES_128' THEN '128' WHEN @EncryptionAlgorithm = 'AES_256' THEN '256' END - IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 += ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand03,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLBackup backup.'', 16, 1)' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLBackup backup.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN - SET @CurrentCommandType03 = 'xp_ss_backup' + SET @CurrentDatabaseContext = 'master' - SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_backup @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' + SET @CurrentCommandType = 'xp_ss_backup' - SELECT @CurrentCommand03 += ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_backup @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' + + SELECT @CurrentCommand += ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC - SELECT @CurrentCommand03 += ', @mirrorfile = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand += ', @mirrorfile = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 1 ORDER BY FilePath ASC - SET @CurrentCommand03 += ', @backuptype = ' + CASE WHEN @CurrentBackupType = 'FULL' THEN '''Full''' WHEN @CurrentBackupType = 'DIFF' THEN '''Differential''' WHEN @CurrentBackupType = 'LOG' THEN '''Log''' END - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ', @readwritefilegroups = 1' - SET @CurrentCommand03 += ', @checksum = ' + CASE WHEN @CheckSum = 'Y' THEN '1' WHEN @CheckSum = 'N' THEN '0' END - SET @CurrentCommand03 += ', @copyonly = ' + CASE WHEN @CopyOnly = 'Y' THEN '1' WHEN @CopyOnly = 'N' THEN '0' END - IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 += ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) - IF @Threads IS NOT NULL SET @CurrentCommand03 += ', @threads = ' + CAST(@Threads AS nvarchar) - IF @Init = 'Y' SET @CurrentCommand03 += ', @overwrite = 1' - IF @Description IS NOT NULL SET @CurrentCommand03 += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' + SET @CurrentCommand += ', @backuptype = ' + CASE WHEN @CurrentBackupType = 'FULL' THEN '''Full''' WHEN @CurrentBackupType = 'DIFF' THEN '''Differential''' WHEN @CurrentBackupType = 'LOG' THEN '''Log''' END + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand += ', @readwritefilegroups = 1' + SET @CurrentCommand += ', @checksum = ' + CASE WHEN @CheckSum = 'Y' THEN '1' WHEN @CheckSum = 'N' THEN '0' END + SET @CurrentCommand += ', @copyonly = ' + CASE WHEN @CopyOnly = 'Y' THEN '1' WHEN @CopyOnly = 'N' THEN '0' END + IF @CompressionLevel IS NOT NULL SET @CurrentCommand += ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) + IF @Threads IS NOT NULL SET @CurrentCommand += ', @threads = ' + CAST(@Threads AS nvarchar) + IF @Init = 'Y' SET @CurrentCommand += ', @overwrite = 1' + IF @Description IS NOT NULL SET @CurrentCommand += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' - IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 += ', @encryptiontype = N''' + CASE + IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand += ', @encryptiontype = N''' + CASE WHEN @EncryptionAlgorithm = 'AES_128' THEN 'AES128' WHEN @EncryptionAlgorithm = 'AES_256' THEN 'AES256' END + '''' - IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 += ', @encryptedbackuppassword = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand03 += ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptedbackuppassword = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN - SET @CurrentCommandType03 = 'emc_run_backup' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'emc_run_backup' - SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.emc_run_backup ''' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.emc_run_backup ''' - SET @CurrentCommand03 += ' -c ' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar) END + SET @CurrentCommand += ' -c ' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar) END - SET @CurrentCommand03 += ' -l ' + CASE + SET @CurrentCommand += ' -l ' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'full' WHEN @CurrentBackupType = 'DIFF' THEN 'diff' WHEN @CurrentBackupType = 'LOG' THEN 'incr' END - IF @NoRecovery = 'Y' SET @CurrentCommand03 += ' -H' + IF @NoRecovery = 'Y' SET @CurrentCommand += ' -H' - IF @CleanupTime IS NOT NULL SET @CurrentCommand03 += ' -y +' + CAST(@CleanupTime/24 + CASE WHEN @CleanupTime%24 > 0 THEN 1 ELSE 0 END AS nvarchar) + 'd' + IF @CleanupTime IS NOT NULL SET @CurrentCommand += ' -y +' + CAST(@CleanupTime/24 + CASE WHEN @CleanupTime%24 > 0 THEN 1 ELSE 0 END AS nvarchar) + 'd' - IF @CheckSum = 'Y' SET @CurrentCommand03 += ' -k' + IF @CheckSum = 'Y' SET @CurrentCommand += ' -k' - SET @CurrentCommand03 += ' -S ' + CAST(@CurrentNumberOfFiles AS nvarchar) + SET @CurrentCommand += ' -S ' + CAST(@CurrentNumberOfFiles AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 += ' -b "' + REPLACE(@Description,'''','''''') + '"' + IF @Description IS NOT NULL SET @CurrentCommand += ' -b "' + REPLACE(@Description,'''','''''') + '"' - IF @BufferCount IS NOT NULL SET @CurrentCommand03 += ' -O "BUFFERCOUNT=' + CAST(@BufferCount AS nvarchar) + '"' + IF @BufferCount IS NOT NULL SET @CurrentCommand += ' -O "BUFFERCOUNT=' + CAST(@BufferCount AS nvarchar) + '"' - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ' -O "READ_WRITE_FILEGROUPS"' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand += ' -O "READ_WRITE_FILEGROUPS"' - IF @DataDomainBoostHost IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DD_HOST=' + REPLACE(@DataDomainBoostHost,'''','''''') + '"' - IF @DataDomainBoostUser IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DD_USER=' + REPLACE(@DataDomainBoostUser,'''','''''') + '"' - IF @DataDomainBoostDevicePath IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DEVICE_PATH=' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '"' - IF @DataDomainBoostLockboxPath IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DD_LOCKBOX_PATH=' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '"' - SET @CurrentCommand03 += ' -a "NSR_SKIP_NON_BACKUPABLE_STATE_DB=TRUE"' - IF @CopyOnly = 'Y' SET @CurrentCommand03 += ' -a "NSR_COPY_ONLY=TRUE"' + IF @DataDomainBoostHost IS NOT NULL SET @CurrentCommand += ' -a "NSR_DFA_SI_DD_HOST=' + REPLACE(@DataDomainBoostHost,'''','''''') + '"' + IF @DataDomainBoostUser IS NOT NULL SET @CurrentCommand += ' -a "NSR_DFA_SI_DD_USER=' + REPLACE(@DataDomainBoostUser,'''','''''') + '"' + IF @DataDomainBoostDevicePath IS NOT NULL SET @CurrentCommand += ' -a "NSR_DFA_SI_DEVICE_PATH=' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '"' + IF @DataDomainBoostLockboxPath IS NOT NULL SET @CurrentCommand += ' -a "NSR_DFA_SI_DD_LOCKBOX_PATH=' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '"' + SET @CurrentCommand += ' -a "NSR_SKIP_NON_BACKUPABLE_STATE_DB=TRUE"' + IF @CopyOnly = 'Y' SET @CurrentCommand += ' -a "NSR_COPY_ONLY=TRUE"' - IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand03 += ' "MSSQL' + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' - IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand03 += ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar) + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' + IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand += ' "MSSQL' + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' + IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand += ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar) + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' - SET @CurrentCommand03 += '''' + SET @CurrentCommand += '''' - SET @CurrentCommand03 += ' IF @ReturnCode <> 0 RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' END - EXECUTE @CurrentCommandOutput03 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand03, @CommandType = @CurrentCommandType03, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput03 = @Error - IF @CurrentCommandOutput03 <> 0 SET @ReturnCode = @CurrentCommandOutput03 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput + SET @CurrentBackupOutput = @CurrentCommandOutput END -- Verify the backup - IF @CurrentCommandOutput03 = 0 AND @Verify = 'Y' + IF @CurrentBackupOutput = 0 AND @Verify = 'Y' BEGIN WHILE (1 = 1) BEGIN @@ -2987,92 +2998,99 @@ BEGIN IF @BackupSoftware IS NULL BEGIN - SET @CurrentCommandType04 = 'RESTORE_VERIFYONLY' + SET @CurrentDatabaseContext = 'master' - SET @CurrentCommand04 = 'RESTORE VERIFYONLY FROM' + SET @CurrentCommandType = 'RESTORE_VERIFYONLY' - SELECT @CurrentCommand04 += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SET @CurrentCommand = 'RESTORE VERIFYONLY FROM' + + SELECT @CurrentCommand += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 += ' WITH ' - IF @CheckSum = 'Y' SET @CurrentCommand04 += 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand04 += 'NO_CHECKSUM' - IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand04 += ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' + SET @CurrentCommand += ' WITH ' + IF @CheckSum = 'Y' SET @CurrentCommand += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' + IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand += ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' END IF @BackupSoftware = 'LITESPEED' BEGIN - SET @CurrentCommandType04 = 'xp_restore_verifyonly' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'xp_restore_verifyonly' - SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_restore_verifyonly' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_restore_verifyonly' - SELECT @CurrentCommand04 += ' @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand += ' @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 += ', @with = ''' - IF @CheckSum = 'Y' SET @CurrentCommand04 += 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand04 += 'NO_CHECKSUM' - SET @CurrentCommand04 += '''' - IF @EncryptionKey IS NOT NULL SET @CurrentCommand04 += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand += ', @with = ''' + IF @CheckSum = 'Y' SET @CurrentCommand += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' + SET @CurrentCommand += '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand04 += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying LiteSpeed backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying LiteSpeed backup.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN - SET @CurrentCommandType04 = 'sqlbackup' + SET @CurrentDatabaseContext = 'master' - SET @CurrentCommand04 = 'RESTORE VERIFYONLY FROM' + SET @CurrentCommandType = 'sqlbackup' - SELECT @CurrentCommand04 += ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SET @CurrentCommand = 'RESTORE VERIFYONLY FROM' + + SELECT @CurrentCommand += ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 += ' WITH ' - IF @CheckSum = 'Y' SET @CurrentCommand04 += 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand04 += 'NO_CHECKSUM' - IF @EncryptionKey IS NOT NULL SET @CurrentCommand04 += ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand += ' WITH ' + IF @CheckSum = 'Y' SET @CurrentCommand += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand04,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLBackup backup.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLBackup backup.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN - SET @CurrentCommandType04 = 'xp_ss_verify' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'xp_ss_verify' - SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_verify @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_verify @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' - SELECT @CurrentCommand04 += ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand += ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' END - EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput04 = @Error - IF @CurrentCommandOutput04 <> 0 SET @ReturnCode = @CurrentCommandOutput04 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput UPDATE @CurrentBackupSet SET VerifyCompleted = 1, - VerifyOutput = @CurrentCommandOutput04 + VerifyOutput = @CurrentCommandOutput WHERE ID = @CurrentBackupSetID SET @CurrentBackupSetID = NULL SET @CurrentIsMirror = NULL - SET @CurrentCommand04 = NULL - - SET @CurrentCommandOutput04 = NULL - - SET @CurrentCommandType04 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL END END @@ -3109,8 +3127,8 @@ BEGIN END -- Delete old backup files, after backup - IF ((@CurrentCommandOutput03 = 0 AND @Verify = 'N') - OR (@CurrentCommandOutput03 = 0 AND @Verify = 'Y' AND NOT EXISTS (SELECT * FROM @CurrentBackupSet WHERE VerifyOutput <> 0 OR VerifyOutput IS NULL))) + IF ((@CurrentBackupOutput = 0 AND @Verify = 'N') + OR (@CurrentBackupOutput = 0 AND @Verify = 'Y' AND NOT EXISTS (SELECT * FROM @CurrentBackupSet WHERE VerifyOutput <> 0 OR VerifyOutput IS NULL))) AND @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) AND @CurrentBackupType = @BackupType @@ -3133,51 +3151,58 @@ BEGIN IF @BackupSoftware IS NULL BEGIN - SET @CurrentCommandType05 = 'xp_delete_file' + SET @CurrentDatabaseContext = 'master' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' + SET @CurrentCommandType = 'xp_delete_file' + + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' BEGIN - SET @CurrentCommandType05 = 'xp_slssqlmaint' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'xp_slssqlmaint' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN - SET @CurrentCommandType05 = 'sqbutility' + SET @CurrentDatabaseContext = 'master' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' + SET @CurrentCommandType = 'sqbutility' + + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN - SET @CurrentCommandType05 = 'xp_ss_delete' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'xp_ss_delete' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END - EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput05 = @Error - IF @CurrentCommandOutput05 <> 0 SET @ReturnCode = @CurrentCommandOutput05 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput UPDATE @CurrentDirectories SET CleanupCompleted = 1, - CleanupOutput = @CurrentCommandOutput05 + CleanupOutput = @CurrentCommandOutput WHERE ID = @CurrentDirectoryID SET @CurrentDirectoryID = NULL SET @CurrentDirectoryPath = NULL SET @CurrentCleanupDate = NULL - SET @CurrentCommand05 = NULL - - SET @CurrentCommandOutput05 = NULL - - SET @CurrentCommandType05 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL END END END @@ -3248,12 +3273,12 @@ BEGIN SET @CurrentAllocatedExtentPageCount = NULL SET @CurrentModifiedExtentPageCount = NULL - SET @CurrentCommand03 = NULL - SET @CurrentCommand07 = NULL - - SET @CurrentCommandOutput03 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL - SET @CurrentCommandType03 = NULL + SET @CurrentBackupOutput = NULL DELETE FROM @CurrentDirectories DELETE FROM @CurrentURLs diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 430a6c01..bd4d3329 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -38,7 +38,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-09 23:10:28 //-- + --// Version: 2020-01-11 12:40:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -91,32 +91,17 @@ BEGIN DECLARE @CurrentObjectType nvarchar(max) DECLARE @CurrentObjectExists bit - DECLARE @CurrentCommand01 nvarchar(max) - DECLARE @CurrentCommand02 nvarchar(max) - DECLARE @CurrentCommand03 nvarchar(max) - DECLARE @CurrentCommand04 nvarchar(max) - DECLARE @CurrentCommand05 nvarchar(max) - DECLARE @CurrentCommand06 nvarchar(max) - DECLARE @CurrentCommand07 nvarchar(max) - DECLARE @CurrentCommand08 nvarchar(max) - DECLARE @CurrentCommand09 nvarchar(max) - - DECLARE @CurrentCommandOutput01 int - DECLARE @CurrentCommandOutput04 int - DECLARE @CurrentCommandOutput05 int - DECLARE @CurrentCommandOutput08 int - DECLARE @CurrentCommandOutput09 int - - DECLARE @CurrentCommandType01 nvarchar(max) - DECLARE @CurrentCommandType04 nvarchar(max) - DECLARE @CurrentCommandType05 nvarchar(max) - DECLARE @CurrentCommandType08 nvarchar(max) - DECLARE @CurrentCommandType09 nvarchar(max) + DECLARE @CurrentDatabaseContext nvarchar(max) + DECLARE @CurrentCommand nvarchar(max) + DECLARE @CurrentCommandOutput int + DECLARE @CurrentCommandType nvarchar(max) DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, - [Message] nvarchar(max)) + [Message] nvarchar(max) NOT NULL, + Severity int NOT NULL) DECLARE @CurrentMessage nvarchar(max) + DECLARE @CurrentSeverity int DECLARE @tmpDatabases TABLE (ID int IDENTITY, DatabaseName nvarchar(max), @@ -263,56 +248,56 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16 END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16 END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16 END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 END 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') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16 END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16 END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16 END IF @@TRANCOUNT <> 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The transaction count is not 0.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The transaction count is not 0.', 16 END ---------------------------------------------------------------------------------------------------- @@ -439,8 +424,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Databases is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Databases is not supported.', 16 END ---------------------------------------------------------------------------------------------------- @@ -534,20 +519,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16 END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16 END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16 END ---------------------------------------------------------------------------------------------------- @@ -685,116 +670,116 @@ BEGIN IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) OR EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) OR NOT EXISTS (SELECT * FROM @SelectedCheckCommands) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG'))) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE'))) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CheckCommands is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CheckCommands is not supported.', 16 END IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @PhysicalOnly is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @PhysicalOnly is not supported.', 16 END IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @NoIndex is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @NoIndex is not supported.', 16 END IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL OR (@ExtendedLogicalChecks = 'Y' AND NOT @Version >= 10) OR (@PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @ExtendedLogicalChecks is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @ExtendedLogicalChecks is not supported.', 16 END IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @TabLock is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @TabLock is not supported.', 16 END IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) OR (@FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups)) OR (@FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP')) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FileGroups is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FileGroups is not supported.', 16 END IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) OR (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) OR (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Objects is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Objects is not supported.', 16 END IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MaxDOP is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MaxDOP is not supported.', 16 END IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @AvailabilityGroupReplicas is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @AvailabilityGroupReplicas is not supported.', 16 END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Updateability is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Updateability is not supported.', 16 END IF @TimeLimit < 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @TimeLimit is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @TimeLimit is not supported.', 16 END IF @LockTimeout < 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LockTimeout is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LockTimeout is not supported.', 16 END IF @LockMessageSeverity NOT IN(10,16) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16 END IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @StringDelimiter is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LogToTable is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LogToTable is not supported.', 16 END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Execute is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Execute is not supported.', 16 END IF EXISTS(SELECT * FROM @Errors) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.', 16 END ---------------------------------------------------------------------------------------------------- @@ -808,8 +793,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -819,8 +804,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -830,8 +815,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -841,8 +826,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -853,8 +838,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -865,8 +850,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END ---------------------------------------------------------------------------------------------------- @@ -875,33 +860,33 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16 END ---------------------------------------------------------------------------------------------------- --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor - FETCH ErrorCursor INTO @CurrentMessage + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity WHILE @@FETCH_STATUS = 0 BEGIN - RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR('%s', @CurrentSeverity, 1, @CurrentMessage) WITH NOWAIT RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT - FETCH NEXT FROM ErrorCursor INTO @CurrentMessage + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity END CLOSE ErrorCursor DEALLOCATE ErrorCursor - IF EXISTS (SELECT * FROM @Errors) + IF EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) BEGIN SET @ReturnCode = 50000 GOTO Logging @@ -1299,32 +1284,34 @@ BEGIN -- Check database IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKDB') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommandType01 = 'DBCC_CHECKDB' - - SET @CurrentCommand01 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand01 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand01 += 'DBCC CHECKDB (' + QUOTENAME(@CurrentDatabaseName) - IF @NoIndex = 'Y' SET @CurrentCommand01 += ', NOINDEX' - SET @CurrentCommand01 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'N' SET @CurrentCommand01 += ', DATA_PURITY' - IF @PhysicalOnly = 'Y' SET @CurrentCommand01 += ', PHYSICAL_ONLY' - IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand01 += ', EXTENDED_LOGICAL_CHECKS' - IF @TabLock = 'Y' SET @CurrentCommand01 += ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand01 += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) - - EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + SET @CurrentDatabaseContext = CASE WHEN SERVERPROPERTY('EngineEdition') = 5 THEN @CurrentDatabaseName ELSE 'master' END + + SET @CurrentCommandType = 'DBCC_CHECKDB' + + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'DBCC CHECKDB (' + QUOTENAME(@CurrentDatabaseName) + IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' + SET @CurrentCommand += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @PhysicalOnly = 'N' SET @CurrentCommand += ', DATA_PURITY' + IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' + IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand += ', EXTENDED_LOGICAL_CHECKS' + IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput01 = @Error - IF @CurrentCommandOutput01 <> 0 SET @ReturnCode = @CurrentCommandOutput01 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput END -- Check filegroups IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommand02 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' INSERT INTO @tmpFileGroups (FileGroupID, FileGroupName, [Order], Selected, Completed) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand02 + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -1400,12 +1387,12 @@ BEGIN END -- Does the filegroup exist? - SET @CurrentCommand03 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand03 += 'IF EXISTS(SELECT * FROM sys.filegroups filegroups WHERE [type] <> ''FX'' AND filegroups.data_space_id = @ParamFileGroupID AND filegroups.[name] = @ParamFileGroupName) BEGIN SET @ParamFileGroupExists = 1 END' + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'IF EXISTS(SELECT * FROM sys.filegroups filegroups WHERE [type] <> ''FX'' AND filegroups.data_space_id = @ParamFileGroupID AND filegroups.[name] = @ParamFileGroupName) BEGIN SET @ParamFileGroupExists = 1 END' BEGIN TRY - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand03, @params = N'@ParamFileGroupID int, @ParamFileGroupName sysname, @ParamFileGroupExists bit OUTPUT', @ParamFileGroupID = @CurrentFileGroupID, @ParamFileGroupName = @CurrentFileGroupName, @ParamFileGroupExists = @CurrentFileGroupExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamFileGroupID int, @ParamFileGroupName sysname, @ParamFileGroupExists bit OUTPUT', @ParamFileGroupID = @CurrentFileGroupID, @ParamFileGroupName = @CurrentFileGroupName, @ParamFileGroupExists = @CurrentFileGroupExists OUTPUT IF @CurrentFileGroupExists IS NULL SET @CurrentFileGroupExists = 0 END TRY @@ -1423,21 +1410,23 @@ BEGIN IF @CurrentFileGroupExists = 1 BEGIN - SET @CurrentCommandType04 = 'DBCC_CHECKFILEGROUP' - - SET @CurrentCommand04 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand04 += 'DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) - IF @NoIndex = 'Y' SET @CurrentCommand04 += ', NOINDEX' - SET @CurrentCommand04 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'Y' SET @CurrentCommand04 += ', PHYSICAL_ONLY' - IF @TabLock = 'Y' SET @CurrentCommand04 += ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand04 += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) - - EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + SET @CurrentDatabaseContext = @CurrentDatabaseName + + SET @CurrentCommandType = 'DBCC_CHECKFILEGROUP' + + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) + IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' + SET @CurrentCommand += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' + IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput04 = @Error - IF @CurrentCommandOutput04 <> 0 SET @ReturnCode = @CurrentCommandOutput04 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput END UPDATE @tmpFileGroups @@ -1451,39 +1440,39 @@ BEGIN SET @CurrentFileGroupName = NULL SET @CurrentFileGroupExists = NULL - SET @CurrentCommand03 = NULL - SET @CurrentCommand04 = NULL - - SET @CurrentCommandOutput04 = NULL - - SET @CurrentCommandType04 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL END END -- Check disk space allocation structures IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKALLOC') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommandType05 = 'DBCC_CHECKALLOC' + SET @CurrentDatabaseContext = CASE WHEN SERVERPROPERTY('EngineEdition') = 5 THEN @CurrentDatabaseName ELSE 'master' END + + SET @CurrentCommandType = 'DBCC_CHECKALLOC' - SET @CurrentCommand05 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand05 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand05 += 'DBCC CHECKALLOC (' + QUOTENAME(@CurrentDatabaseName) - SET @CurrentCommand05 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @TabLock = 'Y' SET @CurrentCommand05 += ', TABLOCK' + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'DBCC CHECKALLOC (' + QUOTENAME(@CurrentDatabaseName) + SET @CurrentCommand += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' - EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput05 = @Error - IF @CurrentCommandOutput05 <> 0 SET @ReturnCode = @CurrentCommandOutput05 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput END -- Check objects IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommand06 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, [Order], Selected, Completed) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand06 + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -1563,12 +1552,12 @@ BEGIN END -- Does the object exist? - SET @CurrentCommand07 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand07 += 'IF EXISTS(SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType) BEGIN SET @ParamObjectExists = 1 END' + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'IF EXISTS(SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType) BEGIN SET @ParamObjectExists = 1 END' BEGIN TRY - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand07, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamObjectExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamObjectExists = @CurrentObjectExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamObjectExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamObjectExists = @CurrentObjectExists OUTPUT IF @CurrentObjectExists IS NULL SET @CurrentObjectExists = 0 END TRY @@ -1586,23 +1575,25 @@ BEGIN IF @CurrentObjectExists = 1 BEGIN - SET @CurrentCommandType08 = 'DBCC_CHECKTABLE' - - SET @CurrentCommand08 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand08 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand08 += 'DBCC CHECKTABLE (''' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + '''' - IF @NoIndex = 'Y' SET @CurrentCommand08 += ', NOINDEX' - SET @CurrentCommand08 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'N' SET @CurrentCommand08 += ', DATA_PURITY' - IF @PhysicalOnly = 'Y' SET @CurrentCommand08 += ', PHYSICAL_ONLY' - IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand08 += ', EXTENDED_LOGICAL_CHECKS' - IF @TabLock = 'Y' SET @CurrentCommand08 += ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand08 += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) - - EXECUTE @CurrentCommandOutput08 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand08, @CommandType = @CurrentCommandType08, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @LogToTable = @LogToTable, @Execute = @Execute + SET @CurrentDatabaseContext = @CurrentDatabaseName + + SET @CurrentCommandType = 'DBCC_CHECKTABLE' + + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'DBCC CHECKTABLE (''' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + '''' + IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' + SET @CurrentCommand += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @PhysicalOnly = 'N' SET @CurrentCommand += ', DATA_PURITY' + IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' + IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand += ', EXTENDED_LOGICAL_CHECKS' + IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput08 = @Error - IF @CurrentCommandOutput08 <> 0 SET @ReturnCode = @CurrentCommandOutput08 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput END UPDATE @tmpObjects @@ -1619,29 +1610,29 @@ BEGIN SET @CurrentObjectType = NULL SET @CurrentObjectExists = NULL - SET @CurrentCommand07 = NULL - SET @CurrentCommand08 = NULL - - SET @CurrentCommandOutput08 = NULL - - SET @CurrentCommandType08 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL END END -- Check catalog IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommandType09 = 'DBCC_CHECKCATALOG' + SET @CurrentDatabaseContext = CASE WHEN SERVERPROPERTY('EngineEdition') = 5 THEN @CurrentDatabaseName ELSE 'master' END + + SET @CurrentCommandType = 'DBCC_CHECKCATALOG' - SET @CurrentCommand09 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand09 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand09 += 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) - SET @CurrentCommand09 += ') WITH NO_INFOMSGS' + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) + SET @CurrentCommand += ') WITH NO_INFOMSGS' - EXECUTE @CurrentCommandOutput09 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand09, @CommandType = @CurrentCommandType09, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput09 = @Error - IF @CurrentCommandOutput09 <> 0 SET @ReturnCode = @CurrentCommandOutput09 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput END END @@ -1690,19 +1681,10 @@ BEGIN SET @CurrentIsPreferredBackupReplica = NULL SET @CurrentDatabaseMirroringRole = NULL - SET @CurrentCommand01 = NULL - SET @CurrentCommand02 = NULL - SET @CurrentCommand05 = NULL - SET @CurrentCommand06 = NULL - SET @CurrentCommand09 = NULL - - SET @CurrentCommandOutput01 = NULL - SET @CurrentCommandOutput05 = NULL - SET @CurrentCommandOutput09 = NULL - - SET @CurrentCommandType01 = NULL - SET @CurrentCommandType05 = NULL - SET @CurrentCommandType09 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL DELETE FROM @tmpFileGroups DELETE FROM @tmpObjects diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 9fbb454a..021ac85b 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-09 23:10:28 //-- + --// Version: 2020-01-11 12:40:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -96,30 +96,19 @@ BEGIN DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentDatabaseMirroringRole nvarchar(max) - DECLARE @CurrentCommand01 nvarchar(max) - DECLARE @CurrentCommand02 nvarchar(max) - DECLARE @CurrentCommand03 nvarchar(max) - DECLARE @CurrentCommand04 nvarchar(max) - DECLARE @CurrentCommand05 nvarchar(max) - DECLARE @CurrentCommand06 nvarchar(max) - DECLARE @CurrentCommand07 nvarchar(max) - - DECLARE @CurrentCommandOutput06 int - DECLARE @CurrentCommandOutput07 int - - DECLARE @CurrentCommandType06 nvarchar(max) - DECLARE @CurrentCommandType07 nvarchar(max) - - DECLARE @CurrentComment06 nvarchar(max) - DECLARE @CurrentComment07 nvarchar(max) - - DECLARE @CurrentExtendedInfo06 xml - DECLARE @CurrentExtendedInfo07 xml + DECLARE @CurrentDatabaseContext nvarchar(max) + DECLARE @CurrentCommand nvarchar(max) + DECLARE @CurrentCommandOutput int + DECLARE @CurrentCommandType nvarchar(max) + DECLARE @CurrentComment nvarchar(max) + DECLARE @CurrentExtendedInfo xml DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, - [Message] nvarchar(max)) + [Message] nvarchar(max) NOT NULL, + Severity int NOT NULL) DECLARE @CurrentMessage nvarchar(max) + DECLARE @CurrentSeverity int DECLARE @CurrentIxID int DECLARE @CurrentIxOrder int @@ -352,56 +341,56 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16 END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16 END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16 END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 END 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') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16 END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16 END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16 END IF @@TRANCOUNT <> 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The transaction count is not 0.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The transaction count is not 0.', 16 END ---------------------------------------------------------------------------------------------------- @@ -527,8 +516,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Databases is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Databases is not supported.', 16 END ---------------------------------------------------------------------------------------------------- @@ -622,20 +611,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16 END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16 END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16 END ---------------------------------------------------------------------------------------------------- @@ -769,214 +758,214 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FragmentationLow is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FragmentationLow is not supported.', 16 END IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FragmentationMedium is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FragmentationMedium is not supported.', 16 END IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'High' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FragmentationHigh is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FragmentationHigh is not supported.', 16 END IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 >= @FragmentationLevel2 OR @FragmentationLevel1 IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FragmentationLevel1 is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FragmentationLevel1 is not supported.', 16 END IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 <= @FragmentationLevel1 OR @FragmentationLevel2 IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FragmentationLevel2 is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FragmentationLevel2 is not supported.', 16 END IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MinNumberOfPages is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MinNumberOfPages is not supported.', 16 END IF @MaxNumberOfPages < 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MaxNumberOfPages is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MaxNumberOfPages is not supported.', 16 END IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @SortInTempdb is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @SortInTempdb is not supported.', 16 END IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MaxDOP is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MaxDOP is not supported.', 16 END IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FillFactor is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FillFactor is not supported.', 16 END IF @PadIndex NOT IN('Y','N') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @PadIndex is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @PadIndex is not supported.', 16 END IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LOBCompaction is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LOBCompaction is not supported.', 16 END IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @UpdateStatistics is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @UpdateStatistics is not supported.', 16 END IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @OnlyModifiedStatistics is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @OnlyModifiedStatistics is not supported.', 16 END IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @StatisticsModificationLevel is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @StatisticsModificationLevel is not supported.', 16 END IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.', 16 END IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @StatisticsSample is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @StatisticsSample is not supported.', 16 END IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL OR (@StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @StatisticsResample is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @StatisticsResample is not supported.', 16 END IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @PartitionLevel is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @PartitionLevel is not supported.', 16 END IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MSShippedObjects is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MSShippedObjects is not supported.', 16 END IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) OR (@Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Indexes is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Indexes is not supported.', 16 END IF @TimeLimit < 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @TimeLimit is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @TimeLimit is not supported.', 16 END IF @Delay < 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Delay is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Delay is not supported.', 16 END IF @WaitAtLowPriorityMaxDuration < 0 OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @WaitAtLowPriorityAbortAfterWait IS NULL) OR (@WaitAtLowPriorityMaxDuration IS NULL AND @WaitAtLowPriorityAbortAfterWait IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16 END IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16 END IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL OR (@Resumable = 'Y' AND NOT (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8))) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Resumable is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Resumable is not supported.', 16 END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.', 16 END IF @LockTimeout < 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LockTimeout is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LockTimeout is not supported.', 16 END IF @LockMessageSeverity NOT IN(10,16) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16 END IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @StringDelimiter is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LogToTable is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LogToTable is not supported.', 16 END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Execute is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Execute is not supported.', 16 END IF EXISTS(SELECT * FROM @Errors) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16 END ---------------------------------------------------------------------------------------------------- @@ -990,8 +979,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -1001,8 +990,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -1012,8 +1001,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -1024,33 +1013,33 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END ---------------------------------------------------------------------------------------------------- --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor - FETCH ErrorCursor INTO @CurrentMessage + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity WHILE @@FETCH_STATUS = 0 BEGIN - RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR('%s', @CurrentSeverity, 1, @CurrentMessage) WITH NOWAIT RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT - FETCH NEXT FROM ErrorCursor INTO @CurrentMessage + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity END CLOSE ErrorCursor DEALLOCATE ErrorCursor - IF EXISTS (SELECT * FROM @Errors) + IF EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) BEGIN SET @ReturnCode = 50000 GOTO Logging @@ -1372,13 +1361,13 @@ BEGIN -- Select indexes in the current database IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, IsComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + ' FROM (' IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') BEGIN - SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID' + SET @CurrentCommand = @CurrentCommand + 'SELECT schemas.[schema_id] AS SchemaID' + ', schemas.[name] AS SchemaName' + ', objects.[object_id] AS ObjectID' + ', objects.[name] AS ObjectName' @@ -1425,11 +1414,11 @@ BEGIN + ' LEFT OUTER JOIN sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' IF @PartitionLevel = 'Y' BEGIN - SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' + SET @CurrentCommand = @CurrentCommand + ' LEFT OUTER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' + ' LEFT OUTER JOIN (SELECT partitions.[object_id], partitions.index_id, COUNT(DISTINCT partitions.partition_number) AS partition_count FROM sys.partitions partitions GROUP BY partitions.[object_id], partitions.index_id) IndexPartitions ON partitions.[object_id] = IndexPartitions.[object_id] AND partitions.[index_id] = IndexPartitions.[index_id]' END - SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,3,4,5,6,7)' + ' AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0' @@ -1437,12 +1426,12 @@ BEGIN IF (EXISTS(SELECT * FROM @ActionsPreferred) AND @UpdateStatistics = 'COLUMNS') OR @UpdateStatistics = 'ALL' BEGIN - SET @CurrentCommand01 = @CurrentCommand01 + ' UNION ' + SET @CurrentCommand = @CurrentCommand + ' UNION ' END IF @UpdateStatistics IN('ALL','COLUMNS') BEGIN - SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID' + SET @CurrentCommand = @CurrentCommand + 'SELECT schemas.[schema_id] AS SchemaID' + ', schemas.[name] AS SchemaName' + ', objects.[object_id] AS ObjectID' + ', objects.[name] AS ObjectName' @@ -1476,18 +1465,18 @@ BEGIN IF @PartitionLevelStatistics = 1 BEGIN - SET @CurrentCommand01 = @CurrentCommand01 + ' OUTER APPLY sys.dm_db_incremental_stats_properties(stats.object_id, stats.stats_id) dm_db_incremental_stats_properties' + SET @CurrentCommand = @CurrentCommand + ' OUTER APPLY sys.dm_db_incremental_stats_properties(stats.object_id, stats.stats_id) dm_db_incremental_stats_properties' END - SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id)' END - SET @CurrentCommand01 = @CurrentCommand01 + ') IndexesStatistics' + SET @CurrentCommand = @CurrentCommand + ') IndexesStatistics' INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, IsComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand01 + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 BEGIN @@ -1617,15 +1606,15 @@ BEGIN -- Does the index exist? IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) BEGIN - SET @CurrentCommand02 = '' + SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand02 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - IF @CurrentIsPartition = 0 SET @CurrentCommand02 += 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' - IF @CurrentIsPartition = 1 SET @CurrentCommand02 += 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' + IF @CurrentIsPartition = 0 SET @CurrentCommand += 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' + IF @CurrentIsPartition = 1 SET @CurrentCommand += 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' BEGIN TRY - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand02, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT IF @CurrentIndexExists IS NULL BEGIN @@ -1651,14 +1640,14 @@ BEGIN -- Does the statistics exist? IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL BEGIN - SET @CurrentCommand03 = '' + SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand03 += 'IF EXISTS(SELECT * FROM sys.stats stats INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' + SET @CurrentCommand += 'IF EXISTS(SELECT * FROM sys.stats stats INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' BEGIN TRY - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand03, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT IF @CurrentStatisticsExists IS NULL BEGIN @@ -1684,26 +1673,26 @@ BEGIN -- Has the data in the statistics been modified since the statistics was last updated? IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL BEGIN - SET @CurrentCommand04 = '' + SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN - SET @CurrentCommand04 += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' + SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' END ELSE IF (@Version >= 10.504000 AND @Version < 11) OR @Version >= 11.03000 BEGIN - SET @CurrentCommand04 += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' + SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' END ELSE BEGIN - SET @CurrentCommand04 += 'SELECT @ParamRowCount = rowcnt, @ParamModificationCounter = rowmodctr FROM sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID' + SET @CurrentCommand += 'SELECT @ParamRowCount = rowcnt, @ParamModificationCounter = rowmodctr FROM sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID' END BEGIN TRY - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT IF @CurrentRowCount IS NULL SET @CurrentRowCount = 0 IF @CurrentModificationCounter IS NULL SET @CurrentModificationCounter = 0 @@ -1729,14 +1718,14 @@ BEGIN AND EXISTS(SELECT * FROM @ActionsPreferred) AND (EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) OR @MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) BEGIN - SET @CurrentCommand05 = '' + SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand05 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand05 += 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + SET @CurrentCommand += 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' BEGIN TRY - EXECUTE sp_executesql @stmt = @CurrentCommand05, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT END TRY BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The page_count and avg_fragmentation_in_percent could not be checked.' ELSE '' END @@ -1867,57 +1856,59 @@ BEGIN -- Create index comment IF @CurrentIndexID IS NOT NULL BEGIN - SET @CurrentComment06 = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment06 += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' - SET @CurrentComment06 += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 += 'NewLOB: ' + CASE WHEN @CurrentIsNewLOB = 1 THEN 'Yes' WHEN @CurrentIsNewLOB = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 11 SET @CurrentComment06 += 'ColumnStore: ' + CASE WHEN @CurrentIsColumnStore = 1 THEN 'Yes' WHEN @CurrentIsColumnStore = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 += 'AllowPageLocks: ' + CASE WHEN @CurrentAllowPageLocks = 1 THEN 'Yes' WHEN @CurrentAllowPageLocks = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 += 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar),'N/A') + ', ' - SET @CurrentComment06 += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar),'N/A') + SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'NewLOB: ' + CASE WHEN @CurrentIsNewLOB = 1 THEN 'Yes' WHEN @CurrentIsNewLOB = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 11 SET @CurrentComment += 'ColumnStore: ' + CASE WHEN @CurrentIsColumnStore = 1 THEN 'Yes' WHEN @CurrentIsColumnStore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'AllowPageLocks: ' + CASE WHEN @CurrentAllowPageLocks = 1 THEN 'Yes' WHEN @CurrentAllowPageLocks = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar),'N/A') + ', ' + SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar),'N/A') END IF @CurrentIndexID IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) BEGIN - SET @CurrentExtendedInfo06 = (SELECT * - FROM (SELECT CAST(@CurrentPageCount AS nvarchar) AS [PageCount], - CAST(@CurrentFragmentationLevel AS nvarchar) AS Fragmentation - ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentPageCount AS nvarchar) AS [PageCount], + CAST(@CurrentFragmentationLevel AS nvarchar) AS Fragmentation + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END -- Create statistics comment IF @CurrentStatisticsID IS NOT NULL BEGIN - SET @CurrentComment07 = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment07 += 'IndexType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' - IF @CurrentIndexID IS NOT NULL SET @CurrentComment07 += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' - SET @CurrentComment07 += 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Y' WHEN @CurrentIsIncremental = 0 THEN 'N' ELSE 'N/A' END + ', ' - SET @CurrentComment07 += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' - SET @CurrentComment07 += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') + SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'IndexType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' + IF @CurrentIndexID IS NOT NULL SET @CurrentComment += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Y' WHEN @CurrentIsIncremental = 0 THEN 'N' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' + SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') END IF @CurrentStatisticsID IS NOT NULL AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) BEGIN - SET @CurrentExtendedInfo07 = (SELECT * - FROM (SELECT CAST(@CurrentRowCount AS nvarchar) AS [RowCount], - CAST(@CurrentModificationCounter AS nvarchar) AS ModificationCounter - ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentRowCount AS nvarchar) AS [RowCount], + CAST(@CurrentModificationCounter AS nvarchar) AS ModificationCounter + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END IF @CurrentIndexID IS NOT NULL AND @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommandType06 = 'ALTER_INDEX' + SET @CurrentDatabaseContext = @CurrentDatabaseName + + SET @CurrentCommandType = 'ALTER_INDEX' - SET @CurrentCommand06 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand06 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand06 += 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) - IF @CurrentResumableIndexOperation = 1 SET @CurrentCommand06 += ' RESUME' - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 += ' REBUILD' - IF @CurrentAction IN('INDEX_REORGANIZE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 += ' REORGANIZE' - IF @CurrentIsPartition = 1 AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 += ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + IF @CurrentResumableIndexOperation = 1 SET @CurrentCommand += ' RESUME' + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand += ' REBUILD' + IF @CurrentAction IN('INDEX_REORGANIZE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand += ' REORGANIZE' + IF @CurrentIsPartition = 1 AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand += ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN @@ -2016,12 +2007,12 @@ BEGIN SET @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + ')' END - IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand06 += @CurrentAlterIndexWithClause + IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand += @CurrentAlterIndexWithClause - EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment06, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo06, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput06 = @Error - IF @CurrentCommandOutput06 <> 0 SET @ReturnCode = @CurrentCommandOutput06 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput IF @Delay > 0 BEGIN @@ -2034,11 +2025,13 @@ BEGIN IF @CurrentStatisticsID IS NOT NULL AND @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommandType07 = 'UPDATE_STATISTICS' + SET @CurrentDatabaseContext = @CurrentDatabaseName - SET @CurrentCommand07 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand07 += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) + SET @CurrentCommandType = 'UPDATE_STATISTICS' + + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) BEGIN @@ -2097,14 +2090,14 @@ BEGIN SET @CurrentUpdateStatisticsWithClause = LEFT(@CurrentUpdateStatisticsWithClause,LEN(@CurrentUpdateStatisticsWithClause) - 1) END - IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand07 += @CurrentUpdateStatisticsWithClause + IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand += @CurrentUpdateStatisticsWithClause - IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand07 += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' - EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput07 = @Error - IF @CurrentCommandOutput07 <> 0 SET @ReturnCode = @CurrentCommandOutput07 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput END NoAction: @@ -2118,24 +2111,13 @@ BEGIN AND ID = @CurrentIxID -- Clear variables - SET @CurrentCommand02 = NULL - SET @CurrentCommand03 = NULL - SET @CurrentCommand04 = NULL - SET @CurrentCommand05 = NULL - SET @CurrentCommand06 = NULL - SET @CurrentCommand07 = NULL - - SET @CurrentCommandOutput06 = NULL - SET @CurrentCommandOutput07 = NULL - - SET @CurrentCommandType06 = NULL - SET @CurrentCommandType07 = NULL - - SET @CurrentComment06 = NULL - SET @CurrentComment07 = NULL + SET @CurrentDatabaseContext = NULL - SET @CurrentExtendedInfo06 = NULL - SET @CurrentExtendedInfo07 = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL + SET @CurrentComment = NULL + SET @CurrentExtendedInfo = NULL SET @CurrentIxID = NULL SET @CurrentIxOrder = NULL @@ -2234,7 +2216,7 @@ BEGIN SET @CurrentAvailabilityGroupRole = NULL SET @CurrentDatabaseMirroringRole = NULL - SET @CurrentCommand01 = NULL + SET @CurrentCommand = NULL DELETE FROM @tmpIndexesStatistics diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index a119c528..c1137cf3 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-09 23:10:28 +Version: 2020-01-11 12:40:32 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-09 23:10:28 //-- + --// Version: 2020-01-11 12:40:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -428,7 +428,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-09 23:10:28 //-- + --// Version: 2020-01-11 12:40:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -507,29 +507,17 @@ BEGIN DECLARE @CurrentAllocatedExtentPageCount bigint DECLARE @CurrentModifiedExtentPageCount bigint - DECLARE @CurrentCommand01 nvarchar(max) - DECLARE @CurrentCommand02 nvarchar(max) - DECLARE @CurrentCommand03 nvarchar(max) - DECLARE @CurrentCommand04 nvarchar(max) - DECLARE @CurrentCommand05 nvarchar(max) - DECLARE @CurrentCommand07 nvarchar(max) - - DECLARE @CurrentCommandOutput01 int - DECLARE @CurrentCommandOutput02 int - DECLARE @CurrentCommandOutput03 int - DECLARE @CurrentCommandOutput04 int - DECLARE @CurrentCommandOutput05 int - - DECLARE @CurrentCommandType01 nvarchar(max) - DECLARE @CurrentCommandType02 nvarchar(max) - DECLARE @CurrentCommandType03 nvarchar(max) - DECLARE @CurrentCommandType04 nvarchar(max) - DECLARE @CurrentCommandType05 nvarchar(max) + DECLARE @CurrentDatabaseContext nvarchar(max) + DECLARE @CurrentCommand nvarchar(max) + DECLARE @CurrentCommandOutput int + DECLARE @CurrentCommandType nvarchar(max) DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, - [Message] nvarchar(max)) + [Message] nvarchar(max) NOT NULL, + Severity int NOT NULL) DECLARE @CurrentMessage nvarchar(max) + DECLARE @CurrentSeverity int DECLARE @Directories TABLE (ID int PRIMARY KEY, DirectoryPath nvarchar(max), @@ -575,6 +563,8 @@ BEGIN StartPosition int, Selected bit) + DECLARE @CurrentBackupOutput bit + DECLARE @CurrentBackupSet TABLE (ID int IDENTITY PRIMARY KEY, Mirror bit, VerifyCompleted bit, @@ -722,62 +712,62 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16 END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16 END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16 END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 END 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') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16 END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16 END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16 END IF @@TRANCOUNT <> 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The transaction count is not 0.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The transaction count is not 0.', 16 END IF @AmazonRDS = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The stored procedure DatabaseBackup is not supported on Amazon RDS.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The stored procedure DatabaseBackup is not supported on Amazon RDS.', 16 END ---------------------------------------------------------------------------------------------------- @@ -904,8 +894,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Databases is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Databases is not supported.', 16 END ---------------------------------------------------------------------------------------------------- @@ -999,20 +989,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16 END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16 END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16 END ---------------------------------------------------------------------------------------------------- @@ -1027,8 +1017,8 @@ BEGIN ORDER BY DatabaseName ASC IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 16 END SET @ErrorMessage = '' @@ -1041,8 +1031,8 @@ BEGIN OPTION (RECOMPILE) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 16 END ---------------------------------------------------------------------------------------------------- @@ -1143,8 +1133,8 @@ BEGIN OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath <> 'NUL')) OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Directory is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Directory is not supported.', 16 END IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) @@ -1159,14 +1149,14 @@ BEGIN OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MirrorDirectory is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16 END IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'Mirrored backup to disk is only available in Enterprise and Developer Edition.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'Mirrored backup to disk is only available in Enterprise and Developer Edition.', 16 END IF NOT EXISTS (SELECT * FROM @Errors WHERE [Message] IN('The value for the parameter @Directory is not supported.','The value for the parameter @MirrorDirectory is not supported.')) @@ -1190,8 +1180,8 @@ BEGIN IF NOT EXISTS (SELECT * FROM @DirectoryInfo WHERE FileExists = 0 AND FileIsADirectory = 1 AND ParentDirectoryExists = 1) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.', 16 END UPDATE @Directories @@ -1273,16 +1263,16 @@ BEGIN OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @URL is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @URL is not supported.', 16 END IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath NOT LIKE 'https://%/%') OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MirrorURL is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16 END ---------------------------------------------------------------------------------------------------- @@ -1355,498 +1345,498 @@ BEGIN IF @BackupType NOT IN ('FULL','DIFF','LOG') OR @BackupType IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @BackupType is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @BackupType is not supported.', 16 END IF SERVERPROPERTY('EngineEdition') = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.', 16 END IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Verify is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Verify is not supported.', 16 END IF @Verify = 'Y' AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.', 16 END IF @CleanupTime < 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupTime is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupTime is not supported.', 16 END IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.', 16 END IF @CleanupTime IS NOT NULL AND @HostPlatform = 'Linux' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.', 16 END IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.', 16 END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.', 16 END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.', 16 END IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.', 16 END IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CleanupMode is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CleanupMode is not supported.', 16 END IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Compress is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Compress is not supported.', 16 END IF @CopyOnly NOT IN ('Y','N') OR @CopyOnly IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CopyOnly is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CopyOnly is not supported.', 16 END IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @ChangeBackupType is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @ChangeBackupType is not supported.', 16 END IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @BackupSoftware is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @BackupSoftware is not supported.', 16 END IF @BackupSoftware = 'LITESPEED' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_backup_database') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.', 16 END IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.', 16 END IF @BackupSoftware = 'SQLSAFE' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_ss_backup') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.', 16 END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'PC' AND [name] = 'emc_run_backup') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.', 16 END IF @CheckSum NOT IN ('Y','N') OR @CheckSum IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CheckSum is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CheckSum is not supported.', 16 END IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @BlockSize is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @BlockSize is not supported.', 16 END IF @BufferCount <= 0 OR @BufferCount > 2147483647 OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @BufferCount is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @BufferCount is not supported.', 16 END IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MaxTransferSize is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16 END IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @NumberOfFiles is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16 END IF @MinBackupSizeForMultipleFiles <= 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported.', 16 END IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @NumberOfFiles IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.', 16 END IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @BackupType = 'DIFF' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.', 16 END IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @BackupType = 'LOG' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16 END IF @MaxFileSize <= 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MaxFileSize is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MaxFileSize is not supported.', 16 END IF @MaxFileSize IS NOT NULL AND @NumberOfFiles IS NOT NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The parameters @MaxFileSize and @NumberOfFiles cannot be used together.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The parameters @MaxFileSize and @NumberOfFiles cannot be used together.', 16 END IF @MaxFileSize IS NOT NULL AND @BackupType = 'DIFF' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.', 16 END IF @MaxFileSize IS NOT NULL AND @BackupType = 'LOG' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16 END IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CompressionLevel is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CompressionLevel is not supported.', 16 END IF LEN(@Description) > 255 OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Description is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Description is not supported.', 16 END IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) OR (@BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32)) OR (@BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32)) OR (@BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Threads is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Threads is not supported.', 16 END IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) OR @Throttle < 1 OR @Throttle > 100 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Throttle is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Throttle is not supported.', 16 END IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Encrypt is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Encrypt is not supported.', 16 END IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16 END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL) OR (@ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @ServerCertificate is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @ServerCertificate is not supported.', 16 END IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL) OR (@ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.', 16 END IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @EncryptionKey is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @EncryptionKey is not supported.', 16 END IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL OR (@ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.', 16 END IF @OverrideBackupPreference NOT IN('Y','N') OR @OverrideBackupPreference IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @OverrideBackupPreference is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @OverrideBackupPreference is not supported.', 16 END IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL OR (@NoRecovery = 'Y' AND @BackupType <> 'LOG') OR (@NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @NoRecovery is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @NoRecovery is not supported.', 16 END IF (@URL IS NOT NULL AND @Directory IS NOT NULL) OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@URL IS NOT NULL AND @Version < 11.03339) OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @URL is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @URL is not supported.', 16 END IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Credential is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Credential is not supported.', 16 END IF @MirrorCleanupTime < 0 OR (@MirrorCleanupTime IS NOT NULL AND @MirrorDirectory IS NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MirrorCleanupTime is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MirrorCleanupTime is not supported.', 16 END IF @MirrorCleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @MirrorCleanupMode IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MirrorCleanupMode is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MirrorCleanupMode is not supported.', 16 END IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @URL IS NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MirrorURL is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16 END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Updateability is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Updateability is not supported.', 16 END IF @AdaptiveCompression NOT IN('SIZE','SPEED') OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @AdaptiveCompression is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @AdaptiveCompression is not supported.', 16 END IF (@ModificationLevel IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count')) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @ModificationLevel is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @ModificationLevel is not supported.', 16 END IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb')) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.', 16 END IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_backup_time')) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @TimeSinceLastLogBackup is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @TimeSinceLastLogBackup is not supported.', 16 END IF (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The parameters @TimeSinceLastLogBackup and @LogSizeSinceLastLogBackup can only be used together.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The parameters @TimeSinceLastLogBackup and @LogSizeSinceLastLogBackup can only be used together.', 16 END IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DataDomainBoostHost is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16 END IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DataDomainBoostUser is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16 END IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16 END IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16 END IF @DirectoryStructure = '' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DirectoryStructure is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DirectoryStructure is not supported.', 16 END IF @AvailabilityGroupDirectoryStructure = '' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.', 16 END IF @FileName IS NULL OR @FileName = '' OR @FileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') OR @FileName LIKE '%{DirectorySeperator}%' OR @FileName LIKE '%/%' OR @FileName LIKE '%\%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FileName is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FileName is not supported.', 16 END IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) OR @AvailabilityGroupFileName = '' OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' OR @AvailabilityGroupFileName LIKE '%/%' OR @AvailabilityGroupFileName LIKE '%\%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16 END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The parameter @DirectoryStructure contains one or more tokens that are not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The parameter @DirectoryStructure contains one or more tokens that are not supported.', 16 END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.', 16 END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The parameter @FileName contains one or more tokens that are not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The parameter @FileName contains one or more tokens that are not supported.', 16 END IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.', 16 END IF @FileExtensionFull LIKE '%.%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FileExtensionFull is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FileExtensionFull is not supported.', 16 END IF @FileExtensionDiff LIKE '%.%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FileExtensionDiff is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FileExtensionDiff is not supported.', 16 END IF @FileExtensionLog LIKE '%.%' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FileExtensionLog is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FileExtensionLog is not supported.', 16 END IF @Init NOT IN('Y','N') OR @Init IS NULL OR (@Init = 'Y' AND @BackupType = 'LOG') OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Init is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Init is not supported.', 16 END IF @Format NOT IN('Y','N') OR @Format IS NULL OR (@Format = 'Y' AND @BackupType = 'LOG') OR (@Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Format is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Format is not supported.', 16 END IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL) OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED') OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16 END IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @StringDelimiter is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 END IF @DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabaseOrder is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabaseOrder is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16 END IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LogToTable is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LogToTable is not supported.', 16 END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Execute is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Execute is not supported.', 16 END IF EXISTS(SELECT * FROM @Errors) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.', 16 END ---------------------------------------------------------------------------------------------------- @@ -1860,8 +1850,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -1871,8 +1861,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END ---------------------------------------------------------------------------------------------------- @@ -1881,33 +1871,33 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16 END ---------------------------------------------------------------------------------------------------- --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor - FETCH ErrorCursor INTO @CurrentMessage + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity WHILE @@FETCH_STATUS = 0 BEGIN - RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR('%s', @CurrentSeverity, 1, @CurrentMessage) WITH NOWAIT RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT - FETCH NEXT FROM ErrorCursor INTO @CurrentMessage + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity END CLOSE ErrorCursor DEALLOCATE ErrorCursor - IF EXISTS (SELECT * FROM @Errors) + IF EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) BEGIN SET @ReturnCode = 50000 GOTO Logging @@ -2233,9 +2223,9 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) BEGIN - SET @CurrentCommand07 = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' + SET @CurrentCommand = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand07, @params = N'@ParamAllocatedExtentPageCount bigint OUTPUT, @ParamModifiedExtentPageCount bigint OUTPUT', @ParamAllocatedExtentPageCount = @CurrentAllocatedExtentPageCount OUTPUT, @ParamModifiedExtentPageCount = @CurrentModifiedExtentPageCount OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAllocatedExtentPageCount bigint OUTPUT, @ParamModifiedExtentPageCount bigint OUTPUT', @ParamAllocatedExtentPageCount = @CurrentAllocatedExtentPageCount OUTPUT, @ParamModifiedExtentPageCount = @CurrentModifiedExtentPageCount OUTPUT END SET @CurrentBackupType = @BackupType @@ -2937,26 +2927,29 @@ BEGIN BREAK END - SET @CurrentCommandType01 = 'xp_create_subdir' - SET @CurrentCommand01 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_create_subdir N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''' IF @ReturnCode <> 0 RAISERROR(''Error creating directory.'', 16, 1)' - EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'xp_create_subdir' + + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_create_subdir N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''' IF @ReturnCode <> 0 RAISERROR(''Error creating directory.'', 16, 1)' + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput01 = @Error - IF @CurrentCommandOutput01 <> 0 SET @ReturnCode = @CurrentCommandOutput01 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput UPDATE @CurrentDirectories SET CreateCompleted = 1, - CreateOutput = @CurrentCommandOutput01 + CreateOutput = @CurrentCommandOutput WHERE ID = @CurrentDirectoryID SET @CurrentDirectoryID = NULL SET @CurrentDirectoryPath = NULL - SET @CurrentCommand01 = NULL - - SET @CurrentCommandOutput01 = NULL - - SET @CurrentCommandType01 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL END END @@ -3016,51 +3009,58 @@ BEGIN IF @BackupSoftware IS NULL BEGIN - SET @CurrentCommandType02 = 'xp_delete_file' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'xp_delete_file' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' BEGIN - SET @CurrentCommandType02 = 'xp_slssqlmaint' + SET @CurrentDatabaseContext = 'master' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommandType = 'xp_slssqlmaint' + + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN - SET @CurrentCommandType02 = 'sqbutility' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'sqbutility' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN - SET @CurrentCommandType02 = 'xp_ss_delete' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'xp_ss_delete' - SET @CurrentCommand02 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END - EXECUTE @CurrentCommandOutput02 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand02, @CommandType = @CurrentCommandType02, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput02 = @Error - IF @CurrentCommandOutput02 <> 0 SET @ReturnCode = @CurrentCommandOutput02 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput UPDATE @CurrentDirectories SET CleanupCompleted = 1, - CleanupOutput = @CurrentCommandOutput02 + CleanupOutput = @CurrentCommandOutput WHERE ID = @CurrentDirectoryID SET @CurrentDirectoryID = NULL SET @CurrentDirectoryPath = NULL SET @CurrentCleanupDate = NULL - SET @CurrentCommand02 = NULL - - SET @CurrentCommandOutput02 = NULL - - SET @CurrentCommandType02 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL END END @@ -3069,112 +3069,116 @@ BEGIN BEGIN IF @BackupSoftware IS NULL BEGIN - SELECT @CurrentCommandType03 = CASE + SET @CurrentDatabaseContext = 'master' + + SELECT @CurrentCommandType = CASE WHEN @CurrentBackupType IN('DIFF','FULL') THEN 'BACKUP_DATABASE' WHEN @CurrentBackupType = 'LOG' THEN 'BACKUP_LOG' END - SELECT @CurrentCommand03 = CASE + SELECT @CurrentCommand = CASE WHEN @CurrentBackupType IN('DIFF','FULL') THEN 'BACKUP DATABASE ' + QUOTENAME(@CurrentDatabaseName) WHEN @CurrentBackupType = 'LOG' THEN 'BACKUP LOG ' + QUOTENAME(@CurrentDatabaseName) END - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ' READ_WRITE_FILEGROUPS' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand += ' READ_WRITE_FILEGROUPS' - SET @CurrentCommand03 += ' TO' + SET @CurrentCommand += ' TO' - SELECT @CurrentCommand03 += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SET @CurrentCommand03 += ' MIRROR TO' + SET @CurrentCommand += ' MIRROR TO' - SELECT @CurrentCommand03 += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 1 ORDER BY FilePath ASC END - SET @CurrentCommand03 += ' WITH ' - IF @CheckSum = 'Y' SET @CurrentCommand03 += 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand03 += 'NO_CHECKSUM' + SET @CurrentCommand += ' WITH ' + IF @CheckSum = 'Y' SET @CurrentCommand += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' IF @Version >= 10 BEGIN - SET @CurrentCommand03 += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND @Version >= 13 AND @CurrentMaxTransferSize > 65536)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END + SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND @Version >= 13 AND @CurrentMaxTransferSize > 65536)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END END - IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 += ', DIFFERENTIAL' + IF @CurrentBackupType = 'DIFF' SET @CurrentCommand += ', DIFFERENTIAL' IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SET @CurrentCommand03 += ', FORMAT' + SET @CurrentCommand += ', FORMAT' END - IF @CopyOnly = 'Y' SET @CurrentCommand03 += ', COPY_ONLY' - IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 += ', NORECOVERY' - IF @Init = 'Y' SET @CurrentCommand03 += ', INIT' - IF @Format = 'Y' SET @CurrentCommand03 += ', FORMAT' - IF @BlockSize IS NOT NULL SET @CurrentCommand03 += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) - IF @BufferCount IS NOT NULL SET @CurrentCommand03 += ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar) - IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' - IF @Encrypt = 'Y' SET @CurrentCommand03 += ', ENCRYPTION (ALGORITHM = ' + UPPER(@EncryptionAlgorithm) + ', ' - IF @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL SET @CurrentCommand03 += 'SERVER CERTIFICATE = ' + QUOTENAME(@ServerCertificate) - IF @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL SET @CurrentCommand03 += 'SERVER ASYMMETRIC KEY = ' + QUOTENAME(@ServerAsymmetricKey) - IF @Encrypt = 'Y' SET @CurrentCommand03 += ')' - IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand03 += ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' + IF @CopyOnly = 'Y' SET @CurrentCommand += ', COPY_ONLY' + IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand += ', NORECOVERY' + IF @Init = 'Y' SET @CurrentCommand += ', INIT' + IF @Format = 'Y' SET @CurrentCommand += ', FORMAT' + IF @BlockSize IS NOT NULL SET @CurrentCommand += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) + IF @BufferCount IS NOT NULL SET @CurrentCommand += ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) + IF @Description IS NOT NULL SET @CurrentCommand += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' + IF @Encrypt = 'Y' SET @CurrentCommand += ', ENCRYPTION (ALGORITHM = ' + UPPER(@EncryptionAlgorithm) + ', ' + IF @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL SET @CurrentCommand += 'SERVER CERTIFICATE = ' + QUOTENAME(@ServerCertificate) + IF @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL SET @CurrentCommand += 'SERVER ASYMMETRIC KEY = ' + QUOTENAME(@ServerAsymmetricKey) + IF @Encrypt = 'Y' SET @CurrentCommand += ')' + IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand += ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' END IF @BackupSoftware = 'LITESPEED' BEGIN - SELECT @CurrentCommandType03 = CASE + SET @CurrentDatabaseContext = 'master' + + SELECT @CurrentCommandType = CASE WHEN @CurrentBackupType IN('DIFF','FULL') THEN 'xp_backup_database' WHEN @CurrentBackupType = 'LOG' THEN 'xp_backup_log' END - SELECT @CurrentCommand03 = CASE + SELECT @CurrentCommand = CASE WHEN @CurrentBackupType IN('DIFF','FULL') THEN 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_backup_database @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' WHEN @CurrentBackupType = 'LOG' THEN 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_backup_log @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' END - SELECT @CurrentCommand03 += ', @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand += ', @filename = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SELECT @CurrentCommand03 += ', @mirror = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand += ', @mirror = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 1 ORDER BY FilePath ASC END - SET @CurrentCommand03 += ', @with = ''' - IF @CheckSum = 'Y' SET @CurrentCommand03 += 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand03 += 'NO_CHECKSUM' - IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 += ', DIFFERENTIAL' - IF @CopyOnly = 'Y' SET @CurrentCommand03 += ', COPY_ONLY' - IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 += ', NORECOVERY' - IF @BlockSize IS NOT NULL SET @CurrentCommand03 += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) - SET @CurrentCommand03 += '''' - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ', @read_write_filegroups = 1' - IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 += ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) - IF @AdaptiveCompression IS NOT NULL SET @CurrentCommand03 += ', @adaptivecompression = ''' + CASE WHEN @AdaptiveCompression = 'SIZE' THEN 'Size' WHEN @AdaptiveCompression = 'SPEED' THEN 'Speed' END + '''' - IF @BufferCount IS NOT NULL SET @CurrentCommand03 += ', @buffercount = ' + CAST(@BufferCount AS nvarchar) - IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 += ', @maxtransfersize = ' + CAST(@CurrentMaxTransferSize AS nvarchar) - IF @Threads IS NOT NULL SET @CurrentCommand03 += ', @threads = ' + CAST(@Threads AS nvarchar) - IF @Init = 'Y' SET @CurrentCommand03 += ', @init = 1' - IF @Format = 'Y' SET @CurrentCommand03 += ', @format = 1' - IF @Throttle IS NOT NULL SET @CurrentCommand03 += ', @throttle = ' + CAST(@Throttle AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' - IF @ObjectLevelRecoveryMap = 'Y' SET @CurrentCommand03 += ', @olrmap = 1' - - IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 += ', @cryptlevel = ' + CASE + SET @CurrentCommand += ', @with = ''' + IF @CheckSum = 'Y' SET @CurrentCommand += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' + IF @CurrentBackupType = 'DIFF' SET @CurrentCommand += ', DIFFERENTIAL' + IF @CopyOnly = 'Y' SET @CurrentCommand += ', COPY_ONLY' + IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand += ', NORECOVERY' + IF @BlockSize IS NOT NULL SET @CurrentCommand += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar) + SET @CurrentCommand += '''' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand += ', @read_write_filegroups = 1' + IF @CompressionLevel IS NOT NULL SET @CurrentCommand += ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) + IF @AdaptiveCompression IS NOT NULL SET @CurrentCommand += ', @adaptivecompression = ''' + CASE WHEN @AdaptiveCompression = 'SIZE' THEN 'Size' WHEN @AdaptiveCompression = 'SPEED' THEN 'Speed' END + '''' + IF @BufferCount IS NOT NULL SET @CurrentCommand += ', @buffercount = ' + CAST(@BufferCount AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand += ', @maxtransfersize = ' + CAST(@CurrentMaxTransferSize AS nvarchar) + IF @Threads IS NOT NULL SET @CurrentCommand += ', @threads = ' + CAST(@Threads AS nvarchar) + IF @Init = 'Y' SET @CurrentCommand += ', @init = 1' + IF @Format = 'Y' SET @CurrentCommand += ', @format = 1' + IF @Throttle IS NOT NULL SET @CurrentCommand += ', @throttle = ' + CAST(@Throttle AS nvarchar) + IF @Description IS NOT NULL SET @CurrentCommand += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' + IF @ObjectLevelRecoveryMap = 'Y' SET @CurrentCommand += ', @olrmap = 1' + + IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand += ', @cryptlevel = ' + CASE WHEN @EncryptionAlgorithm = 'RC2_40' THEN '0' WHEN @EncryptionAlgorithm = 'RC2_56' THEN '1' WHEN @EncryptionAlgorithm = 'RC2_112' THEN '2' @@ -3186,141 +3190,148 @@ BEGIN WHEN @EncryptionAlgorithm = 'AES_256' THEN '8' END - IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand03 += ' IF @ReturnCode <> 0 RAISERROR(''Error performing LiteSpeed backup.'', 16, 1)' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error performing LiteSpeed backup.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN - SET @CurrentCommandType03 = 'sqlbackup' + SET @CurrentDatabaseContext = 'master' - SELECT @CurrentCommand03 = CASE + SET @CurrentCommandType = 'sqlbackup' + + SELECT @CurrentCommand = CASE WHEN @CurrentBackupType IN('DIFF','FULL') THEN 'BACKUP DATABASE ' + QUOTENAME(@CurrentDatabaseName) WHEN @CurrentBackupType = 'LOG' THEN 'BACKUP LOG ' + QUOTENAME(@CurrentDatabaseName) END - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ' READ_WRITE_FILEGROUPS' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand += ' READ_WRITE_FILEGROUPS' - SET @CurrentCommand03 += ' TO' + SET @CurrentCommand += ' TO' - SELECT @CurrentCommand03 += ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand += ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC - SET @CurrentCommand03 += ' WITH ' + SET @CurrentCommand += ' WITH ' IF EXISTS(SELECT * FROM @CurrentFiles WHERE Mirror = 1) BEGIN - SET @CurrentCommand03 += ' MIRRORFILE' + ' = N''' + REPLACE((SELECT FilePath FROM @CurrentFiles WHERE Mirror = 1),'''','''''') + ''', ' + SET @CurrentCommand += ' MIRRORFILE' + ' = N''' + REPLACE((SELECT FilePath FROM @CurrentFiles WHERE Mirror = 1),'''','''''') + ''', ' END - IF @CheckSum = 'Y' SET @CurrentCommand03 += 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand03 += 'NO_CHECKSUM' - IF @CurrentBackupType = 'DIFF' SET @CurrentCommand03 += ', DIFFERENTIAL' - IF @CopyOnly = 'Y' SET @CurrentCommand03 += ', COPY_ONLY' - IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand03 += ', NORECOVERY' - IF @Init = 'Y' SET @CurrentCommand03 += ', INIT' - IF @Format = 'Y' SET @CurrentCommand03 += ', FORMAT' - IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 += ', COMPRESSION = ' + CAST(@CompressionLevel AS nvarchar) - IF @Threads IS NOT NULL SET @CurrentCommand03 += ', THREADCOUNT = ' + CAST(@Threads AS nvarchar) - IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand03 += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' - - IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 += ', KEYSIZE = ' + CASE + IF @CheckSum = 'Y' SET @CurrentCommand += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' + IF @CurrentBackupType = 'DIFF' SET @CurrentCommand += ', DIFFERENTIAL' + IF @CopyOnly = 'Y' SET @CurrentCommand += ', COPY_ONLY' + IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand += ', NORECOVERY' + IF @Init = 'Y' SET @CurrentCommand += ', INIT' + IF @Format = 'Y' SET @CurrentCommand += ', FORMAT' + IF @CompressionLevel IS NOT NULL SET @CurrentCommand += ', COMPRESSION = ' + CAST(@CompressionLevel AS nvarchar) + IF @Threads IS NOT NULL SET @CurrentCommand += ', THREADCOUNT = ' + CAST(@Threads AS nvarchar) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar) + IF @Description IS NOT NULL SET @CurrentCommand += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' + + IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand += ', KEYSIZE = ' + CASE WHEN @EncryptionAlgorithm = 'AES_128' THEN '128' WHEN @EncryptionAlgorithm = 'AES_256' THEN '256' END - IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 += ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand03,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLBackup backup.'', 16, 1)' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLBackup backup.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN - SET @CurrentCommandType03 = 'xp_ss_backup' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'xp_ss_backup' - SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_backup @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_backup @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' - SELECT @CurrentCommand03 += ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand += ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 0 ORDER BY FilePath ASC - SELECT @CurrentCommand03 += ', @mirrorfile = N''' + REPLACE(FilePath,'''','''''') + '''' + SELECT @CurrentCommand += ', @mirrorfile = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = 1 ORDER BY FilePath ASC - SET @CurrentCommand03 += ', @backuptype = ' + CASE WHEN @CurrentBackupType = 'FULL' THEN '''Full''' WHEN @CurrentBackupType = 'DIFF' THEN '''Differential''' WHEN @CurrentBackupType = 'LOG' THEN '''Log''' END - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ', @readwritefilegroups = 1' - SET @CurrentCommand03 += ', @checksum = ' + CASE WHEN @CheckSum = 'Y' THEN '1' WHEN @CheckSum = 'N' THEN '0' END - SET @CurrentCommand03 += ', @copyonly = ' + CASE WHEN @CopyOnly = 'Y' THEN '1' WHEN @CopyOnly = 'N' THEN '0' END - IF @CompressionLevel IS NOT NULL SET @CurrentCommand03 += ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) - IF @Threads IS NOT NULL SET @CurrentCommand03 += ', @threads = ' + CAST(@Threads AS nvarchar) - IF @Init = 'Y' SET @CurrentCommand03 += ', @overwrite = 1' - IF @Description IS NOT NULL SET @CurrentCommand03 += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' + SET @CurrentCommand += ', @backuptype = ' + CASE WHEN @CurrentBackupType = 'FULL' THEN '''Full''' WHEN @CurrentBackupType = 'DIFF' THEN '''Differential''' WHEN @CurrentBackupType = 'LOG' THEN '''Log''' END + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand += ', @readwritefilegroups = 1' + SET @CurrentCommand += ', @checksum = ' + CASE WHEN @CheckSum = 'Y' THEN '1' WHEN @CheckSum = 'N' THEN '0' END + SET @CurrentCommand += ', @copyonly = ' + CASE WHEN @CopyOnly = 'Y' THEN '1' WHEN @CopyOnly = 'N' THEN '0' END + IF @CompressionLevel IS NOT NULL SET @CurrentCommand += ', @compressionlevel = ' + CAST(@CompressionLevel AS nvarchar) + IF @Threads IS NOT NULL SET @CurrentCommand += ', @threads = ' + CAST(@Threads AS nvarchar) + IF @Init = 'Y' SET @CurrentCommand += ', @overwrite = 1' + IF @Description IS NOT NULL SET @CurrentCommand += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' - IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand03 += ', @encryptiontype = N''' + CASE + IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand += ', @encryptiontype = N''' + CASE WHEN @EncryptionAlgorithm = 'AES_128' THEN 'AES128' WHEN @EncryptionAlgorithm = 'AES_256' THEN 'AES256' END + '''' - IF @EncryptionKey IS NOT NULL SET @CurrentCommand03 += ', @encryptedbackuppassword = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand03 += ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptedbackuppassword = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN - SET @CurrentCommandType03 = 'emc_run_backup' + SET @CurrentDatabaseContext = 'master' - SET @CurrentCommand03 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.emc_run_backup ''' + SET @CurrentCommandType = 'emc_run_backup' - SET @CurrentCommand03 += ' -c ' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar) END + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.emc_run_backup ''' - SET @CurrentCommand03 += ' -l ' + CASE + SET @CurrentCommand += ' -c ' + CASE WHEN @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar) END + + SET @CurrentCommand += ' -l ' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'full' WHEN @CurrentBackupType = 'DIFF' THEN 'diff' WHEN @CurrentBackupType = 'LOG' THEN 'incr' END - IF @NoRecovery = 'Y' SET @CurrentCommand03 += ' -H' + IF @NoRecovery = 'Y' SET @CurrentCommand += ' -H' - IF @CleanupTime IS NOT NULL SET @CurrentCommand03 += ' -y +' + CAST(@CleanupTime/24 + CASE WHEN @CleanupTime%24 > 0 THEN 1 ELSE 0 END AS nvarchar) + 'd' + IF @CleanupTime IS NOT NULL SET @CurrentCommand += ' -y +' + CAST(@CleanupTime/24 + CASE WHEN @CleanupTime%24 > 0 THEN 1 ELSE 0 END AS nvarchar) + 'd' - IF @CheckSum = 'Y' SET @CurrentCommand03 += ' -k' + IF @CheckSum = 'Y' SET @CurrentCommand += ' -k' - SET @CurrentCommand03 += ' -S ' + CAST(@CurrentNumberOfFiles AS nvarchar) + SET @CurrentCommand += ' -S ' + CAST(@CurrentNumberOfFiles AS nvarchar) - IF @Description IS NOT NULL SET @CurrentCommand03 += ' -b "' + REPLACE(@Description,'''','''''') + '"' + IF @Description IS NOT NULL SET @CurrentCommand += ' -b "' + REPLACE(@Description,'''','''''') + '"' - IF @BufferCount IS NOT NULL SET @CurrentCommand03 += ' -O "BUFFERCOUNT=' + CAST(@BufferCount AS nvarchar) + '"' + IF @BufferCount IS NOT NULL SET @CurrentCommand += ' -O "BUFFERCOUNT=' + CAST(@BufferCount AS nvarchar) + '"' - IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand03 += ' -O "READ_WRITE_FILEGROUPS"' + IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand += ' -O "READ_WRITE_FILEGROUPS"' - IF @DataDomainBoostHost IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DD_HOST=' + REPLACE(@DataDomainBoostHost,'''','''''') + '"' - IF @DataDomainBoostUser IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DD_USER=' + REPLACE(@DataDomainBoostUser,'''','''''') + '"' - IF @DataDomainBoostDevicePath IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DEVICE_PATH=' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '"' - IF @DataDomainBoostLockboxPath IS NOT NULL SET @CurrentCommand03 += ' -a "NSR_DFA_SI_DD_LOCKBOX_PATH=' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '"' - SET @CurrentCommand03 += ' -a "NSR_SKIP_NON_BACKUPABLE_STATE_DB=TRUE"' - IF @CopyOnly = 'Y' SET @CurrentCommand03 += ' -a "NSR_COPY_ONLY=TRUE"' + IF @DataDomainBoostHost IS NOT NULL SET @CurrentCommand += ' -a "NSR_DFA_SI_DD_HOST=' + REPLACE(@DataDomainBoostHost,'''','''''') + '"' + IF @DataDomainBoostUser IS NOT NULL SET @CurrentCommand += ' -a "NSR_DFA_SI_DD_USER=' + REPLACE(@DataDomainBoostUser,'''','''''') + '"' + IF @DataDomainBoostDevicePath IS NOT NULL SET @CurrentCommand += ' -a "NSR_DFA_SI_DEVICE_PATH=' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '"' + IF @DataDomainBoostLockboxPath IS NOT NULL SET @CurrentCommand += ' -a "NSR_DFA_SI_DD_LOCKBOX_PATH=' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '"' + SET @CurrentCommand += ' -a "NSR_SKIP_NON_BACKUPABLE_STATE_DB=TRUE"' + IF @CopyOnly = 'Y' SET @CurrentCommand += ' -a "NSR_COPY_ONLY=TRUE"' - IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand03 += ' "MSSQL' + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' - IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand03 += ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar) + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' + IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand += ' "MSSQL' + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' + IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand += ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar) + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' - SET @CurrentCommand03 += '''' + SET @CurrentCommand += '''' - SET @CurrentCommand03 += ' IF @ReturnCode <> 0 RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' END - EXECUTE @CurrentCommandOutput03 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand03, @CommandType = @CurrentCommandType03, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput03 = @Error - IF @CurrentCommandOutput03 <> 0 SET @ReturnCode = @CurrentCommandOutput03 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput + SET @CurrentBackupOutput = @CurrentCommandOutput END -- Verify the backup - IF @CurrentCommandOutput03 = 0 AND @Verify = 'Y' + IF @CurrentBackupOutput = 0 AND @Verify = 'Y' BEGIN WHILE (1 = 1) BEGIN @@ -3337,92 +3348,99 @@ BEGIN IF @BackupSoftware IS NULL BEGIN - SET @CurrentCommandType04 = 'RESTORE_VERIFYONLY' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'RESTORE_VERIFYONLY' - SET @CurrentCommand04 = 'RESTORE VERIFYONLY FROM' + SET @CurrentCommand = 'RESTORE VERIFYONLY FROM' - SELECT @CurrentCommand04 += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand += ' ' + [Type] + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 += ' WITH ' - IF @CheckSum = 'Y' SET @CurrentCommand04 += 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand04 += 'NO_CHECKSUM' - IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand04 += ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' + SET @CurrentCommand += ' WITH ' + IF @CheckSum = 'Y' SET @CurrentCommand += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' + IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand += ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' END IF @BackupSoftware = 'LITESPEED' BEGIN - SET @CurrentCommandType04 = 'xp_restore_verifyonly' + SET @CurrentDatabaseContext = 'master' - SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_restore_verifyonly' + SET @CurrentCommandType = 'xp_restore_verifyonly' - SELECT @CurrentCommand04 += ' @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_restore_verifyonly' + + SELECT @CurrentCommand += ' @filename = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 += ', @with = ''' - IF @CheckSum = 'Y' SET @CurrentCommand04 += 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand04 += 'NO_CHECKSUM' - SET @CurrentCommand04 += '''' - IF @EncryptionKey IS NOT NULL SET @CurrentCommand04 += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand += ', @with = ''' + IF @CheckSum = 'Y' SET @CurrentCommand += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' + SET @CurrentCommand += '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand04 += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying LiteSpeed backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying LiteSpeed backup.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN - SET @CurrentCommandType04 = 'sqlbackup' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'sqlbackup' - SET @CurrentCommand04 = 'RESTORE VERIFYONLY FROM' + SET @CurrentCommand = 'RESTORE VERIFYONLY FROM' - SELECT @CurrentCommand04 += ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END + SELECT @CurrentCommand += ' DISK = N''' + REPLACE(FilePath,'''','''''') + '''' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) <> @CurrentNumberOfFiles THEN ',' ELSE '' END FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 += ' WITH ' - IF @CheckSum = 'Y' SET @CurrentCommand04 += 'CHECKSUM' - IF @CheckSum = 'N' SET @CurrentCommand04 += 'NO_CHECKSUM' - IF @EncryptionKey IS NOT NULL SET @CurrentCommand04 += ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + SET @CurrentCommand += ' WITH ' + IF @CheckSum = 'Y' SET @CurrentCommand += 'CHECKSUM' + IF @CheckSum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand04,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLBackup backup.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand,'''','''''') + '"''' + ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLBackup backup.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN - SET @CurrentCommandType04 = 'xp_ss_verify' + SET @CurrentDatabaseContext = 'master' - SET @CurrentCommand04 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_verify @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' + SET @CurrentCommandType = 'xp_ss_verify' - SELECT @CurrentCommand04 += ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_verify @database = N''' + REPLACE(@CurrentDatabaseName,'''','''''') + '''' + + SELECT @CurrentCommand += ', ' + CASE WHEN ROW_NUMBER() OVER (ORDER BY FilePath ASC) = 1 THEN '@filename' ELSE '@backupfile' END + ' = N''' + REPLACE(FilePath,'''','''''') + '''' FROM @CurrentFiles WHERE Mirror = @CurrentIsMirror ORDER BY FilePath ASC - SET @CurrentCommand04 += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' END - EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput04 = @Error - IF @CurrentCommandOutput04 <> 0 SET @ReturnCode = @CurrentCommandOutput04 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput UPDATE @CurrentBackupSet SET VerifyCompleted = 1, - VerifyOutput = @CurrentCommandOutput04 + VerifyOutput = @CurrentCommandOutput WHERE ID = @CurrentBackupSetID SET @CurrentBackupSetID = NULL SET @CurrentIsMirror = NULL - SET @CurrentCommand04 = NULL - - SET @CurrentCommandOutput04 = NULL - - SET @CurrentCommandType04 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL END END @@ -3459,8 +3477,8 @@ BEGIN END -- Delete old backup files, after backup - IF ((@CurrentCommandOutput03 = 0 AND @Verify = 'N') - OR (@CurrentCommandOutput03 = 0 AND @Verify = 'Y' AND NOT EXISTS (SELECT * FROM @CurrentBackupSet WHERE VerifyOutput <> 0 OR VerifyOutput IS NULL))) + IF ((@CurrentBackupOutput = 0 AND @Verify = 'N') + OR (@CurrentBackupOutput = 0 AND @Verify = 'Y' AND NOT EXISTS (SELECT * FROM @CurrentBackupSet WHERE VerifyOutput <> 0 OR VerifyOutput IS NULL))) AND @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) AND @CurrentBackupType = @BackupType @@ -3483,51 +3501,58 @@ BEGIN IF @BackupSoftware IS NULL BEGIN - SET @CurrentCommandType05 = 'xp_delete_file' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'xp_delete_file' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' BEGIN - SET @CurrentCommandType05 = 'xp_slssqlmaint' + SET @CurrentDatabaseContext = 'master' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommandType = 'xp_slssqlmaint' + + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + @CurrentFileExtension + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' BEGIN - SET @CurrentCommandType05 = 'sqbutility' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'sqbutility' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqbutility 1032, N''' + REPLACE(@CurrentDatabaseName,'''','''''') + ''', N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'D' WHEN @CurrentBackupType = 'DIFF' THEN 'I' WHEN @CurrentBackupType = 'LOG' THEN 'L' END + ''', ''' + CAST(DATEDIFF(hh,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' BEGIN - SET @CurrentCommandType05 = 'xp_ss_delete' + SET @CurrentDatabaseContext = 'master' + + SET @CurrentCommandType = 'xp_ss_delete' - SET @CurrentCommand05 = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + @CurrentFileExtension + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar) + 'Minutes'' IF @ReturnCode <> 0 RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END - EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput05 = @Error - IF @CurrentCommandOutput05 <> 0 SET @ReturnCode = @CurrentCommandOutput05 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput UPDATE @CurrentDirectories SET CleanupCompleted = 1, - CleanupOutput = @CurrentCommandOutput05 + CleanupOutput = @CurrentCommandOutput WHERE ID = @CurrentDirectoryID SET @CurrentDirectoryID = NULL SET @CurrentDirectoryPath = NULL SET @CurrentCleanupDate = NULL - SET @CurrentCommand05 = NULL - - SET @CurrentCommandOutput05 = NULL - - SET @CurrentCommandType05 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL END END END @@ -3598,12 +3623,12 @@ BEGIN SET @CurrentAllocatedExtentPageCount = NULL SET @CurrentModifiedExtentPageCount = NULL - SET @CurrentCommand03 = NULL - SET @CurrentCommand07 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL - SET @CurrentCommandOutput03 = NULL - - SET @CurrentCommandType03 = NULL + SET @CurrentBackupOutput = NULL DELETE FROM @CurrentDirectories DELETE FROM @CurrentURLs @@ -3672,7 +3697,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-09 23:10:28 //-- + --// Version: 2020-01-11 12:40:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3725,32 +3750,17 @@ BEGIN DECLARE @CurrentObjectType nvarchar(max) DECLARE @CurrentObjectExists bit - DECLARE @CurrentCommand01 nvarchar(max) - DECLARE @CurrentCommand02 nvarchar(max) - DECLARE @CurrentCommand03 nvarchar(max) - DECLARE @CurrentCommand04 nvarchar(max) - DECLARE @CurrentCommand05 nvarchar(max) - DECLARE @CurrentCommand06 nvarchar(max) - DECLARE @CurrentCommand07 nvarchar(max) - DECLARE @CurrentCommand08 nvarchar(max) - DECLARE @CurrentCommand09 nvarchar(max) - - DECLARE @CurrentCommandOutput01 int - DECLARE @CurrentCommandOutput04 int - DECLARE @CurrentCommandOutput05 int - DECLARE @CurrentCommandOutput08 int - DECLARE @CurrentCommandOutput09 int - - DECLARE @CurrentCommandType01 nvarchar(max) - DECLARE @CurrentCommandType04 nvarchar(max) - DECLARE @CurrentCommandType05 nvarchar(max) - DECLARE @CurrentCommandType08 nvarchar(max) - DECLARE @CurrentCommandType09 nvarchar(max) + DECLARE @CurrentDatabaseContext nvarchar(max) + DECLARE @CurrentCommand nvarchar(max) + DECLARE @CurrentCommandOutput int + DECLARE @CurrentCommandType nvarchar(max) DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, - [Message] nvarchar(max)) + [Message] nvarchar(max) NOT NULL, + Severity int NOT NULL) DECLARE @CurrentMessage nvarchar(max) + DECLARE @CurrentSeverity int DECLARE @tmpDatabases TABLE (ID int IDENTITY, DatabaseName nvarchar(max), @@ -3897,56 +3907,56 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16 END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16 END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16 END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 END 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') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16 END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16 END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16 END IF @@TRANCOUNT <> 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The transaction count is not 0.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The transaction count is not 0.', 16 END ---------------------------------------------------------------------------------------------------- @@ -4073,8 +4083,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Databases is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Databases is not supported.', 16 END ---------------------------------------------------------------------------------------------------- @@ -4168,20 +4178,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16 END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16 END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16 END ---------------------------------------------------------------------------------------------------- @@ -4319,116 +4329,116 @@ BEGIN IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) OR EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) OR NOT EXISTS (SELECT * FROM @SelectedCheckCommands) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG'))) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE'))) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CheckCommands is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @CheckCommands is not supported.', 16 END IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @PhysicalOnly is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @PhysicalOnly is not supported.', 16 END IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @NoIndex is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @NoIndex is not supported.', 16 END IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL OR (@ExtendedLogicalChecks = 'Y' AND NOT @Version >= 10) OR (@PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @ExtendedLogicalChecks is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @ExtendedLogicalChecks is not supported.', 16 END IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @TabLock is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @TabLock is not supported.', 16 END IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) OR (@FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups)) OR (@FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP')) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FileGroups is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FileGroups is not supported.', 16 END IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) OR (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) OR (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Objects is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Objects is not supported.', 16 END IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MaxDOP is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MaxDOP is not supported.', 16 END IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @AvailabilityGroupReplicas is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @AvailabilityGroupReplicas is not supported.', 16 END IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Updateability is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Updateability is not supported.', 16 END IF @TimeLimit < 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @TimeLimit is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @TimeLimit is not supported.', 16 END IF @LockTimeout < 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LockTimeout is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LockTimeout is not supported.', 16 END IF @LockMessageSeverity NOT IN(10,16) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16 END IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @StringDelimiter is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LogToTable is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LogToTable is not supported.', 16 END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Execute is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Execute is not supported.', 16 END IF EXISTS(SELECT * FROM @Errors) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.', 16 END ---------------------------------------------------------------------------------------------------- @@ -4442,8 +4452,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -4453,8 +4463,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -4464,8 +4474,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -4475,8 +4485,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -4487,8 +4497,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -4499,8 +4509,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END ---------------------------------------------------------------------------------------------------- @@ -4509,33 +4519,33 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16 END ---------------------------------------------------------------------------------------------------- --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor - FETCH ErrorCursor INTO @CurrentMessage + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity WHILE @@FETCH_STATUS = 0 BEGIN - RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR('%s', @CurrentSeverity, 1, @CurrentMessage) WITH NOWAIT RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT - FETCH NEXT FROM ErrorCursor INTO @CurrentMessage + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity END CLOSE ErrorCursor DEALLOCATE ErrorCursor - IF EXISTS (SELECT * FROM @Errors) + IF EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) BEGIN SET @ReturnCode = 50000 GOTO Logging @@ -4933,32 +4943,34 @@ BEGIN -- Check database IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKDB') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommandType01 = 'DBCC_CHECKDB' - - SET @CurrentCommand01 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand01 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand01 += 'DBCC CHECKDB (' + QUOTENAME(@CurrentDatabaseName) - IF @NoIndex = 'Y' SET @CurrentCommand01 += ', NOINDEX' - SET @CurrentCommand01 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'N' SET @CurrentCommand01 += ', DATA_PURITY' - IF @PhysicalOnly = 'Y' SET @CurrentCommand01 += ', PHYSICAL_ONLY' - IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand01 += ', EXTENDED_LOGICAL_CHECKS' - IF @TabLock = 'Y' SET @CurrentCommand01 += ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand01 += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) - - EXECUTE @CurrentCommandOutput01 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand01, @CommandType = @CurrentCommandType01, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + SET @CurrentDatabaseContext = CASE WHEN SERVERPROPERTY('EngineEdition') = 5 THEN @CurrentDatabaseName ELSE 'master' END + + SET @CurrentCommandType = 'DBCC_CHECKDB' + + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'DBCC CHECKDB (' + QUOTENAME(@CurrentDatabaseName) + IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' + SET @CurrentCommand += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @PhysicalOnly = 'N' SET @CurrentCommand += ', DATA_PURITY' + IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' + IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand += ', EXTENDED_LOGICAL_CHECKS' + IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput01 = @Error - IF @CurrentCommandOutput01 <> 0 SET @ReturnCode = @CurrentCommandOutput01 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput END -- Check filegroups IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommand02 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' INSERT INTO @tmpFileGroups (FileGroupID, FileGroupName, [Order], Selected, Completed) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand02 + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -5034,12 +5046,12 @@ BEGIN END -- Does the filegroup exist? - SET @CurrentCommand03 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand03 += 'IF EXISTS(SELECT * FROM sys.filegroups filegroups WHERE [type] <> ''FX'' AND filegroups.data_space_id = @ParamFileGroupID AND filegroups.[name] = @ParamFileGroupName) BEGIN SET @ParamFileGroupExists = 1 END' + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'IF EXISTS(SELECT * FROM sys.filegroups filegroups WHERE [type] <> ''FX'' AND filegroups.data_space_id = @ParamFileGroupID AND filegroups.[name] = @ParamFileGroupName) BEGIN SET @ParamFileGroupExists = 1 END' BEGIN TRY - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand03, @params = N'@ParamFileGroupID int, @ParamFileGroupName sysname, @ParamFileGroupExists bit OUTPUT', @ParamFileGroupID = @CurrentFileGroupID, @ParamFileGroupName = @CurrentFileGroupName, @ParamFileGroupExists = @CurrentFileGroupExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamFileGroupID int, @ParamFileGroupName sysname, @ParamFileGroupExists bit OUTPUT', @ParamFileGroupID = @CurrentFileGroupID, @ParamFileGroupName = @CurrentFileGroupName, @ParamFileGroupExists = @CurrentFileGroupExists OUTPUT IF @CurrentFileGroupExists IS NULL SET @CurrentFileGroupExists = 0 END TRY @@ -5057,21 +5069,23 @@ BEGIN IF @CurrentFileGroupExists = 1 BEGIN - SET @CurrentCommandType04 = 'DBCC_CHECKFILEGROUP' - - SET @CurrentCommand04 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand04 += 'DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) - IF @NoIndex = 'Y' SET @CurrentCommand04 += ', NOINDEX' - SET @CurrentCommand04 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'Y' SET @CurrentCommand04 += ', PHYSICAL_ONLY' - IF @TabLock = 'Y' SET @CurrentCommand04 += ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand04 += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) - - EXECUTE @CurrentCommandOutput04 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand04, @CommandType = @CurrentCommandType04, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + SET @CurrentDatabaseContext = @CurrentDatabaseName + + SET @CurrentCommandType = 'DBCC_CHECKFILEGROUP' + + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) + IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' + SET @CurrentCommand += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' + IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput04 = @Error - IF @CurrentCommandOutput04 <> 0 SET @ReturnCode = @CurrentCommandOutput04 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput END UPDATE @tmpFileGroups @@ -5085,39 +5099,39 @@ BEGIN SET @CurrentFileGroupName = NULL SET @CurrentFileGroupExists = NULL - SET @CurrentCommand03 = NULL - SET @CurrentCommand04 = NULL - - SET @CurrentCommandOutput04 = NULL - - SET @CurrentCommandType04 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL END END -- Check disk space allocation structures IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKALLOC') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommandType05 = 'DBCC_CHECKALLOC' + SET @CurrentDatabaseContext = CASE WHEN SERVERPROPERTY('EngineEdition') = 5 THEN @CurrentDatabaseName ELSE 'master' END + + SET @CurrentCommandType = 'DBCC_CHECKALLOC' - SET @CurrentCommand05 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand05 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand05 += 'DBCC CHECKALLOC (' + QUOTENAME(@CurrentDatabaseName) - SET @CurrentCommand05 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @TabLock = 'Y' SET @CurrentCommand05 += ', TABLOCK' + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'DBCC CHECKALLOC (' + QUOTENAME(@CurrentDatabaseName) + SET @CurrentCommand += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' - EXECUTE @CurrentCommandOutput05 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand05, @CommandType = @CurrentCommandType05, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput05 = @Error - IF @CurrentCommandOutput05 <> 0 SET @ReturnCode = @CurrentCommandOutput05 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput END -- Check objects IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommand06 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, [Order], Selected, Completed) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand06 + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -5197,12 +5211,12 @@ BEGIN END -- Does the object exist? - SET @CurrentCommand07 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand07 += 'IF EXISTS(SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType) BEGIN SET @ParamObjectExists = 1 END' + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'IF EXISTS(SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType) BEGIN SET @ParamObjectExists = 1 END' BEGIN TRY - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand07, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamObjectExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamObjectExists = @CurrentObjectExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamObjectExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamObjectExists = @CurrentObjectExists OUTPUT IF @CurrentObjectExists IS NULL SET @CurrentObjectExists = 0 END TRY @@ -5220,23 +5234,25 @@ BEGIN IF @CurrentObjectExists = 1 BEGIN - SET @CurrentCommandType08 = 'DBCC_CHECKTABLE' - - SET @CurrentCommand08 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand08 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand08 += 'DBCC CHECKTABLE (''' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + '''' - IF @NoIndex = 'Y' SET @CurrentCommand08 += ', NOINDEX' - SET @CurrentCommand08 += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'N' SET @CurrentCommand08 += ', DATA_PURITY' - IF @PhysicalOnly = 'Y' SET @CurrentCommand08 += ', PHYSICAL_ONLY' - IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand08 += ', EXTENDED_LOGICAL_CHECKS' - IF @TabLock = 'Y' SET @CurrentCommand08 += ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand08 += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) - - EXECUTE @CurrentCommandOutput08 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand08, @CommandType = @CurrentCommandType08, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @LogToTable = @LogToTable, @Execute = @Execute + SET @CurrentDatabaseContext = @CurrentDatabaseName + + SET @CurrentCommandType = 'DBCC_CHECKTABLE' + + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'DBCC CHECKTABLE (''' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + '''' + IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' + SET @CurrentCommand += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' + IF @PhysicalOnly = 'N' SET @CurrentCommand += ', DATA_PURITY' + IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' + IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand += ', EXTENDED_LOGICAL_CHECKS' + IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput08 = @Error - IF @CurrentCommandOutput08 <> 0 SET @ReturnCode = @CurrentCommandOutput08 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput END UPDATE @tmpObjects @@ -5253,29 +5269,29 @@ BEGIN SET @CurrentObjectType = NULL SET @CurrentObjectExists = NULL - SET @CurrentCommand07 = NULL - SET @CurrentCommand08 = NULL - - SET @CurrentCommandOutput08 = NULL - - SET @CurrentCommandType08 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL END END -- Check catalog IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommandType09 = 'DBCC_CHECKCATALOG' + SET @CurrentDatabaseContext = CASE WHEN SERVERPROPERTY('EngineEdition') = 5 THEN @CurrentDatabaseName ELSE 'master' END - SET @CurrentCommand09 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand09 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand09 += 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) - SET @CurrentCommand09 += ') WITH NO_INFOMSGS' + SET @CurrentCommandType = 'DBCC_CHECKCATALOG' - EXECUTE @CurrentCommandOutput09 = [dbo].[CommandExecute] @DatabaseContext = 'master', @Command = @CurrentCommand09, @CommandType = @CurrentCommandType09, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) + SET @CurrentCommand += ') WITH NO_INFOMSGS' + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput09 = @Error - IF @CurrentCommandOutput09 <> 0 SET @ReturnCode = @CurrentCommandOutput09 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput END END @@ -5324,19 +5340,10 @@ BEGIN SET @CurrentIsPreferredBackupReplica = NULL SET @CurrentDatabaseMirroringRole = NULL - SET @CurrentCommand01 = NULL - SET @CurrentCommand02 = NULL - SET @CurrentCommand05 = NULL - SET @CurrentCommand06 = NULL - SET @CurrentCommand09 = NULL - - SET @CurrentCommandOutput01 = NULL - SET @CurrentCommandOutput05 = NULL - SET @CurrentCommandOutput09 = NULL - - SET @CurrentCommandType01 = NULL - SET @CurrentCommandType05 = NULL - SET @CurrentCommandType09 = NULL + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL DELETE FROM @tmpFileGroups DELETE FROM @tmpObjects @@ -5417,7 +5424,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-09 23:10:28 //-- + --// Version: 2020-01-11 12:40:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5461,30 +5468,19 @@ BEGIN DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentDatabaseMirroringRole nvarchar(max) - DECLARE @CurrentCommand01 nvarchar(max) - DECLARE @CurrentCommand02 nvarchar(max) - DECLARE @CurrentCommand03 nvarchar(max) - DECLARE @CurrentCommand04 nvarchar(max) - DECLARE @CurrentCommand05 nvarchar(max) - DECLARE @CurrentCommand06 nvarchar(max) - DECLARE @CurrentCommand07 nvarchar(max) - - DECLARE @CurrentCommandOutput06 int - DECLARE @CurrentCommandOutput07 int - - DECLARE @CurrentCommandType06 nvarchar(max) - DECLARE @CurrentCommandType07 nvarchar(max) - - DECLARE @CurrentComment06 nvarchar(max) - DECLARE @CurrentComment07 nvarchar(max) - - DECLARE @CurrentExtendedInfo06 xml - DECLARE @CurrentExtendedInfo07 xml + DECLARE @CurrentDatabaseContext nvarchar(max) + DECLARE @CurrentCommand nvarchar(max) + DECLARE @CurrentCommandOutput int + DECLARE @CurrentCommandType nvarchar(max) + DECLARE @CurrentComment nvarchar(max) + DECLARE @CurrentExtendedInfo xml DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, - [Message] nvarchar(max)) + [Message] nvarchar(max) NOT NULL, + Severity int NOT NULL) DECLARE @CurrentMessage nvarchar(max) + DECLARE @CurrentSeverity int DECLARE @CurrentIxID int DECLARE @CurrentIxOrder int @@ -5717,56 +5713,56 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16 END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16 END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16 END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 END 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') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16 END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16 END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16 END IF @@TRANCOUNT <> 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The transaction count is not 0.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The transaction count is not 0.', 16 END ---------------------------------------------------------------------------------------------------- @@ -5892,8 +5888,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Databases is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Databases is not supported.', 16 END ---------------------------------------------------------------------------------------------------- @@ -5987,20 +5983,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16 END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16 END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16 END ---------------------------------------------------------------------------------------------------- @@ -6134,214 +6130,214 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FragmentationLow is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FragmentationLow is not supported.', 16 END IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FragmentationMedium is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FragmentationMedium is not supported.', 16 END IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'High' AND [Action] NOT IN(SELECT * FROM @Actions)) OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FragmentationHigh is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FragmentationHigh is not supported.', 16 END IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 >= @FragmentationLevel2 OR @FragmentationLevel1 IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FragmentationLevel1 is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FragmentationLevel1 is not supported.', 16 END IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 <= @FragmentationLevel1 OR @FragmentationLevel2 IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FragmentationLevel2 is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FragmentationLevel2 is not supported.', 16 END IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MinNumberOfPages is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MinNumberOfPages is not supported.', 16 END IF @MaxNumberOfPages < 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MaxNumberOfPages is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MaxNumberOfPages is not supported.', 16 END IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @SortInTempdb is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @SortInTempdb is not supported.', 16 END IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MaxDOP is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MaxDOP is not supported.', 16 END IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @FillFactor is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @FillFactor is not supported.', 16 END IF @PadIndex NOT IN('Y','N') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @PadIndex is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @PadIndex is not supported.', 16 END IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LOBCompaction is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LOBCompaction is not supported.', 16 END IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @UpdateStatistics is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @UpdateStatistics is not supported.', 16 END IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @OnlyModifiedStatistics is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @OnlyModifiedStatistics is not supported.', 16 END IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @StatisticsModificationLevel is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @StatisticsModificationLevel is not supported.', 16 END IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.', 16 END IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @StatisticsSample is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @StatisticsSample is not supported.', 16 END IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL OR (@StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @StatisticsResample is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @StatisticsResample is not supported.', 16 END IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @PartitionLevel is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @PartitionLevel is not supported.', 16 END IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @MSShippedObjects is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @MSShippedObjects is not supported.', 16 END IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) OR (@Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes)) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Indexes is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Indexes is not supported.', 16 END IF @TimeLimit < 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @TimeLimit is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @TimeLimit is not supported.', 16 END IF @Delay < 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Delay is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Delay is not supported.', 16 END IF @WaitAtLowPriorityMaxDuration < 0 OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @WaitAtLowPriorityAbortAfterWait IS NULL) OR (@WaitAtLowPriorityMaxDuration IS NULL AND @WaitAtLowPriorityAbortAfterWait IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16 END IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16 END IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL OR (@Resumable = 'Y' AND NOT (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8))) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Resumable is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Resumable is not supported.', 16 END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.', 16 END IF @LockTimeout < 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LockTimeout is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LockTimeout is not supported.', 16 END IF @LockMessageSeverity NOT IN(10,16) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16 END IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @StringDelimiter is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 END IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 END IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LogToTable is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @LogToTable is not supported.', 16 END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Execute is not supported.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The value for the parameter @Execute is not supported.', 16 END IF EXISTS(SELECT * FROM @Errors) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16 END ---------------------------------------------------------------------------------------------------- @@ -6355,8 +6351,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -6366,8 +6362,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -6377,8 +6373,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END SET @ErrorMessage = '' @@ -6389,33 +6385,33 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.' + INSERT INTO @Errors ([Message], Severity) + SELECT 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 END ---------------------------------------------------------------------------------------------------- --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor - FETCH ErrorCursor INTO @CurrentMessage + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity WHILE @@FETCH_STATUS = 0 BEGIN - RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR('%s', @CurrentSeverity, 1, @CurrentMessage) WITH NOWAIT RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT - FETCH NEXT FROM ErrorCursor INTO @CurrentMessage + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity END CLOSE ErrorCursor DEALLOCATE ErrorCursor - IF EXISTS (SELECT * FROM @Errors) + IF EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) BEGIN SET @ReturnCode = 50000 GOTO Logging @@ -6737,13 +6733,13 @@ BEGIN -- Select indexes in the current database IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommand01 = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, IsComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + ' FROM (' IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') BEGIN - SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID' + SET @CurrentCommand = @CurrentCommand + 'SELECT schemas.[schema_id] AS SchemaID' + ', schemas.[name] AS SchemaName' + ', objects.[object_id] AS ObjectID' + ', objects.[name] AS ObjectName' @@ -6790,11 +6786,11 @@ BEGIN + ' LEFT OUTER JOIN sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' IF @PartitionLevel = 'Y' BEGIN - SET @CurrentCommand01 = @CurrentCommand01 + ' LEFT OUTER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' + SET @CurrentCommand = @CurrentCommand + ' LEFT OUTER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' + ' LEFT OUTER JOIN (SELECT partitions.[object_id], partitions.index_id, COUNT(DISTINCT partitions.partition_number) AS partition_count FROM sys.partitions partitions GROUP BY partitions.[object_id], partitions.index_id) IndexPartitions ON partitions.[object_id] = IndexPartitions.[object_id] AND partitions.[index_id] = IndexPartitions.[index_id]' END - SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,3,4,5,6,7)' + ' AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0' @@ -6802,12 +6798,12 @@ BEGIN IF (EXISTS(SELECT * FROM @ActionsPreferred) AND @UpdateStatistics = 'COLUMNS') OR @UpdateStatistics = 'ALL' BEGIN - SET @CurrentCommand01 = @CurrentCommand01 + ' UNION ' + SET @CurrentCommand = @CurrentCommand + ' UNION ' END IF @UpdateStatistics IN('ALL','COLUMNS') BEGIN - SET @CurrentCommand01 = @CurrentCommand01 + 'SELECT schemas.[schema_id] AS SchemaID' + SET @CurrentCommand = @CurrentCommand + 'SELECT schemas.[schema_id] AS SchemaID' + ', schemas.[name] AS SchemaName' + ', objects.[object_id] AS ObjectID' + ', objects.[name] AS ObjectName' @@ -6841,18 +6837,18 @@ BEGIN IF @PartitionLevelStatistics = 1 BEGIN - SET @CurrentCommand01 = @CurrentCommand01 + ' OUTER APPLY sys.dm_db_incremental_stats_properties(stats.object_id, stats.stats_id) dm_db_incremental_stats_properties' + SET @CurrentCommand = @CurrentCommand + ' OUTER APPLY sys.dm_db_incremental_stats_properties(stats.object_id, stats.stats_id) dm_db_incremental_stats_properties' END - SET @CurrentCommand01 = @CurrentCommand01 + ' WHERE objects.[type] IN(''U'',''V'')' + SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id)' END - SET @CurrentCommand01 = @CurrentCommand01 + ') IndexesStatistics' + SET @CurrentCommand = @CurrentCommand + ') IndexesStatistics' INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, IsImageText, IsNewLOB, IsFileStream, IsColumnStore, IsComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand01 + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 BEGIN @@ -6982,15 +6978,15 @@ BEGIN -- Does the index exist? IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) BEGIN - SET @CurrentCommand02 = '' + SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand02 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - IF @CurrentIsPartition = 0 SET @CurrentCommand02 += 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' - IF @CurrentIsPartition = 1 SET @CurrentCommand02 += 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' + IF @CurrentIsPartition = 0 SET @CurrentCommand += 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType) BEGIN SET @ParamIndexExists = 1 END' + IF @CurrentIsPartition = 1 SET @CurrentCommand += 'IF EXISTS(SELECT * FROM sys.indexes indexes INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id WHERE objects.[type] IN(''U'',''V'') AND indexes.[type] IN(1,2,3,4,5,6,7) AND indexes.is_disabled = 0 AND indexes.is_hypothetical = 0 AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND indexes.index_id = @ParamIndexID AND indexes.[name] = @ParamIndexName AND indexes.[type] = @ParamIndexType AND partitions.partition_id = @ParamPartitionID AND partitions.partition_number = @ParamPartitionNumber) BEGIN SET @ParamIndexExists = 1 END' BEGIN TRY - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand02, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamIndexID int, @ParamIndexName sysname, @ParamIndexType int, @ParamPartitionID bigint, @ParamPartitionNumber int, @ParamIndexExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamIndexID = @CurrentIndexID, @ParamIndexName = @CurrentIndexName, @ParamIndexType = @CurrentIndexType, @ParamPartitionID = @CurrentPartitionID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamIndexExists = @CurrentIndexExists OUTPUT IF @CurrentIndexExists IS NULL BEGIN @@ -7016,14 +7012,14 @@ BEGIN -- Does the statistics exist? IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL BEGIN - SET @CurrentCommand03 = '' + SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand03 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand03 += 'IF EXISTS(SELECT * FROM sys.stats stats INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' + SET @CurrentCommand += 'IF EXISTS(SELECT * FROM sys.stats stats INNER JOIN sys.objects objects ON stats.[object_id] = objects.[object_id] INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] IN(''U'',''V'')' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND schemas.[schema_id] = @ParamSchemaID AND schemas.[name] = @ParamSchemaName AND objects.[object_id] = @ParamObjectID AND objects.[name] = @ParamObjectName AND objects.[type] = @ParamObjectType AND stats.stats_id = @ParamStatisticsID AND stats.[name] = @ParamStatisticsName) BEGIN SET @ParamStatisticsExists = 1 END' BEGIN TRY - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand03, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamSchemaID int, @ParamSchemaName sysname, @ParamObjectID int, @ParamObjectName sysname, @ParamObjectType sysname, @ParamStatisticsID int, @ParamStatisticsName sysname, @ParamStatisticsExists bit OUTPUT', @ParamSchemaID = @CurrentSchemaID, @ParamSchemaName = @CurrentSchemaName, @ParamObjectID = @CurrentObjectID, @ParamObjectName = @CurrentObjectName, @ParamObjectType = @CurrentObjectType, @ParamStatisticsID = @CurrentStatisticsID, @ParamStatisticsName = @CurrentStatisticsName, @ParamStatisticsExists = @CurrentStatisticsExists OUTPUT IF @CurrentStatisticsExists IS NULL BEGIN @@ -7049,26 +7045,26 @@ BEGIN -- Has the data in the statistics been modified since the statistics was last updated? IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL BEGIN - SET @CurrentCommand04 = '' + SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand04 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN - SET @CurrentCommand04 += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' + SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' END ELSE IF (@Version >= 10.504000 AND @Version < 11) OR @Version >= 11.03000 BEGIN - SET @CurrentCommand04 += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' + SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' END ELSE BEGIN - SET @CurrentCommand04 += 'SELECT @ParamRowCount = rowcnt, @ParamModificationCounter = rowmodctr FROM sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID' + SET @CurrentCommand += 'SELECT @ParamRowCount = rowcnt, @ParamModificationCounter = rowmodctr FROM sys.sysindexes sysindexes WHERE sysindexes.[id] = @ParamObjectID AND sysindexes.[indid] = @ParamStatisticsID' END BEGIN TRY - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand04, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamPartitionNumber int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT IF @CurrentRowCount IS NULL SET @CurrentRowCount = 0 IF @CurrentModificationCounter IS NULL SET @CurrentModificationCounter = 0 @@ -7094,14 +7090,14 @@ BEGIN AND EXISTS(SELECT * FROM @ActionsPreferred) AND (EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) OR @MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) BEGIN - SET @CurrentCommand05 = '' + SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand05 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand05 += 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + SET @CurrentCommand += 'SELECT @ParamFragmentationLevel = MAX(avg_fragmentation_in_percent), @ParamPageCount = SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, @ParamPartitionNumber, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' BEGIN TRY - EXECUTE sp_executesql @stmt = @CurrentCommand05, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int, @ParamPartitionNumber int, @ParamFragmentationLevel float OUTPUT, @ParamPageCount bigint OUTPUT', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamFragmentationLevel = @CurrentFragmentationLevel OUTPUT, @ParamPageCount = @CurrentPageCount OUTPUT END TRY BEGIN CATCH SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The index ' + QUOTENAME(@CurrentIndexName) + ' on the object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The page_count and avg_fragmentation_in_percent could not be checked.' ELSE '' END @@ -7232,57 +7228,59 @@ BEGIN -- Create index comment IF @CurrentIndexID IS NOT NULL BEGIN - SET @CurrentComment06 = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment06 += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' - SET @CurrentComment06 += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 += 'NewLOB: ' + CASE WHEN @CurrentIsNewLOB = 1 THEN 'Yes' WHEN @CurrentIsNewLOB = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 11 SET @CurrentComment06 += 'ColumnStore: ' + CASE WHEN @CurrentIsColumnStore = 1 THEN 'Yes' WHEN @CurrentIsColumnStore = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment06 += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 += 'AllowPageLocks: ' + CASE WHEN @CurrentAllowPageLocks = 1 THEN 'Yes' WHEN @CurrentAllowPageLocks = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment06 += 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar),'N/A') + ', ' - SET @CurrentComment06 += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar),'N/A') + SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'NewLOB: ' + CASE WHEN @CurrentIsNewLOB = 1 THEN 'Yes' WHEN @CurrentIsNewLOB = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 11 SET @CurrentComment += 'ColumnStore: ' + CASE WHEN @CurrentIsColumnStore = 1 THEN 'Yes' WHEN @CurrentIsColumnStore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'AllowPageLocks: ' + CASE WHEN @CurrentAllowPageLocks = 1 THEN 'Yes' WHEN @CurrentAllowPageLocks = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar),'N/A') + ', ' + SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar),'N/A') END IF @CurrentIndexID IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) BEGIN - SET @CurrentExtendedInfo06 = (SELECT * - FROM (SELECT CAST(@CurrentPageCount AS nvarchar) AS [PageCount], - CAST(@CurrentFragmentationLevel AS nvarchar) AS Fragmentation - ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentPageCount AS nvarchar) AS [PageCount], + CAST(@CurrentFragmentationLevel AS nvarchar) AS Fragmentation + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END -- Create statistics comment IF @CurrentStatisticsID IS NOT NULL BEGIN - SET @CurrentComment07 = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment07 += 'IndexType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' - IF @CurrentIndexID IS NOT NULL SET @CurrentComment07 += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' - SET @CurrentComment07 += 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Y' WHEN @CurrentIsIncremental = 0 THEN 'N' ELSE 'N/A' END + ', ' - SET @CurrentComment07 += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' - SET @CurrentComment07 += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') + SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'IndexType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' + IF @CurrentIndexID IS NOT NULL SET @CurrentComment += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Y' WHEN @CurrentIsIncremental = 0 THEN 'N' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' + SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') END IF @CurrentStatisticsID IS NOT NULL AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) BEGIN - SET @CurrentExtendedInfo07 = (SELECT * - FROM (SELECT CAST(@CurrentRowCount AS nvarchar) AS [RowCount], - CAST(@CurrentModificationCounter AS nvarchar) AS ModificationCounter - ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentRowCount AS nvarchar) AS [RowCount], + CAST(@CurrentModificationCounter AS nvarchar) AS ModificationCounter + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END IF @CurrentIndexID IS NOT NULL AND @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommandType06 = 'ALTER_INDEX' + SET @CurrentDatabaseContext = @CurrentDatabaseName + + SET @CurrentCommandType = 'ALTER_INDEX' - SET @CurrentCommand06 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand06 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand06 += 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) - IF @CurrentResumableIndexOperation = 1 SET @CurrentCommand06 += ' RESUME' - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 += ' REBUILD' - IF @CurrentAction IN('INDEX_REORGANIZE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 += ' REORGANIZE' - IF @CurrentIsPartition = 1 AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand06 += ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'ALTER INDEX ' + QUOTENAME(@CurrentIndexName) + ' ON ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + IF @CurrentResumableIndexOperation = 1 SET @CurrentCommand += ' RESUME' + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand += ' REBUILD' + IF @CurrentAction IN('INDEX_REORGANIZE') AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand += ' REORGANIZE' + IF @CurrentIsPartition = 1 AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand += ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar) IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN @@ -7381,12 +7379,12 @@ BEGIN SET @CurrentAlterIndexWithClause = @CurrentAlterIndexWithClause + ')' END - IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand06 += @CurrentAlterIndexWithClause + IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand += @CurrentAlterIndexWithClause - EXECUTE @CurrentCommandOutput06 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand06, @CommandType = @CurrentCommandType06, @Mode = 2, @Comment = @CurrentComment06, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo06, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput06 = @Error - IF @CurrentCommandOutput06 <> 0 SET @ReturnCode = @CurrentCommandOutput06 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput IF @Delay > 0 BEGIN @@ -7399,11 +7397,13 @@ BEGIN IF @CurrentStatisticsID IS NOT NULL AND @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentCommandType07 = 'UPDATE_STATISTICS' + SET @CurrentDatabaseContext = @CurrentDatabaseName - SET @CurrentCommand07 = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand07 = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' - SET @CurrentCommand07 += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) + SET @CurrentCommandType = 'UPDATE_STATISTICS' + + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + SET @CurrentCommand += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) IF @CurrentMaxDOP IS NOT NULL AND ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.030154) BEGIN @@ -7462,14 +7462,14 @@ BEGIN SET @CurrentUpdateStatisticsWithClause = LEFT(@CurrentUpdateStatisticsWithClause,LEN(@CurrentUpdateStatisticsWithClause) - 1) END - IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand07 += @CurrentUpdateStatisticsWithClause + IF @CurrentUpdateStatisticsWithClause IS NOT NULL SET @CurrentCommand += @CurrentUpdateStatisticsWithClause - IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand07 += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' - EXECUTE @CurrentCommandOutput07 = [dbo].[CommandExecute] @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand07, @CommandType = @CurrentCommandType07, @Mode = 2, @Comment = @CurrentComment07, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo07, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR - IF @Error <> 0 SET @CurrentCommandOutput07 = @Error - IF @CurrentCommandOutput07 <> 0 SET @ReturnCode = @CurrentCommandOutput07 + IF @Error <> 0 SET @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput END NoAction: @@ -7483,24 +7483,13 @@ BEGIN AND ID = @CurrentIxID -- Clear variables - SET @CurrentCommand02 = NULL - SET @CurrentCommand03 = NULL - SET @CurrentCommand04 = NULL - SET @CurrentCommand05 = NULL - SET @CurrentCommand06 = NULL - SET @CurrentCommand07 = NULL - - SET @CurrentCommandOutput06 = NULL - SET @CurrentCommandOutput07 = NULL - - SET @CurrentCommandType06 = NULL - SET @CurrentCommandType07 = NULL - - SET @CurrentComment06 = NULL - SET @CurrentComment07 = NULL + SET @CurrentDatabaseContext = NULL - SET @CurrentExtendedInfo06 = NULL - SET @CurrentExtendedInfo07 = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL + SET @CurrentComment = NULL + SET @CurrentExtendedInfo = NULL SET @CurrentIxID = NULL SET @CurrentIxOrder = NULL @@ -7599,7 +7588,7 @@ BEGIN SET @CurrentAvailabilityGroupRole = NULL SET @CurrentDatabaseMirroringRole = NULL - SET @CurrentCommand01 = NULL + SET @CurrentCommand = NULL DELETE FROM @tmpIndexesStatistics From 71c20cdf65d2036558c49cabe79c22145f222c03 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 11 Jan 2020 12:57:32 +0100 Subject: [PATCH 148/188] Add files via upload From f7c1709db35586e1f2c0726a702122ca91892843 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 11 Jan 2020 13:11:36 +0100 Subject: [PATCH 149/188] Add files via upload --- .gitattributes | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitattributes b/.gitattributes index df745445..5bdace7f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1 @@ -# linguist overrides *.sql linguist-language=TSQL From a6b9d7573b7c518282a44d5a8697c6231b02f393 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 11 Jan 2020 14:05:22 +0100 Subject: [PATCH 150/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 147 +++++++++++++++++++------ DatabaseIntegrityCheck.sql | 32 ++++-- IndexOptimize.sql | 31 ++++-- MaintenanceSolution.sql | 214 ++++++++++++++++++++++++++++--------- 5 files changed, 325 insertions(+), 101 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index d58b5483..a74c3f3c 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 12:40:32 //-- + --// Version: 2020-01-11 14:01:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 808cba6b..0cd1391d 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 12:40:32 //-- + --// Version: 2020-01-11 14:01:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1005,7 +1005,9 @@ BEGIN SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.', 16 END - IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @Verify NOT IN ('Y','N') OR @Verify IS NULL + OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') + OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Verify is not supported.', 16 @@ -1065,7 +1067,11 @@ BEGIN SELECT 'The value for the parameter @CleanupMode is not supported.', 16 END - IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) + IF @Compress NOT IN ('Y','N') OR @Compress IS NULL + OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) + OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) + OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) + OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Compress is not supported.', 16 @@ -1083,7 +1089,8 @@ BEGIN SELECT 'The value for the parameter @ChangeBackupType is not supported.', 16 END - IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') + IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') + OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @BackupSoftware is not supported.', 16 @@ -1119,25 +1126,43 @@ BEGIN SELECT 'The value for the parameter @CheckSum is not supported.', 16 END - IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) + OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') + OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') + OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) + OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @BlockSize is not supported.', 16 END - IF @BufferCount <= 0 OR @BufferCount > 2147483647 OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE') + IF @BufferCount <= 0 OR @BufferCount > 2147483647 + OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') + OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @BufferCount is not supported.', 16 END - IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 + OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') + OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') + OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) + OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16 END - IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 + IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 + OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') + OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) + OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 + OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) + OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) + OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) + OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16 @@ -1191,61 +1216,87 @@ BEGIN SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16 END - IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) + OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 + OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) + OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) + OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @CompressionLevel is not supported.', 16 END - IF LEN(@Description) > 255 OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) + IF LEN(@Description) > 255 + OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) + OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Description is not supported.', 16 END - IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) OR (@BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32)) OR (@BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32)) OR (@BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64)) + IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) + OR (@BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32)) + OR (@BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32)) + OR (@BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64)) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Threads is not supported.', 16 END - IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) OR @Throttle < 1 OR @Throttle > 100 + IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) + OR @Throttle < 1 + OR @Throttle > 100 BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Throttle is not supported.', 16 END - IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL + OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) + OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Encrypt is not supported.', 16 END - IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) + OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) + OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) + OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) + OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16 END - IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL) OR (@ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate)) + IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) + OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL) + OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL) + OR (@ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate)) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @ServerCertificate is not supported.', 16 END - IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL) OR (@ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey)) + IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL) + OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL) + OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL) + OR (@ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey)) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.', 16 END - IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') + OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) + OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @EncryptionKey is not supported.', 16 END - IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL OR (@ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG') + IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL + OR (@ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.', 16 @@ -1257,19 +1308,27 @@ BEGIN SELECT 'The value for the parameter @OverrideBackupPreference is not supported.', 16 END - IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL OR (@NoRecovery = 'Y' AND @BackupType <> 'LOG') OR (@NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE') + IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL + OR (@NoRecovery = 'Y' AND @BackupType <> 'LOG') + OR (@NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @NoRecovery is not supported.', 16 END - IF (@URL IS NOT NULL AND @Directory IS NOT NULL) OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@URL IS NOT NULL AND @Version < 11.03339) OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) + IF (@URL IS NOT NULL AND @Directory IS NOT NULL) + OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) + OR (@URL IS NOT NULL AND @Version < 11.03339) + OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @URL is not supported.', 16 END - IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) + IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) + OR (@Credential IS NOT NULL AND @URL IS NULL) + OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) + OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Credential is not supported.', 16 @@ -1287,7 +1346,11 @@ BEGIN SELECT 'The value for the parameter @MirrorCleanupMode is not supported.', 16 END - IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @URL IS NULL) + IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) + OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) + OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) + OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) + OR (@MirrorURL IS NOT NULL AND @URL IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @MirrorURL is not supported.', 16 @@ -1299,13 +1362,16 @@ BEGIN SELECT 'The value for the parameter @Updateability is not supported.', 16 END - IF @AdaptiveCompression NOT IN('SIZE','SPEED') OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) + IF @AdaptiveCompression NOT IN('SIZE','SPEED') + OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @AdaptiveCompression is not supported.', 16 END - IF (@ModificationLevel IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count')) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') + IF (@ModificationLevel IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count')) + OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') + OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @ModificationLevel is not supported.', 16 @@ -1329,19 +1395,22 @@ BEGIN SELECT 'The parameters @TimeSinceLastLogBackup and @LogSizeSinceLastLogBackup can only be used together.', 16 END - IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) + OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16 END - IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) + OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16 END - IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) + OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16 @@ -1371,7 +1440,13 @@ BEGIN SELECT 'The value for the parameter @FileName is not supported.', 16 END - IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) OR @AvailabilityGroupFileName = '' OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' OR @AvailabilityGroupFileName LIKE '%/%' OR @AvailabilityGroupFileName LIKE '%\%' + IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) + OR @AvailabilityGroupFileName = '' + OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' + OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') + OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' + OR @AvailabilityGroupFileName LIKE '%/%' + OR @AvailabilityGroupFileName LIKE '%\%' BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16 @@ -1423,19 +1498,26 @@ BEGIN SELECT 'The value for the parameter @FileExtensionLog is not supported.', 16 END - IF @Init NOT IN('Y','N') OR @Init IS NULL OR (@Init = 'Y' AND @BackupType = 'LOG') OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @Init NOT IN('Y','N') OR @Init IS NULL + OR (@Init = 'Y' AND @BackupType = 'LOG') + OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Init is not supported.', 16 END - IF @Format NOT IN('Y','N') OR @Format IS NULL OR (@Format = 'Y' AND @BackupType = 'LOG') OR (@Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @Format NOT IN('Y','N') OR @Format IS NULL + OR (@Format = 'Y' AND @BackupType = 'LOG') + OR (@Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Format is not supported.', 16 END - IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL) OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED') OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG') + IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL + OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL) + OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED') + OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16 @@ -1465,7 +1547,8 @@ BEGIN SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 END - IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL + OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index bd4d3329..3824869f 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -38,7 +38,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 12:40:32 //-- + --// Version: 2020-01-11 14:01:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -668,7 +668,11 @@ BEGIN --// Check input parameters //-- ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) OR EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) OR NOT EXISTS (SELECT * FROM @SelectedCheckCommands) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG'))) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE'))) + IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) + OR EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) + OR NOT EXISTS (SELECT * FROM @SelectedCheckCommands) + OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG'))) + OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE'))) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @CheckCommands is not supported.', 16 @@ -686,7 +690,9 @@ BEGIN SELECT 'The value for the parameter @NoIndex is not supported.', 16 END - IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL OR (@ExtendedLogicalChecks = 'Y' AND NOT @Version >= 10) OR (@PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y') + IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL + OR (@ExtendedLogicalChecks = 'Y' AND NOT @Version >= 10) + OR (@PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @ExtendedLogicalChecks is not supported.', 16 @@ -698,19 +704,24 @@ BEGIN SELECT 'The value for the parameter @TabLock is not supported.', 16 END - IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) OR (@FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups)) OR (@FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP')) + IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) + OR (@FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups)) + OR (@FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP')) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @FileGroups is not supported.', 16 END - IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) OR (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) OR (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) + IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) + OR (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) + OR (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Objects is not supported.', 16 END - IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) + IF @MaxDOP < 0 OR @MaxDOP > 64 + OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @MaxDOP is not supported.', 16 @@ -752,13 +763,18 @@ BEGIN SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') + OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) + OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') + OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') + OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 END - IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL + OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 021ac85b..87b98b4c 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 12:40:32 //-- + --// Version: 2020-01-11 14:01:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -776,13 +776,17 @@ BEGIN SELECT 'The value for the parameter @FragmentationHigh is not supported.', 16 END - IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 >= @FragmentationLevel2 OR @FragmentationLevel1 IS NULL + IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 + OR @FragmentationLevel1 >= @FragmentationLevel2 + OR @FragmentationLevel1 IS NULL BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @FragmentationLevel1 is not supported.', 16 END - IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 <= @FragmentationLevel1 OR @FragmentationLevel2 IS NULL + IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 + OR @FragmentationLevel2 <= @FragmentationLevel1 + OR @FragmentationLevel2 IS NULL BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @FragmentationLevel2 is not supported.', 16 @@ -860,7 +864,8 @@ BEGIN SELECT 'The value for the parameter @StatisticsSample is not supported.', 16 END - IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL OR (@StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL) + IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL + OR (@StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @StatisticsResample is not supported.', 16 @@ -878,7 +883,8 @@ BEGIN SELECT 'The value for the parameter @MSShippedObjects is not supported.', 16 END - IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) OR (@Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes)) + IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) + OR (@Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes)) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Indexes is not supported.', 16 @@ -896,13 +902,18 @@ BEGIN SELECT 'The value for the parameter @Delay is not supported.', 16 END - IF @WaitAtLowPriorityMaxDuration < 0 OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @WaitAtLowPriorityAbortAfterWait IS NULL) OR (@WaitAtLowPriorityMaxDuration IS NULL AND @WaitAtLowPriorityAbortAfterWait IS NOT NULL) + IF @WaitAtLowPriorityMaxDuration < 0 OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12) + OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @WaitAtLowPriorityAbortAfterWait IS NULL) + OR (@WaitAtLowPriorityMaxDuration IS NULL AND @WaitAtLowPriorityAbortAfterWait IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16 END - IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) + IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') + OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12) + OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) + OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16 @@ -938,13 +949,15 @@ BEGIN SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 END - IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL + OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index c1137cf3..a09b79e7 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-11 12:40:32 +Version: 2020-01-11 14:01:25 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 12:40:32 //-- + --// Version: 2020-01-11 14:01:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -428,7 +428,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 12:40:32 //-- + --// Version: 2020-01-11 14:01:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1355,7 +1355,9 @@ BEGIN SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.', 16 END - IF @Verify NOT IN ('Y','N') OR @Verify IS NULL OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @Verify NOT IN ('Y','N') OR @Verify IS NULL + OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') + OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Verify is not supported.', 16 @@ -1415,7 +1417,11 @@ BEGIN SELECT 'The value for the parameter @CleanupMode is not supported.', 16 END - IF @Compress NOT IN ('Y','N') OR @Compress IS NULL OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) + IF @Compress NOT IN ('Y','N') OR @Compress IS NULL + OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) + OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) + OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) + OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Compress is not supported.', 16 @@ -1433,7 +1439,8 @@ BEGIN SELECT 'The value for the parameter @ChangeBackupType is not supported.', 16 END - IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') + IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') + OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @BackupSoftware is not supported.', 16 @@ -1469,25 +1476,43 @@ BEGIN SELECT 'The value for the parameter @CheckSum is not supported.', 16 END - IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) + OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') + OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') + OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) + OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @BlockSize is not supported.', 16 END - IF @BufferCount <= 0 OR @BufferCount > 2147483647 OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE') + IF @BufferCount <= 0 OR @BufferCount > 2147483647 + OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') + OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @BufferCount is not supported.', 16 END - IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 + OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') + OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') + OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) + OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16 END - IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 + IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 + OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') + OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) + OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 + OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) + OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) + OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) + OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16 @@ -1541,61 +1566,87 @@ BEGIN SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16 END - IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) + OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 + OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) + OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) + OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @CompressionLevel is not supported.', 16 END - IF LEN(@Description) > 255 OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) + IF LEN(@Description) > 255 + OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) + OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Description is not supported.', 16 END - IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) OR (@BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32)) OR (@BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32)) OR (@BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64)) + IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) + OR (@BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32)) + OR (@BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32)) + OR (@BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64)) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Threads is not supported.', 16 END - IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) OR @Throttle < 1 OR @Throttle > 100 + IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) + OR @Throttle < 1 + OR @Throttle > 100 BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Throttle is not supported.', 16 END - IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL + OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) + OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Encrypt is not supported.', 16 END - IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) + OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) + OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) + OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) + OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16 END - IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL) OR (@ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate)) + IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) + OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL) + OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL) + OR (@ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate)) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @ServerCertificate is not supported.', 16 END - IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL) OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL) OR (@ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey)) + IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL) + OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL) + OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL) + OR (@ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey)) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.', 16 END - IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') + OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) + OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @EncryptionKey is not supported.', 16 END - IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL OR (@ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG') + IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL + OR (@ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.', 16 @@ -1607,19 +1658,27 @@ BEGIN SELECT 'The value for the parameter @OverrideBackupPreference is not supported.', 16 END - IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL OR (@NoRecovery = 'Y' AND @BackupType <> 'LOG') OR (@NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE') + IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL + OR (@NoRecovery = 'Y' AND @BackupType <> 'LOG') + OR (@NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @NoRecovery is not supported.', 16 END - IF (@URL IS NOT NULL AND @Directory IS NOT NULL) OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@URL IS NOT NULL AND @Version < 11.03339) OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) + IF (@URL IS NOT NULL AND @Directory IS NOT NULL) + OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) + OR (@URL IS NOT NULL AND @Version < 11.03339) + OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @URL is not supported.', 16 END - IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) OR (@Credential IS NOT NULL AND @URL IS NULL) OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) + IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) + OR (@Credential IS NOT NULL AND @URL IS NULL) + OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) + OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Credential is not supported.', 16 @@ -1637,7 +1696,11 @@ BEGIN SELECT 'The value for the parameter @MirrorCleanupMode is not supported.', 16 END - IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) OR (@MirrorURL IS NOT NULL AND @URL IS NULL) + IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) + OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) + OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) + OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) + OR (@MirrorURL IS NOT NULL AND @URL IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @MirrorURL is not supported.', 16 @@ -1649,13 +1712,16 @@ BEGIN SELECT 'The value for the parameter @Updateability is not supported.', 16 END - IF @AdaptiveCompression NOT IN('SIZE','SPEED') OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) + IF @AdaptiveCompression NOT IN('SIZE','SPEED') + OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @AdaptiveCompression is not supported.', 16 END - IF (@ModificationLevel IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count')) OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') + IF (@ModificationLevel IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count')) + OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') + OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @ModificationLevel is not supported.', 16 @@ -1679,19 +1745,22 @@ BEGIN SELECT 'The parameters @TimeSinceLastLogBackup and @LogSizeSinceLastLogBackup can only be used together.', 16 END - IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) + OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16 END - IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) + OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16 END - IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) + OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16 @@ -1721,7 +1790,13 @@ BEGIN SELECT 'The value for the parameter @FileName is not supported.', 16 END - IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) OR @AvailabilityGroupFileName = '' OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' OR @AvailabilityGroupFileName LIKE '%/%' OR @AvailabilityGroupFileName LIKE '%\%' + IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) + OR @AvailabilityGroupFileName = '' + OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' + OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') + OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' + OR @AvailabilityGroupFileName LIKE '%/%' + OR @AvailabilityGroupFileName LIKE '%\%' BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16 @@ -1773,19 +1848,26 @@ BEGIN SELECT 'The value for the parameter @FileExtensionLog is not supported.', 16 END - IF @Init NOT IN('Y','N') OR @Init IS NULL OR (@Init = 'Y' AND @BackupType = 'LOG') OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @Init NOT IN('Y','N') OR @Init IS NULL + OR (@Init = 'Y' AND @BackupType = 'LOG') + OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Init is not supported.', 16 END - IF @Format NOT IN('Y','N') OR @Format IS NULL OR (@Format = 'Y' AND @BackupType = 'LOG') OR (@Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @Format NOT IN('Y','N') OR @Format IS NULL + OR (@Format = 'Y' AND @BackupType = 'LOG') + OR (@Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Format is not supported.', 16 END - IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL) OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED') OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG') + IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL + OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL) + OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED') + OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16 @@ -1815,7 +1897,8 @@ BEGIN SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 END - IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL + OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 @@ -3697,7 +3780,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 12:40:32 //-- + --// Version: 2020-01-11 14:01:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4327,7 +4410,11 @@ BEGIN --// Check input parameters //-- ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) OR EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) OR NOT EXISTS (SELECT * FROM @SelectedCheckCommands) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG'))) OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE'))) + IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) + OR EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) + OR NOT EXISTS (SELECT * FROM @SelectedCheckCommands) + OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG'))) + OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE'))) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @CheckCommands is not supported.', 16 @@ -4345,7 +4432,9 @@ BEGIN SELECT 'The value for the parameter @NoIndex is not supported.', 16 END - IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL OR (@ExtendedLogicalChecks = 'Y' AND NOT @Version >= 10) OR (@PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y') + IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL + OR (@ExtendedLogicalChecks = 'Y' AND NOT @Version >= 10) + OR (@PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y') BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @ExtendedLogicalChecks is not supported.', 16 @@ -4357,19 +4446,24 @@ BEGIN SELECT 'The value for the parameter @TabLock is not supported.', 16 END - IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) OR (@FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups)) OR (@FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP')) + IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) + OR (@FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups)) + OR (@FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP')) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @FileGroups is not supported.', 16 END - IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) OR (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) OR (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) + IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) + OR (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) + OR (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Objects is not supported.', 16 END - IF @MaxDOP < 0 OR @MaxDOP > 64 OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) + IF @MaxDOP < 0 OR @MaxDOP > 64 + OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @MaxDOP is not supported.', 16 @@ -4411,13 +4505,18 @@ BEGIN SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') + OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) + OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') + OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') + OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 END - IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL + OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 @@ -5424,7 +5523,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 12:40:32 //-- + --// Version: 2020-01-11 14:01:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6148,13 +6247,17 @@ BEGIN SELECT 'The value for the parameter @FragmentationHigh is not supported.', 16 END - IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 >= @FragmentationLevel2 OR @FragmentationLevel1 IS NULL + IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 + OR @FragmentationLevel1 >= @FragmentationLevel2 + OR @FragmentationLevel1 IS NULL BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @FragmentationLevel1 is not supported.', 16 END - IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 <= @FragmentationLevel1 OR @FragmentationLevel2 IS NULL + IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 + OR @FragmentationLevel2 <= @FragmentationLevel1 + OR @FragmentationLevel2 IS NULL BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @FragmentationLevel2 is not supported.', 16 @@ -6232,7 +6335,8 @@ BEGIN SELECT 'The value for the parameter @StatisticsSample is not supported.', 16 END - IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL OR (@StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL) + IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL + OR (@StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @StatisticsResample is not supported.', 16 @@ -6250,7 +6354,8 @@ BEGIN SELECT 'The value for the parameter @MSShippedObjects is not supported.', 16 END - IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) OR (@Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes)) + IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) + OR (@Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes)) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @Indexes is not supported.', 16 @@ -6268,13 +6373,18 @@ BEGIN SELECT 'The value for the parameter @Delay is not supported.', 16 END - IF @WaitAtLowPriorityMaxDuration < 0 OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @WaitAtLowPriorityAbortAfterWait IS NULL) OR (@WaitAtLowPriorityMaxDuration IS NULL AND @WaitAtLowPriorityAbortAfterWait IS NOT NULL) + IF @WaitAtLowPriorityMaxDuration < 0 OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12) + OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @WaitAtLowPriorityAbortAfterWait IS NULL) + OR (@WaitAtLowPriorityMaxDuration IS NULL AND @WaitAtLowPriorityAbortAfterWait IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16 END - IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12) OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) + IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') + OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12) + OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) + OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16 @@ -6310,13 +6420,15 @@ BEGIN SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 END - IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 END - IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL + OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN INSERT INTO @Errors ([Message], Severity) SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 From 450d24c5b6dd29cff09f88158f03844695627fb7 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 11 Jan 2020 19:49:39 +0100 Subject: [PATCH 151/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 6 +++--- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 14 +++++++------- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index a74c3f3c..fbbef17d 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 14:01:25 //-- + --// Version: 2020-01-11 19:44:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 0cd1391d..878d7e77 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 14:01:25 //-- + --// Version: 2020-01-11 19:44:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2150,9 +2150,9 @@ BEGIN SELECT @CurrentLatestBackup = MAX(backup_start_date) FROM msdb.dbo.backupset WHERE ([type] IN('D','I') - OR database_backup_lsn < @CurrentDifferentialBaseLSN) + OR ([type] = 'L' AND last_lsn < @CurrentDifferentialBaseLSN)) AND is_damaged = 0 - AND database_name = @CurrentDatabaseName + AND [database_name] = @CurrentDatabaseName END SET @CurrentDate = SYSDATETIME() diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 3824869f..f1a3941d 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -38,7 +38,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 14:01:25 //-- + --// Version: 2020-01-11 19:44:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 87b98b4c..bf74eba9 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 14:01:25 //-- + --// Version: 2020-01-11 19:44:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index a09b79e7..41bb3059 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-11 14:01:25 +Version: 2020-01-11 19:44:01 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 14:01:25 //-- + --// Version: 2020-01-11 19:44:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -428,7 +428,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 14:01:25 //-- + --// Version: 2020-01-11 19:44:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2500,9 +2500,9 @@ BEGIN SELECT @CurrentLatestBackup = MAX(backup_start_date) FROM msdb.dbo.backupset WHERE ([type] IN('D','I') - OR database_backup_lsn < @CurrentDifferentialBaseLSN) + OR ([type] = 'L' AND last_lsn < @CurrentDifferentialBaseLSN)) AND is_damaged = 0 - AND database_name = @CurrentDatabaseName + AND [database_name] = @CurrentDatabaseName END SET @CurrentDate = SYSDATETIME() @@ -3780,7 +3780,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 14:01:25 //-- + --// Version: 2020-01-11 19:44:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5523,7 +5523,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 14:01:25 //-- + --// Version: 2020-01-11 19:44:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 16175b8d069d9613b8830b9a431d95fa225543ac Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 12 Jan 2020 16:17:51 +0100 Subject: [PATCH 152/188] Add files via upload --- CommandExecute.sql | 62 +- DatabaseBackup.sql | 1352 ++++++++++++++++------ DatabaseIntegrityCheck.sql | 314 ++++-- IndexOptimize.sql | 394 ++++--- MaintenanceSolution.sql | 2156 +++++++++++++++++++++++++----------- 5 files changed, 3041 insertions(+), 1237 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index fbbef17d..6eccff76 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 19:44:01 //-- + --// Version: 2020-01-12 16:01:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -47,9 +47,13 @@ BEGIN DECLARE @Severity int DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, - [Message] nvarchar(max)) + [Message] nvarchar(max) NOT NULL, + Severity int NOT NULL, + [State] int) DECLARE @CurrentMessage nvarchar(max) + DECLARE @CurrentSeverity int + DECLARE @CurrentState int DECLARE @sp_executesql nvarchar(max) = QUOTENAME(@DatabaseContext) + '.sys.sp_executesql' @@ -69,26 +73,26 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16, 1 END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 END 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') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -97,69 +101,69 @@ BEGIN IF @DatabaseContext IS NULL OR NOT EXISTS (SELECT * FROM sys.databases WHERE name = @DatabaseContext) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabaseContext is not supported.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseContext is not supported.', 16, 1 END IF @Command IS NULL OR @Command = '' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Command is not supported.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Command is not supported.', 16, 1 END IF @CommandType IS NULL OR @CommandType = '' OR LEN(@CommandType) > 60 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CommandType is not supported.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CommandType is not supported.', 16, 1 END IF @Mode NOT IN(1,2) OR @Mode IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Mode is not supported.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Mode is not supported.', 16, 1 END IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LogToTable is not supported.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Execute is not supported.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Execute is not supported.', 16, 1 END ---------------------------------------------------------------------------------------------------- --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor - FETCH ErrorCursor INTO @CurrentMessage + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState WHILE @@FETCH_STATUS = 0 BEGIN - RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR('%s', @CurrentSeverity, @CurrentState, @CurrentMessage) WITH NOWAIT RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT - FETCH NEXT FROM ErrorCursor INTO @CurrentMessage + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState END CLOSE ErrorCursor DEALLOCATE ErrorCursor - IF EXISTS (SELECT * FROM @Errors) + IF EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) BEGIN SET @ReturnCode = 50000 GOTO ReturnCode diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 878d7e77..dd05f96f 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 19:44:01 //-- + --// Version: 2020-01-12 16:01:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -164,10 +164,12 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, - Severity int NOT NULL) + Severity int NOT NULL, + [State] int) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int + DECLARE @CurrentState int DECLARE @Directories TABLE (ID int PRIMARY KEY, DirectoryPath nvarchar(max), @@ -362,62 +364,62 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16, 1 END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 END 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') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1 END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1 END IF @@TRANCOUNT <> 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The transaction count is not 0.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The transaction count is not 0.', 16, 1 END IF @AmazonRDS = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The stored procedure DatabaseBackup is not supported on Amazon RDS.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The stored procedure DatabaseBackup is not supported on Amazon RDS.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -544,8 +546,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Databases is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Databases is not supported.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -639,20 +641,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2 END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -667,8 +669,8 @@ BEGIN ORDER BY DatabaseName ASC IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 16, 1 END SET @ErrorMessage = '' @@ -681,8 +683,8 @@ BEGIN OPTION (RECOMPILE) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -773,43 +775,95 @@ BEGIN --// Check directories //-- ---------------------------------------------------------------------------------------------------- - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux') OR (DirectoryPath = 'NUL' AND @HostPlatform = 'Windows')) - OR DirectoryPath IS NULL - OR LEFT(DirectoryPath,1) = ' ' - OR RIGHT(DirectoryPath,1) = ' ')) - OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) - OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) - OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') - OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath <> 'NUL')) - OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) + IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux') OR (DirectoryPath = 'NUL' AND @HostPlatform = 'Windows')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Directory is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Directory is not supported.', 16, 1 END - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) - OR DirectoryPath IS NULL - OR LEFT(DirectoryPath,1) = ' ' - OR RIGHT(DirectoryPath,1) = ' ')) - OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) - OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) - OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) - OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) - OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) - OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') - OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) + IF EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Directory is not supported.', 16, 2 + END + + IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Directory is not supported.', 16, 3 + END + + IF (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Directory is not supported.', 16, 4 + END + + IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath <> 'NUL') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Directory is not supported.', 16, 5 + END + + IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Directory is not supported.', 16, 6 + END + + ---------------------------------------------------------------------------------------------------- + + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 1 + END + + IF EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 2 + END + + IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 3 + END + + IF @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 4 + END + + IF @MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 5 + END + + IF @MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 6 + END + + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 7 END IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'Mirrored backup to disk is only available in Enterprise and Developer Edition.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported. Mirrored backup to disk is only available in Enterprise and Developer Edition.', 16, 8 END - IF NOT EXISTS (SELECT * FROM @Errors WHERE [Message] IN('The value for the parameter @Directory is not supported.','The value for the parameter @MirrorDirectory is not supported.')) + ---------------------------------------------------------------------------------------------------- + + IF NOT EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) BEGIN WHILE (1 = 1) BEGIN @@ -830,8 +884,8 @@ BEGIN IF NOT EXISTS (SELECT * FROM @DirectoryInfo WHERE FileExists = 0 AND FileIsADirectory = 1 AND ParentDirectoryExists = 1) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.', 16, 1 END UPDATE @Directories @@ -910,19 +964,41 @@ BEGIN ---------------------------------------------------------------------------------------------------- IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath NOT LIKE 'https://%/%') - OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) - OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @URL is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @URL is not supported.', 16, 1 + END + + IF EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @URL is not supported.', 16, 2 + END + + IF (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @URL is not supported.', 16, 3 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath NOT LIKE 'https://%/%') - OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) - OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MirrorURL is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 1 + END + + IF EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 2 + END + + IF (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -995,581 +1071,1159 @@ BEGIN IF @BackupType NOT IN ('FULL','DIFF','LOG') OR @BackupType IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @BackupType is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BackupType is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF SERVERPROPERTY('EngineEdition') = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Verify NOT IN ('Y','N') OR @Verify IS NULL - OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') - OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Verify is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Verify is not supported.', 16, 1 + END + + IF @BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Verify is not supported. Verify is not supported with encrypted backups with Idera SQL Safe Backup', 16, 2 + END + + IF @Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Verify is not supported. Verify is not supported with Data Domain Boost', 16, 3 END IF @Verify = 'Y' AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.', 16, 4 END + ---------------------------------------------------------------------------------------------------- + IF @CleanupTime < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupTime is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupTime is not supported.', 16, 1 END IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.', 16, 2 END IF @CleanupTime IS NOT NULL AND @HostPlatform = 'Linux' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.', 16, 3 END IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.', 16, 4 END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.', 16, 5 END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.', 16, 6 END IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.', 16, 7 END + ---------------------------------------------------------------------------------------------------- + IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupMode is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupMode is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Compress NOT IN ('Y','N') OR @Compress IS NULL - OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) - OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) - OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) - OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Compress is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Compress is not supported.', 16, 1 + END + + IF @Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786)))) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Compress is not supported.', 16, 2 END + IF @Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Compress is not supported.', 16, 3 + END + + IF @Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Compress is not supported.', 16, 4 + END + + ---------------------------------------------------------------------------------------------------- + IF @CopyOnly NOT IN ('Y','N') OR @CopyOnly IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CopyOnly is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CopyOnly is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @ChangeBackupType is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ChangeBackupType is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') - OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @BackupSoftware is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BackupSoftware is not supported.', 16, 1 + END + + IF @BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BackupSoftware is not supported. Only native backups are supported on Linux', 16, 2 END IF @BackupSoftware = 'LITESPEED' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_backup_database') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.', 16, 3 END IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.', 16, 4 END IF @BackupSoftware = 'SQLSAFE' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_ss_backup') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.', 16, 5 END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'PC' AND [name] = 'emc_run_backup') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.', 16, 6 END + ---------------------------------------------------------------------------------------------------- + IF @CheckSum NOT IN ('Y','N') OR @CheckSum IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CheckSum is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CheckSum is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) - OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') - OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') - OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) - OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @BlockSize is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BlockSize is not supported.', 16, 1 + END + + IF @BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BlockSize is not supported. This parameter is not supported with Redgate SQL Backup Pro', 16, 2 + END + + IF @BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BlockSize is not supported. This parameter is not supported with Idera SQL Safe', 16, 3 + END + + IF @BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BlockSize is not supported.', 16, 4 END + IF @BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BlockSize is not supported. This parameter is not supported with Data Domain Boost', 16, 5 + END + + ---------------------------------------------------------------------------------------------------- + IF @BufferCount <= 0 OR @BufferCount > 2147483647 - OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') - OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @BufferCount is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BufferCount is not supported.', 16, 1 END + IF @BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BufferCount is not supported.', 16, 2 + END + + IF @BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BufferCount is not supported.', 16, 3 + END + + ---------------------------------------------------------------------------------------------------- + IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 - OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') - OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') - OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) - OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 1 END + IF @MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 2 + END + + IF @MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 3 + END + + IF @MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 4 + END + + IF @MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 5 + END + + ---------------------------------------------------------------------------------------------------- + IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 - OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') - OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) - OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 - OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) - OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) - OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') - OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) - OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 1 + END + + IF @NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 2 + END + + IF @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 3 + END + + IF @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 4 + END + + IF @URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 5 + END + + IF @NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 6 + END + + IF @NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 7 + END + + IF @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 8 END + IF @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 9 + END + + ---------------------------------------------------------------------------------------------------- + IF @MinBackupSizeForMultipleFiles <= 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported.', 16, 1 END IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @NumberOfFiles IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.', 16, 2 END IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @BackupType = 'DIFF' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.', 16, 3 END IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @BackupType = 'LOG' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16, 4 END + ---------------------------------------------------------------------------------------------------- + IF @MaxFileSize <= 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MaxFileSize is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxFileSize is not supported.', 16, 1 END IF @MaxFileSize IS NOT NULL AND @NumberOfFiles IS NOT NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The parameters @MaxFileSize and @NumberOfFiles cannot be used together.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameters @MaxFileSize and @NumberOfFiles cannot be used together.', 16, 2 END IF @MaxFileSize IS NOT NULL AND @BackupType = 'DIFF' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.', 16, 3 END IF @MaxFileSize IS NOT NULL AND @BackupType = 'LOG' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16, 4 END + ---------------------------------------------------------------------------------------------------- + IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) - OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 - OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) - OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) - OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CompressionLevel is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CompressionLevel is not supported.', 16, 1 + END + + IF @BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CompressionLevel is not supported.', 16, 2 + END + + IF @BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CompressionLevel is not supported.', 16, 3 END + IF @BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CompressionLevel is not supported.', 16, 4 + END + + IF @CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CompressionLevel is not supported.', 16, 5 + END + + ---------------------------------------------------------------------------------------------------- + IF LEN(@Description) > 255 - OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) - OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Description is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Description is not supported.', 16, 1 + END + + IF @BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Description is not supported.', 16, 2 + END + + IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Description is not supported.', 16, 3 END + ---------------------------------------------------------------------------------------------------- + IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) - OR (@BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32)) - OR (@BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32)) - OR (@BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64)) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Threads is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Threads is not supported.', 16, 1 + END + + IF @BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Threads is not supported.', 16, 2 + END + + IF @BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Threads is not supported.', 16, 3 + END + + IF @BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Threads is not supported.', 16, 4 + END + + ---------------------------------------------------------------------------------------------------- + + IF @Throttle < 1 OR @Throttle > 100 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Throttle is not supported.', 16, 1 END IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) - OR @Throttle < 1 - OR @Throttle > 100 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Throttle is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Throttle is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL - OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) - OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Encrypt is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Encrypt is not supported.', 16, 1 + END + + IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786)) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Encrypt is not supported.', 16, 2 END - IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) - OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) - OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) - OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) + IF @Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Encrypt is not supported.', 16, 3 + END + + ---------------------------------------------------------------------------------------------------- + + IF @BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16, 1 + END + + IF @BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16, 2 + END + + IF @BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16, 3 + END + + IF @BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL) OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16, 4 END + IF @EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16, 5 + END + + ---------------------------------------------------------------------------------------------------- + IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) - OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL) - OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL) - OR (@ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate)) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @ServerCertificate is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerCertificate is not supported.', 16, 1 + END + + IF @BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerCertificate is not supported.', 16, 2 + END + + IF @BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerCertificate is not supported.', 16, 3 + END + + IF @ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerCertificate is not supported.', 16, 4 + END + + ---------------------------------------------------------------------------------------------------- + + IF NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.', 16, 1 + END + + IF @BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.', 16, 2 + END + + IF @BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.', 16, 3 + END + + IF @ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.', 16, 4 + END + + ---------------------------------------------------------------------------------------------------- + + IF @EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionKey is not supported.', 16, 1 + END + + IF @EncryptionKey IS NOT NULL AND @Encrypt = 'N' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionKey is not supported.', 16, 2 END - IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL) - OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL) - OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL) - OR (@ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey)) + IF @EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionKey is not supported.', 16, 3 END - IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') - OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) - OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @EncryptionKey is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionKey is not supported.', 16, 4 END + ---------------------------------------------------------------------------------------------------- + IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL - OR (@ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.', 16, 1 + END + + IF @ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @OverrideBackupPreference NOT IN('Y','N') OR @OverrideBackupPreference IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @OverrideBackupPreference is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @OverrideBackupPreference is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL - OR (@NoRecovery = 'Y' AND @BackupType <> 'LOG') - OR (@NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @NoRecovery is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NoRecovery is not supported.', 16, 1 + END + + IF @NoRecovery = 'Y' AND @BackupType <> 'LOG' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NoRecovery is not supported.', 16, 2 + END + + IF @NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NoRecovery is not supported.', 16, 3 + END + + ---------------------------------------------------------------------------------------------------- + + IF @URL IS NOT NULL AND @Directory IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @URL is not supported.', 16, 1 + END + + IF @URL IS NOT NULL AND @MirrorDirectory IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @URL is not supported.', 16, 2 + END + + IF @URL IS NOT NULL AND @Version < 11.03339 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @URL is not supported.', 16, 3 END - IF (@URL IS NOT NULL AND @Directory IS NOT NULL) - OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) - OR (@URL IS NOT NULL AND @Version < 11.03339) - OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) + IF @URL IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @URL is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @URL is not supported.', 16, 4 END - IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) - OR (@Credential IS NOT NULL AND @URL IS NULL) - OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) - OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) + ---------------------------------------------------------------------------------------------------- + + IF @Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Credential is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Credential is not supported.', 16, 1 END - IF @MirrorCleanupTime < 0 OR (@MirrorCleanupTime IS NOT NULL AND @MirrorDirectory IS NULL) + IF @Credential IS NOT NULL AND @URL IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MirrorCleanupTime is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Credential is not supported.', 16, 2 END + IF @URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Credential is not supported.', 16, 3 + END + + IF @Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Credential is not supported.', 16, 4 + END + + ---------------------------------------------------------------------------------------------------- + + IF @MirrorCleanupTime < 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorCleanupTime is not supported.', 16, 1 + END + + IF @MirrorCleanupTime IS NOT NULL AND @MirrorDirectory IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorCleanupTime is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF @MirrorCleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @MirrorCleanupMode IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MirrorCleanupMode is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorCleanupMode is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + + IF @MirrorURL IS NOT NULL AND @Directory IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 1 + END + + IF @MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 2 + END + + IF @MirrorURL IS NOT NULL AND @Version < 11.03339 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 3 + END + + IF @MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 4 END - IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) - OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) - OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) - OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) - OR (@MirrorURL IS NOT NULL AND @URL IS NULL) + IF @MirrorURL IS NOT NULL AND @URL IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MirrorURL is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 5 END + ---------------------------------------------------------------------------------------------------- + IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Updateability is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Updateability is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @AdaptiveCompression NOT IN('SIZE','SPEED') - OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @AdaptiveCompression is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AdaptiveCompression is not supported.', 16, 1 + END + + IF @AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AdaptiveCompression is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + + IF @ModificationLevel IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ModificationLevel is not supported.', 16, 1 END - IF (@ModificationLevel IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count')) - OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') - OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') + IF @ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @ModificationLevel is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ModificationLevel is not supported.', 16, 2 END - IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb')) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF @ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ModificationLevel is not supported.', 16, 3 + END + + ---------------------------------------------------------------------------------------------------- + + IF @LogSizeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.', 16, 1 END - IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_backup_time')) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF @LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @TimeSinceLastLogBackup is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + + IF @TimeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_backup_time') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @TimeSinceLastLogBackup is not supported.', 16, 1 + END + + IF @TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @TimeSinceLastLogBackup is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The parameters @TimeSinceLastLogBackup and @LogSizeSinceLastLogBackup can only be used together.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameters @TimeSinceLastLogBackup and @LogSizeSinceLastLogBackup can only be used together.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + + IF @DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16, 1 + END + + IF @DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + + IF @DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16, 1 END - IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) - OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16, 2 END - IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) - OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + ---------------------------------------------------------------------------------------------------- + + IF @DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 1 END - IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) - OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @DirectoryStructure = '' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DirectoryStructure is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DirectoryStructure is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @AvailabilityGroupDirectoryStructure = '' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + + IF @FileName IS NULL OR @FileName = '' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileName is not supported.', 16, 1 + END + + IF @FileName NOT LIKE '%.{FileExtension}' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileName is not supported.', 16, 2 + END + + IF (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileName is not supported.', 16, 3 + END + + IF @FileName LIKE '%{DirectorySeperator}%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileName is not supported.', 16, 4 + END + + IF @FileName LIKE '%/%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileName is not supported.', 16, 5 END - IF @FileName IS NULL OR @FileName = '' OR @FileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') OR @FileName LIKE '%{DirectorySeperator}%' OR @FileName LIKE '%/%' OR @FileName LIKE '%\%' + IF @FileName LIKE '%\%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FileName is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileName is not supported.', 16, 6 END + ---------------------------------------------------------------------------------------------------- + IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) - OR @AvailabilityGroupFileName = '' - OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' - OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') - OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' - OR @AvailabilityGroupFileName LIKE '%/%' - OR @AvailabilityGroupFileName LIKE '%\%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 1 + END + + IF @AvailabilityGroupFileName = '' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 2 + END + + IF @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 3 + END + + IF (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 4 + END + + IF @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 5 END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF @AvailabilityGroupFileName LIKE '%/%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The parameter @DirectoryStructure contains one or more tokens that are not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 6 END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF @AvailabilityGroupFileName LIKE '%\%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 7 END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + ---------------------------------------------------------------------------------------------------- + + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The parameter @FileName contains one or more tokens that are not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameter @DirectoryStructure contains one or more tokens that are not supported.', 16, 1 END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + ---------------------------------------------------------------------------------------------------- + + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS AvailabilityGroupDirectoryStructure) Temp WHERE AvailabilityGroupDirectoryStructure LIKE '%{%' OR AvailabilityGroupDirectoryStructure LIKE '%}%') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') AS [FileName]) Temp WHERE [FileName] LIKE '%{%' OR [FileName] LIKE '%}%') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameter @FileName contains one or more tokens that are not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') AS AvailabilityGroupFileName) Temp WHERE AvailabilityGroupFileName LIKE '%{%' OR AvailabilityGroupFileName LIKE '%}%') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + IF @FileExtensionFull LIKE '%.%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FileExtensionFull is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileExtensionFull is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @FileExtensionDiff LIKE '%.%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FileExtensionDiff is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileExtensionDiff is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @FileExtensionLog LIKE '%.%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FileExtensionLog is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileExtensionLog is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Init NOT IN('Y','N') OR @Init IS NULL - OR (@Init = 'Y' AND @BackupType = 'LOG') - OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Init is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Init is not supported.', 16, 1 + END + + IF @Init = 'Y' AND @BackupType = 'LOG' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Init is not supported.', 16, 2 + END + + IF @Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Init is not supported.', 16, 3 END + ---------------------------------------------------------------------------------------------------- + IF @Format NOT IN('Y','N') OR @Format IS NULL - OR (@Format = 'Y' AND @BackupType = 'LOG') - OR (@Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Format is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Format is not supported.', 16, 1 END + IF @Format = 'Y' AND @BackupType = 'LOG' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Format is not supported.', 16, 2 + END + + IF @Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Format is not supported.', 16, 3 + END + + ---------------------------------------------------------------------------------------------------- + IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL - OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL) - OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED') - OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16, 1 + END + + IF @ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16, 2 + END + + IF @ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16, 3 END + IF @ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16, 4 + END + + ---------------------------------------------------------------------------------------------------- + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 END IF @DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabaseOrder is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16, 2 END IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 3 END + ---------------------------------------------------------------------------------------------------- + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL - OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 + END + + IF @DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LogToTable is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Execute is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Execute is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS(SELECT * FROM @Errors) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -1583,8 +2237,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -1594,8 +2248,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END ---------------------------------------------------------------------------------------------------- @@ -1604,26 +2258,26 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16, 1 END ---------------------------------------------------------------------------------------------------- --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor - FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState WHILE @@FETCH_STATUS = 0 BEGIN - RAISERROR('%s', @CurrentSeverity, 1, @CurrentMessage) WITH NOWAIT + RAISERROR('%s', @CurrentSeverity, @CurrentState, @CurrentMessage) WITH NOWAIT RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT - FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState END CLOSE ErrorCursor diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index f1a3941d..52b491d0 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -38,7 +38,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 19:44:01 //-- + --// Version: 2020-01-12 16:01:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -98,10 +98,12 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, - Severity int NOT NULL) + Severity int NOT NULL, + [State] int) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int + DECLARE @CurrentState int DECLARE @tmpDatabases TABLE (ID int IDENTITY, DatabaseName nvarchar(max), @@ -248,56 +250,56 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16, 1 END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 END 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') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1 END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1 END IF @@TRANCOUNT <> 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The transaction count is not 0.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The transaction count is not 0.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -424,8 +426,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Databases is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Databases is not supported.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -519,20 +521,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2 END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -669,133 +671,243 @@ BEGIN ---------------------------------------------------------------------------------------------------- IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) - OR EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) - OR NOT EXISTS (SELECT * FROM @SelectedCheckCommands) - OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG'))) - OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE'))) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CheckCommands is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CheckCommands is not supported.', 16, 1 END + IF EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CheckCommands is not supported.', 16, 2 + END + + IF NOT EXISTS (SELECT * FROM @SelectedCheckCommands) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CheckCommands is not supported.' , 16, 3 + END + + IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CheckCommands is not supported.', 16, 4 + END + + IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CheckCommands is not supported.', 16, 5 + END + + ---------------------------------------------------------------------------------------------------- + IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @PhysicalOnly is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @PhysicalOnly is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @NoIndex is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NoIndex is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL - OR (@ExtendedLogicalChecks = 'Y' AND NOT @Version >= 10) - OR (@PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @ExtendedLogicalChecks is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ExtendedLogicalChecks is not supported.', 16, 1 + END + + IF @PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameters @PhysicalOnly and @ExtendedLogicalChecks cannot be used together.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @TabLock is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @TabLock is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) - OR (@FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups)) - OR (@FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP')) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FileGroups is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileGroups is not supported.', 16, 1 + END + + IF @FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileGroups is not supported.', 16, 2 + END + + IF @FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileGroups is not supported.', 16, 3 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) - OR (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) - OR (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Objects is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Objects is not supported.', 16, 1 + END + + IF (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Objects is not supported.', 16, 2 END + IF (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Objects is not supported.', 16, 3 + END + + ---------------------------------------------------------------------------------------------------- + IF @MaxDOP < 0 OR @MaxDOP > 64 - OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MaxDOP is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxDOP is not supported.', 16, 1 END + IF @MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8)) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxDOP is not supported. MAXDOP is not available in this version of SQL Server.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @AvailabilityGroupReplicas is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupReplicas is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Updateability is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Updateability is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @TimeLimit < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @TimeLimit is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @TimeLimit is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @LockTimeout < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LockTimeout is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 1 END - IF @LockMessageSeverity NOT IN(10,16) + ---------------------------------------------------------------------------------------------------- + + IF @LockMessageSeverity NOT IN(10, 16) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') - OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) - OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') - OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') - OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 + END + + IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported. DATABASEPROPERTYEX(''DatabaseName'', ''LastGoodCheckDbTime'') is not available in this version of SQL Server.', 16, 2 END + IF @DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @LogToTable = ''Y''.', 16, 3 + END + + IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @CheckCommands = ''CHECKDB''.', 16, 4 + END + + IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported. This parameter is not supported in Azure SQL Database.', 16, 5 + END + + ---------------------------------------------------------------------------------------------------- + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL - OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 END + IF @DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported. This parameter is not supported in Azure SQL Database.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LogToTable is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Execute is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Execute is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS(SELECT * FROM @Errors) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -809,8 +921,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -820,8 +932,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -831,8 +943,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -842,8 +954,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -854,8 +966,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -866,8 +978,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END ---------------------------------------------------------------------------------------------------- @@ -876,26 +988,26 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16, 1 END ---------------------------------------------------------------------------------------------------- --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor - FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState WHILE @@FETCH_STATUS = 0 BEGIN - RAISERROR('%s', @CurrentSeverity, 1, @CurrentMessage) WITH NOWAIT + RAISERROR('%s', @CurrentSeverity, @CurrentState, @CurrentMessage) WITH NOWAIT RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT - FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState END CLOSE ErrorCursor diff --git a/IndexOptimize.sql b/IndexOptimize.sql index bf74eba9..8cff1a7d 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 19:44:01 //-- + --// Version: 2020-01-12 16:01:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -105,10 +105,12 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, - Severity int NOT NULL) + Severity int NOT NULL, + [State] int) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int + DECLARE @CurrentState int DECLARE @CurrentIxID int DECLARE @CurrentIxOrder int @@ -341,56 +343,56 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16, 1 END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 END 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') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1 END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1 END IF @@TRANCOUNT <> 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The transaction count is not 0.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The transaction count is not 0.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -516,8 +518,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Databases is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Databases is not supported.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -611,20 +613,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2 END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -756,229 +758,359 @@ BEGIN ---------------------------------------------------------------------------------------------------- IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' AND [Action] NOT IN(SELECT * FROM @Actions)) - OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FragmentationLow is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationLow is not supported.', 16, 1 END + IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationLow is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' AND [Action] NOT IN(SELECT * FROM @Actions)) - OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FragmentationMedium is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationMedium is not supported.', 16, 1 + END + + IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationMedium is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'High' AND [Action] NOT IN(SELECT * FROM @Actions)) - OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FragmentationHigh is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationHigh is not supported.', 16, 1 END - IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 - OR @FragmentationLevel1 >= @FragmentationLevel2 - OR @FragmentationLevel1 IS NULL + IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FragmentationLevel1 is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationHigh is not supported.', 16, 2 END - IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 - OR @FragmentationLevel2 <= @FragmentationLevel1 - OR @FragmentationLevel2 IS NULL + ---------------------------------------------------------------------------------------------------- + + IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FragmentationLevel2 is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationLevel1 is not supported.', 16, 1 END + IF @FragmentationLevel1 >= @FragmentationLevel2 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationLevel1 is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + + IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationLevel2 is not supported.', 16, 1 + END + + IF @FragmentationLevel2 <= @FragmentationLevel1 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationLevel2 is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MinNumberOfPages is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MinNumberOfPages is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @MaxNumberOfPages < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MaxNumberOfPages is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxNumberOfPages is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @SortInTempdb is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @SortInTempdb is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MaxDOP is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxDOP is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FillFactor is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FillFactor is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @PadIndex NOT IN('Y','N') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @PadIndex is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @PadIndex is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LOBCompaction is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LOBCompaction is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @UpdateStatistics is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @UpdateStatistics is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @OnlyModifiedStatistics is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @OnlyModifiedStatistics is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @StatisticsModificationLevel is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StatisticsModificationLevel is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @StatisticsSample is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StatisticsSample is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL - OR (@StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @StatisticsResample is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 1 + END + + IF @StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @PartitionLevel is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @PartitionLevel is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MSShippedObjects is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MSShippedObjects is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) - OR (@Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes)) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Indexes is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Indexes is not supported.', 16, 1 + END + + IF @Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Indexes is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @TimeLimit < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @TimeLimit is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @TimeLimit is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Delay < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Delay is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Delay is not supported.', 16, 1 END - IF @WaitAtLowPriorityMaxDuration < 0 OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12) - OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @WaitAtLowPriorityAbortAfterWait IS NULL) - OR (@WaitAtLowPriorityMaxDuration IS NULL AND @WaitAtLowPriorityAbortAfterWait IS NOT NULL) + ---------------------------------------------------------------------------------------------------- + + IF @WaitAtLowPriorityMaxDuration < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1 END + IF @WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') - OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12) - OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) - OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16, 1 END - IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL OR (@Resumable = 'Y' AND NOT (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8))) + IF @WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Resumable is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + + IF (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameters @WaitAtLowPriorityMaxDuration and @WaitAtLowPriorityAbortAfterWait can only be used together.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + + IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Resumable is not supported.', 16, 1 + END + + IF @Resumable = 'Y' AND NOT (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5, 8)) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Resumable is not supported.', 16, 2 END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 3 END + ---------------------------------------------------------------------------------------------------- + IF @LockTimeout < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LockTimeout is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 1 END - IF @LockMessageSeverity NOT IN(10,16) + ---------------------------------------------------------------------------------------------------- + + IF @LockMessageSeverity NOT IN(10, 16) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') - OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 + END + + IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL - OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 + END + + IF @DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LogToTable is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Execute is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Execute is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS(SELECT * FROM @Errors) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -992,8 +1124,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -1003,8 +1135,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -1014,8 +1146,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -1026,26 +1158,26 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END ---------------------------------------------------------------------------------------------------- --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor - FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState WHILE @@FETCH_STATUS = 0 BEGIN - RAISERROR('%s', @CurrentSeverity, 1, @CurrentMessage) WITH NOWAIT + RAISERROR('%s', @CurrentSeverity, @CurrentState, @CurrentMessage) WITH NOWAIT RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT - FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState END CLOSE ErrorCursor diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 41bb3059..98d19b99 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-11 19:44:01 +Version: 2020-01-12 16:01:32 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 19:44:01 //-- + --// Version: 2020-01-12 16:01:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -134,9 +134,13 @@ BEGIN DECLARE @Severity int DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, - [Message] nvarchar(max)) + [Message] nvarchar(max) NOT NULL, + Severity int NOT NULL, + [State] int) DECLARE @CurrentMessage nvarchar(max) + DECLARE @CurrentSeverity int + DECLARE @CurrentState int DECLARE @sp_executesql nvarchar(max) = QUOTENAME(@DatabaseContext) + '.sys.sp_executesql' @@ -156,26 +160,26 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16, 1 END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 END 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') BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -184,69 +188,69 @@ BEGIN IF @DatabaseContext IS NULL OR NOT EXISTS (SELECT * FROM sys.databases WHERE name = @DatabaseContext) BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @DatabaseContext is not supported.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseContext is not supported.', 16, 1 END IF @Command IS NULL OR @Command = '' BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Command is not supported.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Command is not supported.', 16, 1 END IF @CommandType IS NULL OR @CommandType = '' OR LEN(@CommandType) > 60 BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @CommandType is not supported.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CommandType is not supported.', 16, 1 END IF @Mode NOT IN(1,2) OR @Mode IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Mode is not supported.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Mode is not supported.', 16, 1 END IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @LogToTable is not supported.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - INSERT INTO @Errors ([Message]) - SELECT 'The value for the parameter @Execute is not supported.' + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Execute is not supported.', 16, 1 END ---------------------------------------------------------------------------------------------------- --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor - FETCH ErrorCursor INTO @CurrentMessage + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState WHILE @@FETCH_STATUS = 0 BEGIN - RAISERROR('%s', 16, 1, @CurrentMessage) WITH NOWAIT + RAISERROR('%s', @CurrentSeverity, @CurrentState, @CurrentMessage) WITH NOWAIT RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT - FETCH NEXT FROM ErrorCursor INTO @CurrentMessage + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState END CLOSE ErrorCursor DEALLOCATE ErrorCursor - IF EXISTS (SELECT * FROM @Errors) + IF EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) BEGIN SET @ReturnCode = 50000 GOTO ReturnCode @@ -428,7 +432,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 19:44:01 //-- + --// Version: 2020-01-12 16:01:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -514,10 +518,12 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, - Severity int NOT NULL) + Severity int NOT NULL, + [State] int) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int + DECLARE @CurrentState int DECLARE @Directories TABLE (ID int PRIMARY KEY, DirectoryPath nvarchar(max), @@ -712,62 +718,62 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16, 1 END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 END 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') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1 END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1 END IF @@TRANCOUNT <> 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The transaction count is not 0.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The transaction count is not 0.', 16, 1 END IF @AmazonRDS = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The stored procedure DatabaseBackup is not supported on Amazon RDS.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The stored procedure DatabaseBackup is not supported on Amazon RDS.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -894,8 +900,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Databases is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Databases is not supported.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -989,20 +995,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2 END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -1017,8 +1023,8 @@ BEGIN ORDER BY DatabaseName ASC IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The names of the following databases are not supported: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 16, 1 END SET @ErrorMessage = '' @@ -1031,8 +1037,8 @@ BEGIN OPTION (RECOMPILE) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The names of the following databases are not unique in the file system: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -1123,43 +1129,95 @@ BEGIN --// Check directories //-- ---------------------------------------------------------------------------------------------------- - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux') OR (DirectoryPath = 'NUL' AND @HostPlatform = 'Windows')) - OR DirectoryPath IS NULL - OR LEFT(DirectoryPath,1) = ' ' - OR RIGHT(DirectoryPath,1) = ' ')) - OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) - OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) - OR (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') - OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath <> 'NUL')) - OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) + IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux') OR (DirectoryPath = 'NUL' AND @HostPlatform = 'Windows')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Directory is not supported.', 16, 1 + END + + IF EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Directory is not supported.', 16, 2 + END + + IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Directory is not supported.', 16, 3 + END + + IF (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Directory is not supported.', 16, 4 + END + + IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath <> 'NUL') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Directory is not supported.', 16, 5 + END + + IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Directory is not supported.', 16, 6 + END + + ---------------------------------------------------------------------------------------------------- + + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 1 + END + + IF EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Directory is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 2 END - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) - OR DirectoryPath IS NULL - OR LEFT(DirectoryPath,1) = ' ' - OR RIGHT(DirectoryPath,1) = ' ')) - OR EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) - OR ((SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0) - OR (@BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1) - OR (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) - OR (@MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) - OR (@MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') - OR (EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) + IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 3 + END + + IF @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 4 + END + + IF @MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 5 + END + + IF @MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 6 + END + + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 7 END IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'Mirrored backup to disk is only available in Enterprise and Developer Edition.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorDirectory is not supported. Mirrored backup to disk is only available in Enterprise and Developer Edition.', 16, 8 END - IF NOT EXISTS (SELECT * FROM @Errors WHERE [Message] IN('The value for the parameter @Directory is not supported.','The value for the parameter @MirrorDirectory is not supported.')) + ---------------------------------------------------------------------------------------------------- + + IF NOT EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) BEGIN WHILE (1 = 1) BEGIN @@ -1180,8 +1238,8 @@ BEGIN IF NOT EXISTS (SELECT * FROM @DirectoryInfo WHERE FileExists = 0 AND FileIsADirectory = 1 AND ParentDirectoryExists = 1) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.', 16, 1 END UPDATE @Directories @@ -1260,19 +1318,41 @@ BEGIN ---------------------------------------------------------------------------------------------------- IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath NOT LIKE 'https://%/%') - OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) - OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @URL is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @URL is not supported.', 16, 1 + END + + IF EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @URL is not supported.', 16, 2 + END + + IF (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @URL is not supported.', 16, 3 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath NOT LIKE 'https://%/%') - OR EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) - OR ((SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MirrorURL is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 1 + END + + IF EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 2 + END + + IF (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 1) > 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -1345,581 +1425,1159 @@ BEGIN IF @BackupType NOT IN ('FULL','DIFF','LOG') OR @BackupType IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @BackupType is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BackupType is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF SERVERPROPERTY('EngineEdition') = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Verify NOT IN ('Y','N') OR @Verify IS NULL - OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y') - OR (@Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Verify is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Verify is not supported.', 16, 1 + END + + IF @BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Verify is not supported. Verify is not supported with encrypted backups with Idera SQL Safe Backup', 16, 2 + END + + IF @Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Verify is not supported. Verify is not supported with Data Domain Boost', 16, 3 END IF @Verify = 'Y' AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.', 16, 4 END + ---------------------------------------------------------------------------------------------------- + IF @CleanupTime < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupTime is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupTime is not supported.', 16, 1 END IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.', 16, 2 END IF @CleanupTime IS NOT NULL AND @HostPlatform = 'Linux' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.', 16, 3 END IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.', 16, 4 END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.', 16, 5 END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory.', 16, 6 END IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (SERVERPROPERTY('IsHadrEnabled') = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.', 16, 7 END + ---------------------------------------------------------------------------------------------------- + IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CleanupMode is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CleanupMode is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Compress NOT IN ('Y','N') OR @Compress IS NULL - OR (@Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) - OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786))))) - OR (@Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1)) - OR (@Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Compress is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Compress is not supported.', 16, 1 + END + + IF @Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786)))) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Compress is not supported.', 16, 2 + END + + IF @Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Compress is not supported.', 16, 3 + END + + IF @Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevel = 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Compress is not supported.', 16, 4 END + ---------------------------------------------------------------------------------------------------- + IF @CopyOnly NOT IN ('Y','N') OR @CopyOnly IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CopyOnly is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CopyOnly is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @ChangeBackupType is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ChangeBackupType is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') - OR (@BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @BackupSoftware is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BackupSoftware is not supported.', 16, 1 + END + + IF @BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BackupSoftware is not supported. Only native backups are supported on Linux', 16, 2 END IF @BackupSoftware = 'LITESPEED' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_backup_database') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.', 16, 3 END IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.', 16, 4 END IF @BackupSoftware = 'SQLSAFE' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'xp_ss_backup') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.', 16, 5 END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'PC' AND [name] = 'emc_run_backup') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.', 16, 6 END + ---------------------------------------------------------------------------------------------------- + IF @CheckSum NOT IN ('Y','N') OR @CheckSum IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CheckSum is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CheckSum is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) - OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') - OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') - OR (@BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) - OR (@BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @BlockSize is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BlockSize is not supported.', 16, 1 + END + + IF @BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BlockSize is not supported. This parameter is not supported with Redgate SQL Backup Pro', 16, 2 + END + + IF @BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BlockSize is not supported. This parameter is not supported with Idera SQL Safe', 16, 3 + END + + IF @BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BlockSize is not supported.', 16, 4 + END + + IF @BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BlockSize is not supported. This parameter is not supported with Data Domain Boost', 16, 5 END + ---------------------------------------------------------------------------------------------------- + IF @BufferCount <= 0 OR @BufferCount > 2147483647 - OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP') - OR (@BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @BufferCount is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BufferCount is not supported.', 16, 1 END + IF @BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BufferCount is not supported.', 16, 2 + END + + IF @BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BufferCount is not supported.', 16, 3 + END + + ---------------------------------------------------------------------------------------------------- + IF @MaxTransferSize < 65536 OR @MaxTransferSize > 4194304 - OR (@MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP') - OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE') - OR (@MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL) - OR (@MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 1 + END + + IF @MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 2 END + IF @MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 3 + END + + IF @MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 4 + END + + IF @MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 5 + END + + ---------------------------------------------------------------------------------------------------- + IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 - OR (@NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP') - OR @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) - OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 - OR (@URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1) - OR (@NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1)) - OR (@NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST') - OR @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) - OR @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 1 + END + + IF @NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 2 + END + + IF @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 3 + END + + IF @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 4 + END + + IF @URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 5 + END + + IF @NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 6 END + IF @NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 7 + END + + IF @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 8 + END + + IF @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 9 + END + + ---------------------------------------------------------------------------------------------------- + IF @MinBackupSizeForMultipleFiles <= 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported.', 16, 1 END IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @NumberOfFiles IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.', 16, 2 END IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @BackupType = 'DIFF' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.', 16, 3 END IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @BackupType = 'LOG' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16, 4 END + ---------------------------------------------------------------------------------------------------- + IF @MaxFileSize <= 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MaxFileSize is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxFileSize is not supported.', 16, 1 END IF @MaxFileSize IS NOT NULL AND @NumberOfFiles IS NOT NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The parameters @MaxFileSize and @NumberOfFiles cannot be used together.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameters @MaxFileSize and @NumberOfFiles cannot be used together.', 16, 2 END IF @MaxFileSize IS NOT NULL AND @BackupType = 'DIFF' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_file_space_usage.modified_extent_page_count is not available in this version of SQL Server.', 16, 3 END IF @MaxFileSize IS NOT NULL AND @BackupType = 'LOG' AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxFileSize is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16, 4 END + ---------------------------------------------------------------------------------------------------- + IF (@BackupSoftware IS NULL AND @CompressionLevel IS NOT NULL) - OR (@BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 - OR @CompressionLevel > 8)) OR (@BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4)) - OR (@BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4)) - OR (@CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CompressionLevel is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CompressionLevel is not supported.', 16, 1 + END + + IF @BackupSoftware = 'LITESPEED' AND (@CompressionLevel < 0 OR @CompressionLevel > 8) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CompressionLevel is not supported.', 16, 2 + END + + IF @BackupSoftware = 'SQLBACKUP' AND (@CompressionLevel < 0 OR @CompressionLevel > 4) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CompressionLevel is not supported.', 16, 3 + END + + IF @BackupSoftware = 'SQLSAFE' AND (@CompressionLevel < 1 OR @CompressionLevel > 4) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CompressionLevel is not supported.', 16, 4 + END + + IF @CompressionLevel IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CompressionLevel is not supported.', 16, 5 END + ---------------------------------------------------------------------------------------------------- + IF LEN(@Description) > 255 - OR (@BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128) - OR (@BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Description is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Description is not supported.', 16, 1 END + IF @BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Description is not supported.', 16, 2 + END + + IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Description is not supported.', 16, 3 + END + + ---------------------------------------------------------------------------------------------------- + IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) - OR (@BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32)) - OR (@BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32)) - OR (@BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64)) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Threads is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Threads is not supported.', 16, 1 + END + + IF @BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Threads is not supported.', 16, 2 + END + + IF @BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Threads is not supported.', 16, 3 + END + + IF @BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Threads is not supported.', 16, 4 + END + + ---------------------------------------------------------------------------------------------------- + + IF @Throttle < 1 OR @Throttle > 100 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Throttle is not supported.', 16, 1 END IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) - OR @Throttle < 1 - OR @Throttle > 100 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Throttle is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Throttle is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL - OR (@Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786))) - OR (@Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Encrypt is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Encrypt is not supported.', 16, 1 END - IF (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL)) - OR (@BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL)) - OR (@BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) - OR (@BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL)) + IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@Version >= 12 AND (SERVERPROPERTY('EngineEdition') = 3) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786)) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Encrypt is not supported.', 16, 2 + END + + IF @Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Encrypt is not supported.', 16, 3 + END + + ---------------------------------------------------------------------------------------------------- + + IF @BackupSoftware IS NULL AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_192','AES_256','TRIPLE_DES_3KEY') OR @EncryptionAlgorithm IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16, 1 + END + + IF @BackupSoftware = 'LITESPEED' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('RC2_40','RC2_56','RC2_112','RC2_128','TRIPLE_DES_3KEY','RC4_128','AES_128','AES_192','AES_256') OR @EncryptionAlgorithm IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16, 2 + END + + IF @BackupSoftware = 'SQLBACKUP' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16, 3 + END + + IF @BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL) OR (@EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16, 4 END + IF @EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16, 5 + END + + ---------------------------------------------------------------------------------------------------- + IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) - OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL) - OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL) - OR (@ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate)) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @ServerCertificate is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerCertificate is not supported.', 16, 1 + END + + IF @BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NULL AND @ServerAsymmetricKey IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerCertificate is not supported.', 16, 2 + END + + IF @BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerCertificate IS NOT NULL AND @ServerAsymmetricKey IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerCertificate is not supported.', 16, 3 + END + + IF @ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerCertificate is not supported.', 16, 4 + END + + ---------------------------------------------------------------------------------------------------- + + IF NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.', 16, 1 + END + + IF @BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.', 16, 2 + END + + IF @BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.', 16, 3 + END + + IF @ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.', 16, 4 + END + + ---------------------------------------------------------------------------------------------------- + + IF @EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionKey is not supported.', 16, 1 + END + + IF @EncryptionKey IS NOT NULL AND @Encrypt = 'N' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionKey is not supported.', 16, 2 END - IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL) - OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NULL AND @ServerCertificate IS NULL) - OR (@BackupSoftware IS NULL AND @Encrypt = 'Y' AND @ServerAsymmetricKey IS NOT NULL AND @ServerCertificate IS NOT NULL) - OR (@ServerAsymmetricKey IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.asymmetric_keys WHERE name = @ServerAsymmetricKey)) + IF @EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @ServerAsymmetricKey is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionKey is not supported.', 16, 3 END - IF (@EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL) OR (@EncryptionKey IS NOT NULL AND @Encrypt = 'N') - OR (@EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE')) - OR (@EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @EncryptionKey is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @EncryptionKey is not supported.', 16, 4 END + ---------------------------------------------------------------------------------------------------- + IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL - OR (@ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.', 16, 1 + END + + IF @ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + + IF @OverrideBackupPreference NOT IN('Y','N') OR @OverrideBackupPreference IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @OverrideBackupPreference is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + + IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NoRecovery is not supported.', 16, 1 + END + + IF @NoRecovery = 'Y' AND @BackupType <> 'LOG' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NoRecovery is not supported.', 16, 2 + END + + IF @NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NoRecovery is not supported.', 16, 3 + END + + ---------------------------------------------------------------------------------------------------- + + IF @URL IS NOT NULL AND @Directory IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @URL is not supported.', 16, 1 + END + + IF @URL IS NOT NULL AND @MirrorDirectory IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @URL is not supported.', 16, 2 + END + + IF @URL IS NOT NULL AND @Version < 11.03339 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @URL is not supported.', 16, 3 + END + + IF @URL IS NOT NULL AND @BackupSoftware IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @URL is not supported.', 16, 4 + END + + ---------------------------------------------------------------------------------------------------- + + IF @Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Credential is not supported.', 16, 1 + END + + IF @Credential IS NOT NULL AND @URL IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Credential is not supported.', 16, 2 + END + + IF @URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Credential is not supported.', 16, 3 + END + + IF @Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Credential is not supported.', 16, 4 + END + + ---------------------------------------------------------------------------------------------------- + + IF @MirrorCleanupTime < 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorCleanupTime is not supported.', 16, 1 + END + + IF @MirrorCleanupTime IS NOT NULL AND @MirrorDirectory IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorCleanupTime is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + + IF @MirrorCleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @MirrorCleanupMode IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorCleanupMode is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + + IF @MirrorURL IS NOT NULL AND @Directory IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 1 + END + + IF @MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 2 + END + + IF @MirrorURL IS NOT NULL AND @Version < 11.03339 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 3 + END + + IF @MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 4 + END + + IF @MirrorURL IS NOT NULL AND @URL IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 5 + END + + ---------------------------------------------------------------------------------------------------- + + IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Updateability is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + + IF @AdaptiveCompression NOT IN('SIZE','SPEED') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AdaptiveCompression is not supported.', 16, 1 + END + + IF @AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AdaptiveCompression is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + + IF @ModificationLevel IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ModificationLevel is not supported.', 16, 1 + END + + IF @ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ModificationLevel is not supported.', 16, 2 + END + + IF @ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ModificationLevel is not supported.', 16, 3 + END + + ---------------------------------------------------------------------------------------------------- + + IF @LogSizeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.', 16, 1 + END + + IF @LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + + IF @TimeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_backup_time') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @TimeSinceLastLogBackup is not supported.', 16, 1 + END + + IF @TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @TimeSinceLastLogBackup is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + + IF (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameters @TimeSinceLastLogBackup and @LogSizeSinceLastLogBackup can only be used together.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + + IF @DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16, 1 + END + + IF @DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + + IF @DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16, 1 + END + + IF @DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + + IF @DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 1 + END + + IF @DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + + IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + + IF @DirectoryStructure = '' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DirectoryStructure is not supported.', 16, 1 END - IF @OverrideBackupPreference NOT IN('Y','N') OR @OverrideBackupPreference IS NULL + ---------------------------------------------------------------------------------------------------- + + IF @AvailabilityGroupDirectoryStructure = '' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @OverrideBackupPreference is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.', 16, 1 END - IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL - OR (@NoRecovery = 'Y' AND @BackupType <> 'LOG') - OR (@NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE') + ---------------------------------------------------------------------------------------------------- + + IF @FileName IS NULL OR @FileName = '' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @NoRecovery is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileName is not supported.', 16, 1 END - IF (@URL IS NOT NULL AND @Directory IS NOT NULL) - OR (@URL IS NOT NULL AND @MirrorDirectory IS NOT NULL) - OR (@URL IS NOT NULL AND @Version < 11.03339) - OR (@URL IS NOT NULL AND @BackupSoftware IS NOT NULL) + IF @FileName NOT LIKE '%.{FileExtension}' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @URL is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileName is not supported.', 16, 2 END - IF (@Credential IS NULL AND @URL IS NOT NULL AND NOT (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8)) - OR (@Credential IS NOT NULL AND @URL IS NULL) - OR (@URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) = 'SHARED ACCESS SIGNATURE')) - OR (@Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential)) + IF (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Credential is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileName is not supported.', 16, 3 END - IF @MirrorCleanupTime < 0 OR (@MirrorCleanupTime IS NOT NULL AND @MirrorDirectory IS NULL) + IF @FileName LIKE '%{DirectorySeperator}%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MirrorCleanupTime is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileName is not supported.', 16, 4 END - IF @MirrorCleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @MirrorCleanupMode IS NULL + IF @FileName LIKE '%/%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MirrorCleanupMode is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileName is not supported.', 16, 5 END - IF (@MirrorURL IS NOT NULL AND @Directory IS NOT NULL) - OR (@MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL) - OR (@MirrorURL IS NOT NULL AND @Version < 11.03339) - OR (@MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL) - OR (@MirrorURL IS NOT NULL AND @URL IS NULL) + IF @FileName LIKE '%\%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MirrorURL is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileName is not supported.', 16, 6 END - IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL + ---------------------------------------------------------------------------------------------------- + + IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Updateability is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 1 END - IF @AdaptiveCompression NOT IN('SIZE','SPEED') - OR (@AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL)) + IF @AvailabilityGroupFileName = '' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @AdaptiveCompression is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 2 END - IF (@ModificationLevel IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count')) - OR (@ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N') - OR (@ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF') + IF @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @ModificationLevel is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 3 END - IF (@LogSizeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb')) OR (@LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LogSizeSinceLastLogBackup is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 4 END - IF (@TimeSinceLastLogBackup IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_backup_time')) OR (@TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG') + IF @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @TimeSinceLastLogBackup is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 5 END - IF (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) + IF @AvailabilityGroupFileName LIKE '%/%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The parameters @TimeSinceLastLogBackup and @LogSizeSinceLastLogBackup can only be used together.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 6 END - IF (@DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) - OR (@DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @AvailabilityGroupFileName LIKE '%\%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 7 END - IF (@DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) - OR (@DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + ---------------------------------------------------------------------------------------------------- + + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameter @DirectoryStructure contains one or more tokens that are not supported.', 16, 1 END - IF (@DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL)) - OR (@DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + ---------------------------------------------------------------------------------------------------- + + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS AvailabilityGroupDirectoryStructure) Temp WHERE AvailabilityGroupDirectoryStructure LIKE '%{%' OR AvailabilityGroupDirectoryStructure LIKE '%}%') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.', 16, 1 END - IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + ---------------------------------------------------------------------------------------------------- + + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') AS [FileName]) Temp WHERE [FileName] LIKE '%{%' OR [FileName] LIKE '%}%') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameter @FileName contains one or more tokens that are not supported.', 16, 1 END - IF @DirectoryStructure = '' + ---------------------------------------------------------------------------------------------------- + + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') AS AvailabilityGroupFileName) Temp WHERE AvailabilityGroupFileName LIKE '%{%' OR AvailabilityGroupFileName LIKE '%}%') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DirectoryStructure is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.', 16, 1 END - IF @AvailabilityGroupDirectoryStructure = '' + ---------------------------------------------------------------------------------------------------- + + IF @FileExtensionFull LIKE '%.%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileExtensionFull is not supported.', 16, 1 END - IF @FileName IS NULL OR @FileName = '' OR @FileName NOT LIKE '%.{FileExtension}' OR (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') OR @FileName LIKE '%{DirectorySeperator}%' OR @FileName LIKE '%/%' OR @FileName LIKE '%\%' + ---------------------------------------------------------------------------------------------------- + + IF @FileExtensionDiff LIKE '%.%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FileName is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileExtensionDiff is not supported.', 16, 1 END - IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) - OR @AvailabilityGroupFileName = '' - OR @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' - OR (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') - OR @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' - OR @AvailabilityGroupFileName LIKE '%/%' - OR @AvailabilityGroupFileName LIKE '%\%' + ---------------------------------------------------------------------------------------------------- + + IF @FileExtensionLog LIKE '%.%' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileExtensionLog is not supported.', 16, 1 END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + ---------------------------------------------------------------------------------------------------- + + IF @Init NOT IN('Y','N') OR @Init IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The parameter @DirectoryStructure contains one or more tokens that are not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Init is not supported.', 16, 1 END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF @Init = 'Y' AND @BackupType = 'LOG' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Init is not supported.', 16, 2 END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + IF @Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The parameter @FileName contains one or more tokens that are not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Init is not supported.', 16, 3 END - IF REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%{%' - OR REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') LIKE '%}%' + ---------------------------------------------------------------------------------------------------- + + IF @Format NOT IN('Y','N') OR @Format IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Format is not supported.', 16, 1 END - IF @FileExtensionFull LIKE '%.%' + IF @Format = 'Y' AND @BackupType = 'LOG' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FileExtensionFull is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Format is not supported.', 16, 2 END - IF @FileExtensionDiff LIKE '%.%' + IF @Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FileExtensionDiff is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Format is not supported.', 16, 3 END - IF @FileExtensionLog LIKE '%.%' + ---------------------------------------------------------------------------------------------------- + + IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FileExtensionLog is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16, 1 END - IF @Init NOT IN('Y','N') OR @Init IS NULL - OR (@Init = 'Y' AND @BackupType = 'LOG') - OR (@Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Init is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16, 2 END - IF @Format NOT IN('Y','N') OR @Format IS NULL - OR (@Format = 'Y' AND @BackupType = 'LOG') - OR (@Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Format is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16, 3 END - IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL - OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL) - OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED') - OR (@ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG') + IF @ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16, 4 END + ---------------------------------------------------------------------------------------------------- + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 END IF @DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabaseOrder is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16, 2 END IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 3 END + ---------------------------------------------------------------------------------------------------- + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL - OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 + END + + IF @DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LogToTable is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Execute is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Execute is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS(SELECT * FROM @Errors) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -1933,8 +2591,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -1944,8 +2602,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END ---------------------------------------------------------------------------------------------------- @@ -1954,26 +2612,26 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16, 1 END ---------------------------------------------------------------------------------------------------- --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor - FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState WHILE @@FETCH_STATUS = 0 BEGIN - RAISERROR('%s', @CurrentSeverity, 1, @CurrentMessage) WITH NOWAIT + RAISERROR('%s', @CurrentSeverity, @CurrentState, @CurrentMessage) WITH NOWAIT RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT - FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState END CLOSE ErrorCursor @@ -3780,7 +4438,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 19:44:01 //-- + --// Version: 2020-01-12 16:01:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3840,10 +4498,12 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, - Severity int NOT NULL) + Severity int NOT NULL, + [State] int) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int + DECLARE @CurrentState int DECLARE @tmpDatabases TABLE (ID int IDENTITY, DatabaseName nvarchar(max), @@ -3990,56 +4650,56 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16, 1 END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 END 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') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1 END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1 END IF @@TRANCOUNT <> 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The transaction count is not 0.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The transaction count is not 0.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -4166,8 +4826,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Databases is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Databases is not supported.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -4261,20 +4921,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2 END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -4411,133 +5071,243 @@ BEGIN ---------------------------------------------------------------------------------------------------- IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) - OR EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) - OR NOT EXISTS (SELECT * FROM @SelectedCheckCommands) - OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG'))) - OR (EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE'))) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @CheckCommands is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CheckCommands is not supported.', 16, 1 + END + + IF EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CheckCommands is not supported.', 16, 2 + END + + IF NOT EXISTS (SELECT * FROM @SelectedCheckCommands) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CheckCommands is not supported.' , 16, 3 END + IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKDB')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CheckCommands is not supported.', 16, 4 + END + + IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKFILEGROUP')) AND EXISTS (SELECT CheckCommand FROM @SelectedCheckCommands WHERE CheckCommand IN('CHECKALLOC','CHECKTABLE')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @CheckCommands is not supported.', 16, 5 + END + + ---------------------------------------------------------------------------------------------------- + IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @PhysicalOnly is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @PhysicalOnly is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @NoIndex is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @NoIndex is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL - OR (@ExtendedLogicalChecks = 'Y' AND NOT @Version >= 10) - OR (@PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @ExtendedLogicalChecks is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ExtendedLogicalChecks is not supported.', 16, 1 END + IF @PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameters @PhysicalOnly and @ExtendedLogicalChecks cannot be used together.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @TabLock is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @TabLock is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) - OR (@FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups)) - OR (@FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP')) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FileGroups is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileGroups is not supported.', 16, 1 + END + + IF @FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileGroups is not supported.', 16, 2 + END + + IF @FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FileGroups is not supported.', 16, 3 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) - OR (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) - OR (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Objects is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Objects is not supported.', 16, 1 + END + + IF (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Objects is not supported.', 16, 2 + END + + IF (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Objects is not supported.', 16, 3 END + ---------------------------------------------------------------------------------------------------- + IF @MaxDOP < 0 OR @MaxDOP > 64 - OR (@MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8))) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MaxDOP is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxDOP is not supported.', 16, 1 + END + + IF @MaxDOP IS NOT NULL AND NOT (@Version >= 12.050000 OR SERVERPROPERTY('EngineEdition') IN (5, 8)) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxDOP is not supported. MAXDOP is not available in this version of SQL Server.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @AvailabilityGroupReplicas is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroupReplicas is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Updateability is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Updateability is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @TimeLimit < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @TimeLimit is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @TimeLimit is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @LockTimeout < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LockTimeout is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 1 END - IF @LockMessageSeverity NOT IN(10,16) + ---------------------------------------------------------------------------------------------------- + + IF @LockMessageSeverity NOT IN(10, 16) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC','DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') - OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916)) - OR (@DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N') - OR (@DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB') - OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 + END + + IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT ((@Version >= 12.06024 AND @Version < 13) OR (@Version >= 13.05026 AND @Version < 14) OR @Version >= 14.0302916) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported. DATABASEPROPERTYEX(''DatabaseName'', ''LastGoodCheckDbTime'') is not available in this version of SQL Server.', 16, 2 + END + + IF @DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @LogToTable = ''Y''.', 16, 3 + END + + IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC','REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @CheckCommands <> 'CHECKDB' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @CheckCommands = ''CHECKDB''.', 16, 4 + END + + IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported. This parameter is not supported in Azure SQL Database.', 16, 5 END + ---------------------------------------------------------------------------------------------------- + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL - OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 + END + + IF @DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported. This parameter is not supported in Azure SQL Database.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LogToTable is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Execute is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Execute is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS(SELECT * FROM @Errors) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -4551,8 +5321,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -4562,8 +5332,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases in the @FileGroups parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -4573,8 +5343,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases in the @Objects parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -4584,8 +5354,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -4596,8 +5366,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -4608,8 +5378,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END ---------------------------------------------------------------------------------------------------- @@ -4618,26 +5388,26 @@ BEGIN IF @@SERVERNAME <> CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN SERVERPROPERTY('IsClustered') = 0 THEN 'https://docs.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN SERVERPROPERTY('IsClustered') = 1 THEN 'https://docs.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16, 1 END ---------------------------------------------------------------------------------------------------- --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor - FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState WHILE @@FETCH_STATUS = 0 BEGIN - RAISERROR('%s', @CurrentSeverity, 1, @CurrentMessage) WITH NOWAIT + RAISERROR('%s', @CurrentSeverity, @CurrentState, @CurrentMessage) WITH NOWAIT RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT - FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState END CLOSE ErrorCursor @@ -5523,7 +6293,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-11 19:44:01 //-- + --// Version: 2020-01-12 16:01:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5576,10 +6346,12 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, - Severity int NOT NULL) + Severity int NOT NULL, + [State] int) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int + DECLARE @CurrentState int DECLARE @CurrentIxID int DECLARE @CurrentIxOrder int @@ -5812,56 +6584,56 @@ BEGIN IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE database_id = DB_ID()) >= 90 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The database ' + QUOTENAME(DB_NAME(DB_ID())) + ' has to be in compatibility level 90 or higher.', 16, 1 END IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 END IF NOT EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 END IF EXISTS (SELECT * FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id] WHERE objects.[type] = 'P' AND schemas.[name] = 'dbo' AND objects.[name] = 'CommandExecute' AND OBJECT_DEFINITION(objects.[object_id]) NOT LIKE '%@DatabaseContext%') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 END 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') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 END IF @DatabasesInParallel = '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] = 'Queue') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1 END IF @DatabasesInParallel = '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] = 'QueueDatabase') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1 END IF @@TRANCOUNT <> 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The transaction count is not 0.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The transaction count is not 0.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -5987,8 +6759,8 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DatabaseName = '')) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Databases is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Databases is not supported.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -6082,20 +6854,20 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @Version < 11 OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2 END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -6227,229 +6999,359 @@ BEGIN ---------------------------------------------------------------------------------------------------- IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' AND [Action] NOT IN(SELECT * FROM @Actions)) - OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FragmentationLow is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationLow is not supported.', 16, 1 END + IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationLow is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' AND [Action] NOT IN(SELECT * FROM @Actions)) - OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FragmentationMedium is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationMedium is not supported.', 16, 1 + END + + IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationMedium is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'High' AND [Action] NOT IN(SELECT * FROM @Actions)) - OR EXISTS(SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FragmentationHigh is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationHigh is not supported.', 16, 1 + END + + IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationHigh is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + + IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationLevel1 is not supported.', 16, 1 + END + + IF @FragmentationLevel1 >= @FragmentationLevel2 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationLevel1 is not supported.', 16, 2 END - IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 - OR @FragmentationLevel1 >= @FragmentationLevel2 - OR @FragmentationLevel1 IS NULL + ---------------------------------------------------------------------------------------------------- + + IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FragmentationLevel1 is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationLevel2 is not supported.', 16, 1 END - IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 - OR @FragmentationLevel2 <= @FragmentationLevel1 - OR @FragmentationLevel2 IS NULL + IF @FragmentationLevel2 <= @FragmentationLevel1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FragmentationLevel2 is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FragmentationLevel2 is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MinNumberOfPages is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MinNumberOfPages is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @MaxNumberOfPages < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MaxNumberOfPages is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxNumberOfPages is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @SortInTempdb is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @SortInTempdb is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MaxDOP is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MaxDOP is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @FillFactor is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @FillFactor is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @PadIndex NOT IN('Y','N') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @PadIndex is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @PadIndex is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LOBCompaction is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LOBCompaction is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @UpdateStatistics is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @UpdateStatistics is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @OnlyModifiedStatistics is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @OnlyModifiedStatistics is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @StatisticsModificationLevel is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StatisticsModificationLevel is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @StatisticsSample is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StatisticsSample is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL - OR (@StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @StatisticsResample is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 1 + END + + IF @StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @PartitionLevel is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @PartitionLevel is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @MSShippedObjects is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MSShippedObjects is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) - OR (@Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes)) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Indexes is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Indexes is not supported.', 16, 1 + END + + IF @Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Indexes is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @TimeLimit < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @TimeLimit is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @TimeLimit is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Delay < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Delay is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Delay is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + + IF @WaitAtLowPriorityMaxDuration < 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1 END - IF @WaitAtLowPriorityMaxDuration < 0 OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12) - OR (@WaitAtLowPriorityMaxDuration IS NOT NULL AND @WaitAtLowPriorityAbortAfterWait IS NULL) - OR (@WaitAtLowPriorityMaxDuration IS NULL AND @WaitAtLowPriorityAbortAfterWait IS NOT NULL) + IF @WaitAtLowPriorityMaxDuration IS NOT NULL AND @Version < 12 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') - OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12) - OR (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) - OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16, 1 + END + + IF @WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @Version < 12 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + + IF (@WaitAtLowPriorityAbortAfterWait IS NOT NULL AND @WaitAtLowPriorityMaxDuration IS NULL) OR (@WaitAtLowPriorityAbortAfterWait IS NULL AND @WaitAtLowPriorityMaxDuration IS NOT NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameters @WaitAtLowPriorityMaxDuration and @WaitAtLowPriorityAbortAfterWait can only be used together.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + + IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Resumable is not supported.', 16, 1 END - IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL OR (@Resumable = 'Y' AND NOT (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8))) + IF @Resumable = 'Y' AND NOT (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5, 8)) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Resumable is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Resumable is not supported.', 16, 2 END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 3 END + ---------------------------------------------------------------------------------------------------- + IF @LockTimeout < 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LockTimeout is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 1 END - IF @LockMessageSeverity NOT IN(10,16) + ---------------------------------------------------------------------------------------------------- + + IF @LockMessageSeverity NOT IN(10, 16) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @StringDelimiter is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') - OR (@DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 + END + + IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL - OR (@DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 + END + + IF @DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 2 END + ---------------------------------------------------------------------------------------------------- + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @LogToTable is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The value for the parameter @Execute is not supported.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Execute is not supported.', 16, 1 END + ---------------------------------------------------------------------------------------------------- + IF EXISTS(SELECT * FROM @Errors) BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -6463,8 +7365,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases in the @Databases parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -6474,8 +7376,8 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases in the @Indexes parameter do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -6485,8 +7387,8 @@ BEGIN AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following availability groups do not exist: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END SET @ErrorMessage = '' @@ -6497,26 +7399,26 @@ BEGIN AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases WHERE Selected = 1) IF @@ROWCOUNT > 0 BEGIN - INSERT INTO @Errors ([Message], Severity) - SELECT 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10 + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + LEFT(@ErrorMessage,LEN(@ErrorMessage)-1) + '.', 10, 1 END ---------------------------------------------------------------------------------------------------- --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor - FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState WHILE @@FETCH_STATUS = 0 BEGIN - RAISERROR('%s', @CurrentSeverity, 1, @CurrentMessage) WITH NOWAIT + RAISERROR('%s', @CurrentSeverity, @CurrentState, @CurrentMessage) WITH NOWAIT RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT - FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState END CLOSE ErrorCursor From 5df350a15e8b7e6e4304d2408418c81ec604c795 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 13 Jan 2020 20:12:14 +0100 Subject: [PATCH 153/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 12 +++++++++--- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 20 +++++++++++++------- 5 files changed, 25 insertions(+), 13 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 6eccff76..cfcd7909 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-12 16:01:32 //-- + --// Version: 2020-01-13 20:08:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index dd05f96f..990a1fb3 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-12 16:01:32 //-- + --// Version: 2020-01-13 20:08:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3088,6 +3088,12 @@ BEGIN SET @Updated = 1 END + IF CHARINDEX('of.',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'of.','.') + SET @Updated = 1 + END + IF LEFT(@CurrentDatabaseFileName,1) = '_' BEGIN SET @CurrentDatabaseFileName = RIGHT(@CurrentDatabaseFileName,LEN(@CurrentDatabaseFileName) - 1) @@ -3157,7 +3163,7 @@ BEGIN WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) WHEN EXISTS (SELECT * FROM @CurrentURLs) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentURLs) END - + LEN(REPLACE(REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN '1' WHEN @CurrentNumberOfFiles >= 10 THEN '01' ELSE '' END)) + + LEN(REPLACE(REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @CurrentNumberOfFiles >= 1 AND @CurrentNumberOfFiles <= 9 THEN '1' WHEN @CurrentNumberOfFiles >= 10 THEN '01' END)) -- The maximum length of a backup device is 259 characters IF @CurrentMaxFilePathLength > 259 @@ -3183,7 +3189,7 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 0) AND Mirror = 0 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles >= 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) END) IF @CurrentDirectoryPath = 'NUL' BEGIN diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 52b491d0..39373f45 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -38,7 +38,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-12 16:01:32 //-- + --// Version: 2020-01-13 20:08:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 8cff1a7d..6abb1f77 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-12 16:01:32 //-- + --// Version: 2020-01-13 20:08:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 98d19b99..a0548a8c 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-12 16:01:32 +Version: 2020-01-13 20:08:15 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-12 16:01:32 //-- + --// Version: 2020-01-13 20:08:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -432,7 +432,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-12 16:01:32 //-- + --// Version: 2020-01-13 20:08:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3442,6 +3442,12 @@ BEGIN SET @Updated = 1 END + IF CHARINDEX('of.',@CurrentDatabaseFileName) > 0 + BEGIN + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'of.','.') + SET @Updated = 1 + END + IF LEFT(@CurrentDatabaseFileName,1) = '_' BEGIN SET @CurrentDatabaseFileName = RIGHT(@CurrentDatabaseFileName,LEN(@CurrentDatabaseFileName) - 1) @@ -3511,7 +3517,7 @@ BEGIN WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) WHEN EXISTS (SELECT * FROM @CurrentURLs) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentURLs) END - + LEN(REPLACE(REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN '1' WHEN @CurrentNumberOfFiles >= 10 THEN '01' ELSE '' END)) + + LEN(REPLACE(REPLACE(@CurrentDatabaseFileName,'{DatabaseName}',@CurrentDatabaseNameFS), '{FileNumber}', CASE WHEN @CurrentNumberOfFiles >= 1 AND @CurrentNumberOfFiles <= 9 THEN '1' WHEN @CurrentNumberOfFiles >= 10 THEN '01' END)) -- The maximum length of a backup device is 259 characters IF @CurrentMaxFilePathLength > 259 @@ -3537,7 +3543,7 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 0) AND Mirror = 0 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles >= 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar),2) END) IF @CurrentDirectoryPath = 'NUL' BEGIN @@ -4438,7 +4444,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-12 16:01:32 //-- + --// Version: 2020-01-13 20:08:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6293,7 +6299,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-12 16:01:32 //-- + --// Version: 2020-01-13 20:08:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 1ebeba2e078fddee2ca20fe2e16add393de17305 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 14 Jan 2020 21:53:36 +0100 Subject: [PATCH 154/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 54 +++++++------ DatabaseIntegrityCheck.sql | 48 ++++++------ IndexOptimize.sql | 48 ++++++------ MaintenanceSolution.sql | 154 ++++++++++++++++++++----------------- 5 files changed, 165 insertions(+), 141 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index cfcd7909..4543381d 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-13 20:08:15 //-- + --// Version: 2020-01-14 21:48:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 990a1fb3..b39bccfd 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-13 20:08:15 //-- + --// Version: 2020-01-14 21:48:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2552,6 +2552,14 @@ BEGIN SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + BEGIN + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @@ -2562,6 +2570,26 @@ BEGIN FROM sys.databases WHERE [name] = @CurrentDatabaseName + BEGIN + SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Encrypted: ' + CASE WHEN @CurrentIsEncrypted = 1 THEN 'Yes' WHEN @CurrentIsEncrypted = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + SELECT @CurrentMaxTransferSize = CASE WHEN @MaxTransferSize IS NOT NULL THEN @MaxTransferSize WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND @Version >= 13.04446 THEN 65537 @@ -2692,36 +2720,12 @@ BEGIN SET @CurrentLogShippingRole = 'SECONDARY' END - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentIsDatabaseAccessible IS NOT NULL BEGIN SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Encrypted: ' + CASE WHEN @CurrentIsEncrypted = 1 THEN 'Yes' WHEN @CurrentIsEncrypted = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentAvailabilityGroup IS NOT NULL BEGIN SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 39373f45..39d74627 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -38,7 +38,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-13 20:08:15 //-- + --// Version: 2020-01-14 21:48:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1305,6 +1305,14 @@ BEGIN SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + BEGIN + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @@ -1313,6 +1321,23 @@ BEGIN FROM sys.databases WHERE [name] = @CurrentDatabaseName + BEGIN + SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + IF @CurrentDatabaseState = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 BEGIN IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) AND database_guid IS NOT NULL) @@ -1348,33 +1373,12 @@ BEGIN WHERE database_id = DB_ID(@CurrentDatabaseName) END - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentIsDatabaseAccessible IS NOT NULL BEGIN SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentAvailabilityGroup IS NOT NULL BEGIN SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 6abb1f77..0dc56bf2 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-13 20:08:15 //-- + --// Version: 2020-01-14 21:48:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1417,6 +1417,14 @@ BEGIN SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + BEGIN + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @@ -1425,6 +1433,23 @@ BEGIN FROM sys.databases WHERE [name] = @CurrentDatabaseName + BEGIN + SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + IF @CurrentDatabaseState = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 BEGIN IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) AND database_guid IS NOT NULL) @@ -1454,33 +1479,12 @@ BEGIN WHERE database_id = DB_ID(@CurrentDatabaseName) END - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentIsDatabaseAccessible IS NOT NULL BEGIN SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentAvailabilityGroup IS NOT NULL BEGIN SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index a0548a8c..5851161c 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-13 20:08:15 +Version: 2020-01-14 21:48:14 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-13 20:08:15 //-- + --// Version: 2020-01-14 21:48:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -432,7 +432,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-13 20:08:15 //-- + --// Version: 2020-01-14 21:48:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2906,6 +2906,14 @@ BEGIN SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + BEGIN + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @@ -2916,6 +2924,26 @@ BEGIN FROM sys.databases WHERE [name] = @CurrentDatabaseName + BEGIN + SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Encrypted: ' + CASE WHEN @CurrentIsEncrypted = 1 THEN 'Yes' WHEN @CurrentIsEncrypted = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + SELECT @CurrentMaxTransferSize = CASE WHEN @MaxTransferSize IS NOT NULL THEN @MaxTransferSize WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND @Version >= 13.04446 THEN 65537 @@ -3046,36 +3074,12 @@ BEGIN SET @CurrentLogShippingRole = 'SECONDARY' END - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentIsDatabaseAccessible IS NOT NULL BEGIN SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Encrypted: ' + CASE WHEN @CurrentIsEncrypted = 1 THEN 'Yes' WHEN @CurrentIsEncrypted = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentAvailabilityGroup IS NOT NULL BEGIN SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') @@ -4444,7 +4448,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-13 20:08:15 //-- + --// Version: 2020-01-14 21:48:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5711,6 +5715,14 @@ BEGIN SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + BEGIN + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @@ -5719,6 +5731,23 @@ BEGIN FROM sys.databases WHERE [name] = @CurrentDatabaseName + BEGIN + SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + IF @CurrentDatabaseState = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 BEGIN IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) AND database_guid IS NOT NULL) @@ -5754,33 +5783,12 @@ BEGIN WHERE database_id = DB_ID(@CurrentDatabaseName) END - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentIsDatabaseAccessible IS NOT NULL BEGIN SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentAvailabilityGroup IS NOT NULL BEGIN SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') @@ -6299,7 +6307,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-13 20:08:15 //-- + --// Version: 2020-01-14 21:48:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7664,6 +7672,14 @@ BEGIN SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + BEGIN + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + SELECT @CurrentUserAccess = user_access_desc, @CurrentIsReadOnly = is_read_only, @CurrentDatabaseState = state_desc, @@ -7672,6 +7688,23 @@ BEGIN FROM sys.databases WHERE [name] = @CurrentDatabaseName + BEGIN + SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + IF @CurrentDatabaseState = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 BEGIN IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) AND database_guid IS NOT NULL) @@ -7701,33 +7734,12 @@ BEGIN WHERE database_id = DB_ID(@CurrentDatabaseName) END - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'State: ' + @CurrentDatabaseState - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Standby: ' + CASE WHEN @CurrentInStandby = 1 THEN 'Yes' ELSE 'No' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Updateability: ' + CASE WHEN @CurrentIsReadOnly = 1 THEN 'READ_ONLY' WHEN @CurrentIsReadOnly = 0 THEN 'READ_WRITE' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'User access: ' + @CurrentUserAccess - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentIsDatabaseAccessible IS NOT NULL BEGIN SET @DatabaseMessage = 'Is accessible: ' + CASE WHEN @CurrentIsDatabaseAccessible = 1 THEN 'Yes' ELSE 'No' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentAvailabilityGroup IS NOT NULL BEGIN SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') From b551a6bdee6b134b49629caca2b9ee55ee630c4e Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 26 Jan 2020 12:21:49 +0100 Subject: [PATCH 155/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 4 ++-- MaintenanceSolution.sql | 12 ++++++------ 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 4543381d..5d4c02ac 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-14 21:48:14 //-- + --// Version: 2020-01-26 12:07:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index b39bccfd..072b69c9 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-14 21:48:14 //-- + --// Version: 2020-01-26 12:07:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 39d74627..1b53ad6e 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -38,7 +38,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-14 21:48:14 //-- + --// Version: 2020-01-26 12:07:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 0dc56bf2..850aa463 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-14 21:48:14 //-- + --// Version: 2020-01-26 12:07:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -152,7 +152,7 @@ BEGIN DECLARE @CurrentUpdateStatistics nvarchar(max) DECLARE @CurrentStatisticsSample int DECLARE @CurrentStatisticsResample nvarchar(max) - DECLARE @CurrentDelay datetime2 + DECLARE @CurrentDelay datetime DECLARE @tmpDatabases TABLE (ID int IDENTITY, DatabaseName nvarchar(max), diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 5851161c..37427f2d 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-14 21:48:14 +Version: 2020-01-26 12:07:49 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-14 21:48:14 //-- + --// Version: 2020-01-26 12:07:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -432,7 +432,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-14 21:48:14 //-- + --// Version: 2020-01-26 12:07:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4448,7 +4448,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-14 21:48:14 //-- + --// Version: 2020-01-26 12:07:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6307,7 +6307,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-14 21:48:14 //-- + --// Version: 2020-01-26 12:07:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6407,7 +6407,7 @@ BEGIN DECLARE @CurrentUpdateStatistics nvarchar(max) DECLARE @CurrentStatisticsSample int DECLARE @CurrentStatisticsResample nvarchar(max) - DECLARE @CurrentDelay datetime2 + DECLARE @CurrentDelay datetime DECLARE @tmpDatabases TABLE (ID int IDENTITY, DatabaseName nvarchar(max), From a05ee433129e0dc84cb478204b7f411d4c35c5b1 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 26 Jan 2020 12:33:09 +0100 Subject: [PATCH 156/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 4 ++-- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 ++++++------ 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 5d4c02ac..73145931 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:07:49 //-- + --// Version: 2020-01-26 12:29:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 072b69c9..40ca83bc 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:07:49 //-- + --// Version: 2020-01-26 12:29:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2176,7 +2176,7 @@ BEGIN SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 END - IF @DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') + IF @DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @DatabaseOrder is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16, 2 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 1b53ad6e..ff206f14 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -38,7 +38,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:07:49 //-- + --// Version: 2020-01-26 12:29:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 850aa463..f7448673 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:07:49 //-- + --// Version: 2020-01-26 12:29:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 37427f2d..a5b38c75 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-26 12:07:49 +Version: 2020-01-26 12:29:21 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:07:49 //-- + --// Version: 2020-01-26 12:29:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -432,7 +432,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:07:49 //-- + --// Version: 2020-01-26 12:29:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2530,7 +2530,7 @@ BEGIN SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 END - IF @DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') + IF @DatabaseOrder IN('LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC','LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC') AND NOT EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @DatabaseOrder is not supported. The column sys.dm_db_log_stats.log_since_last_log_backup_mb is not available in this version of SQL Server.', 16, 2 @@ -4448,7 +4448,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:07:49 //-- + --// Version: 2020-01-26 12:29:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6307,7 +6307,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:07:49 //-- + --// Version: 2020-01-26 12:29:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From e7406a1c413dba466b2863230ac14124891a10ed Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 26 Jan 2020 12:57:08 +0100 Subject: [PATCH 157/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 22 +++++++++++++++++++--- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 30 +++++++++++++++++++++++------- 5 files changed, 45 insertions(+), 13 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 73145931..9be1e693 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:29:21 //-- + --// Version: 2020-01-26 12:52:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 40ca83bc..0e6c89d7 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:29:21 //-- + --// Version: 2020-01-26 12:52:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index ff206f14..4cc06ec5 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -12,6 +12,7 @@ ALTER PROCEDURE [dbo].[DatabaseIntegrityCheck] @Databases nvarchar(max) = NULL, @CheckCommands nvarchar(max) = 'CHECKDB', @PhysicalOnly nvarchar(max) = 'N', +@DataPurity nvarchar(max) = 'N', @NoIndex nvarchar(max) = 'N', @ExtendedLogicalChecks nvarchar(max) = 'N', @TabLock nvarchar(max) = 'N', @@ -38,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:29:21 //-- + --// Version: 2020-01-26 12:52:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -197,6 +198,7 @@ BEGIN SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @Parameters += ', @CheckCommands = ' + ISNULL('''' + REPLACE(@CheckCommands,'''','''''') + '''','NULL') SET @Parameters += ', @PhysicalOnly = ' + ISNULL('''' + REPLACE(@PhysicalOnly,'''','''''') + '''','NULL') + SET @Parameters += ', @DataPurity = ' + ISNULL('''' + REPLACE(@DataPurity,'''','''''') + '''','NULL') SET @Parameters += ', @NoIndex = ' + ISNULL('''' + REPLACE(@NoIndex,'''','''''') + '''','NULL') SET @Parameters += ', @ExtendedLogicalChecks = ' + ISNULL('''' + REPLACE(@ExtendedLogicalChecks,'''','''''') + '''','NULL') SET @Parameters += ', @TabLock = ' + ISNULL('''' + REPLACE(@TabLock,'''','''''') + '''','NULL') @@ -710,6 +712,20 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @DataPurity NOT IN ('Y','N') OR @DataPurity IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataPurity is not supported.', 16, 1 + END + + IF @PhysicalOnly = 'Y' AND @DataPurity = 'Y' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameters @PhysicalOnly and @DataPurity cannot be used together.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -1425,7 +1441,7 @@ BEGIN SET @CurrentCommand += 'DBCC CHECKDB (' + QUOTENAME(@CurrentDatabaseName) IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' SET @CurrentCommand += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'N' SET @CurrentCommand += ', DATA_PURITY' + IF @DataPurity = 'Y' SET @CurrentCommand += ', DATA_PURITY' IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand += ', EXTENDED_LOGICAL_CHECKS' IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' @@ -1716,7 +1732,7 @@ BEGIN SET @CurrentCommand += 'DBCC CHECKTABLE (''' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + '''' IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' SET @CurrentCommand += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'N' SET @CurrentCommand += ', DATA_PURITY' + IF @DataPurity = 'Y' SET @CurrentCommand += ', DATA_PURITY' IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand += ', EXTENDED_LOGICAL_CHECKS' IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' diff --git a/IndexOptimize.sql b/IndexOptimize.sql index f7448673..a9dff53e 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:29:21 //-- + --// Version: 2020-01-26 12:52:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index a5b38c75..41f7f274 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-26 12:29:21 +Version: 2020-01-26 12:52:50 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:29:21 //-- + --// Version: 2020-01-26 12:52:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -432,7 +432,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:29:21 //-- + --// Version: 2020-01-26 12:52:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4422,6 +4422,7 @@ ALTER PROCEDURE [dbo].[DatabaseIntegrityCheck] @Databases nvarchar(max) = NULL, @CheckCommands nvarchar(max) = 'CHECKDB', @PhysicalOnly nvarchar(max) = 'N', +@DataPurity nvarchar(max) = 'N', @NoIndex nvarchar(max) = 'N', @ExtendedLogicalChecks nvarchar(max) = 'N', @TabLock nvarchar(max) = 'N', @@ -4448,7 +4449,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:29:21 //-- + --// Version: 2020-01-26 12:52:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4607,6 +4608,7 @@ BEGIN SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','NULL') SET @Parameters += ', @CheckCommands = ' + ISNULL('''' + REPLACE(@CheckCommands,'''','''''') + '''','NULL') SET @Parameters += ', @PhysicalOnly = ' + ISNULL('''' + REPLACE(@PhysicalOnly,'''','''''') + '''','NULL') + SET @Parameters += ', @DataPurity = ' + ISNULL('''' + REPLACE(@DataPurity,'''','''''') + '''','NULL') SET @Parameters += ', @NoIndex = ' + ISNULL('''' + REPLACE(@NoIndex,'''','''''') + '''','NULL') SET @Parameters += ', @ExtendedLogicalChecks = ' + ISNULL('''' + REPLACE(@ExtendedLogicalChecks,'''','''''') + '''','NULL') SET @Parameters += ', @TabLock = ' + ISNULL('''' + REPLACE(@TabLock,'''','''''') + '''','NULL') @@ -5120,6 +5122,20 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @DataPurity NOT IN ('Y','N') OR @DataPurity IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataPurity is not supported.', 16, 1 + END + + IF @PhysicalOnly = 'Y' AND @DataPurity = 'Y' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameters @PhysicalOnly and @DataPurity cannot be used together.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -5835,7 +5851,7 @@ BEGIN SET @CurrentCommand += 'DBCC CHECKDB (' + QUOTENAME(@CurrentDatabaseName) IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' SET @CurrentCommand += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'N' SET @CurrentCommand += ', DATA_PURITY' + IF @DataPurity = 'Y' SET @CurrentCommand += ', DATA_PURITY' IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand += ', EXTENDED_LOGICAL_CHECKS' IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' @@ -6126,7 +6142,7 @@ BEGIN SET @CurrentCommand += 'DBCC CHECKTABLE (''' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + '''' IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' SET @CurrentCommand += ') WITH NO_INFOMSGS, ALL_ERRORMSGS' - IF @PhysicalOnly = 'N' SET @CurrentCommand += ', DATA_PURITY' + IF @DataPurity = 'Y' SET @CurrentCommand += ', DATA_PURITY' IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand += ', EXTENDED_LOGICAL_CHECKS' IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' @@ -6307,7 +6323,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:29:21 //-- + --// Version: 2020-01-26 12:52:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From d76ec19a22aa2670ac75e8f565946882e9945774 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 26 Jan 2020 12:57:33 +0100 Subject: [PATCH 158/188] Add files via upload From 588c16545cdb59432489f73695fbb7f6d0161112 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 26 Jan 2020 14:14:32 +0100 Subject: [PATCH 159/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 40 +++++++++++++++---------------- MaintenanceSolution.sql | 48 +++++++++++++++++++------------------- 5 files changed, 47 insertions(+), 47 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 9be1e693..40a3d7b3 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:52:50 //-- + --// Version: 2020-01-26 14:06:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 0e6c89d7..6ef722fe 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:52:50 //-- + --// Version: 2020-01-26 14:06:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 4cc06ec5..3abe59d2 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:52:50 //-- + --// Version: 2020-01-26 14:06:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index a9dff53e..e6085a14 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:52:50 //-- + --// Version: 2020-01-26 14:06:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2026,25 +2026,6 @@ BEGIN ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END - -- Create statistics comment - IF @CurrentStatisticsID IS NOT NULL - BEGIN - SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment += 'IndexType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' - IF @CurrentIndexID IS NOT NULL SET @CurrentComment += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' - SET @CurrentComment += 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Y' WHEN @CurrentIsIncremental = 0 THEN 'N' ELSE 'N/A' END + ', ' - SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' - SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') - END - - IF @CurrentStatisticsID IS NOT NULL AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) - BEGIN - SET @CurrentExtendedInfo = (SELECT * - FROM (SELECT CAST(@CurrentRowCount AS nvarchar) AS [RowCount], - CAST(@CurrentModificationCounter AS nvarchar) AS ModificationCounter - ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) - END - IF @CurrentIndexID IS NOT NULL AND @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentDatabaseContext = @CurrentDatabaseName @@ -2172,6 +2153,25 @@ BEGIN SET @CurrentMaxDOP = @MaxDOP + -- Create statistics comment + IF @CurrentStatisticsID IS NOT NULL + BEGIN + SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'IndexType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' + IF @CurrentIndexID IS NOT NULL SET @CurrentComment += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Y' WHEN @CurrentIsIncremental = 0 THEN 'N' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' + SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') + END + + IF @CurrentStatisticsID IS NOT NULL AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) + BEGIN + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentRowCount AS nvarchar) AS [RowCount], + CAST(@CurrentModificationCounter AS nvarchar) AS ModificationCounter + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) + END + IF @CurrentStatisticsID IS NOT NULL AND @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentDatabaseContext = @CurrentDatabaseName diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 41f7f274..d77fe0a9 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-26 12:52:50 +Version: 2020-01-26 14:06:53 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:52:50 //-- + --// Version: 2020-01-26 14:06:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -432,7 +432,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:52:50 //-- + --// Version: 2020-01-26 14:06:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4449,7 +4449,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:52:50 //-- + --// Version: 2020-01-26 14:06:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6323,7 +6323,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 12:52:50 //-- + --// Version: 2020-01-26 14:06:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8297,25 +8297,6 @@ BEGIN ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END - -- Create statistics comment - IF @CurrentStatisticsID IS NOT NULL - BEGIN - SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment += 'IndexType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' - IF @CurrentIndexID IS NOT NULL SET @CurrentComment += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' - SET @CurrentComment += 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Y' WHEN @CurrentIsIncremental = 0 THEN 'N' ELSE 'N/A' END + ', ' - SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' - SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') - END - - IF @CurrentStatisticsID IS NOT NULL AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) - BEGIN - SET @CurrentExtendedInfo = (SELECT * - FROM (SELECT CAST(@CurrentRowCount AS nvarchar) AS [RowCount], - CAST(@CurrentModificationCounter AS nvarchar) AS ModificationCounter - ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) - END - IF @CurrentIndexID IS NOT NULL AND @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentDatabaseContext = @CurrentDatabaseName @@ -8443,6 +8424,25 @@ BEGIN SET @CurrentMaxDOP = @MaxDOP + -- Create statistics comment + IF @CurrentStatisticsID IS NOT NULL + BEGIN + SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'IndexType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' + IF @CurrentIndexID IS NOT NULL SET @CurrentComment += 'IndexType: ' + CASE WHEN @CurrentIndexType = 1 THEN 'Clustered' WHEN @CurrentIndexType = 2 THEN 'NonClustered' WHEN @CurrentIndexType = 3 THEN 'XML' WHEN @CurrentIndexType = 4 THEN 'Spatial' WHEN @CurrentIndexType = 5 THEN 'Clustered Columnstore' WHEN @CurrentIndexType = 6 THEN 'NonClustered Columnstore' WHEN @CurrentIndexType = 7 THEN 'NonClustered Hash' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Y' WHEN @CurrentIsIncremental = 0 THEN 'N' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' + SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') + END + + IF @CurrentStatisticsID IS NOT NULL AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) + BEGIN + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentRowCount AS nvarchar) AS [RowCount], + CAST(@CurrentModificationCounter AS nvarchar) AS ModificationCounter + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) + END + IF @CurrentStatisticsID IS NOT NULL AND @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentDatabaseContext = @CurrentDatabaseName From 9a855afe23d4cbd79a25cc19fd4fd305b35ca076 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 25 Oct 2020 18:23:54 +0100 Subject: [PATCH 160/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 12 ++---------- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 20 ++++++-------------- 5 files changed, 11 insertions(+), 27 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 40a3d7b3..3faffff2 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 14:06:53 //-- + --// Version: 2020-10-25 18:05:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 6ef722fe..26ed0c22 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 14:06:53 //-- + --// Version: 2020-10-25 18:05:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -775,7 +775,7 @@ BEGIN --// Check directories //-- ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux') OR (DirectoryPath = 'NUL' AND @HostPlatform = 'Windows')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) + IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux') OR DirectoryPath = 'NUL') OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @Directory is not supported.', 16, 1 @@ -1123,12 +1123,6 @@ BEGIN SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.', 16, 2 END - IF @CleanupTime IS NOT NULL AND @HostPlatform = 'Linux' - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.', 16, 3 - END - IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -3384,7 +3378,6 @@ BEGIN -- Delete old backup files, before backup IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateOutput <> 0 OR CreateOutput IS NULL) - AND @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) AND @CurrentBackupType = @BackupType BEGIN @@ -3876,7 +3869,6 @@ BEGIN -- Delete old backup files, after backup IF ((@CurrentBackupOutput = 0 AND @Verify = 'N') OR (@CurrentBackupOutput = 0 AND @Verify = 'Y' AND NOT EXISTS (SELECT * FROM @CurrentBackupSet WHERE VerifyOutput <> 0 OR VerifyOutput IS NULL))) - AND @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) AND @CurrentBackupType = @BackupType BEGIN diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 3abe59d2..590578f4 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 14:06:53 //-- + --// Version: 2020-10-25 18:05:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index e6085a14..160fb931 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 14:06:53 //-- + --// Version: 2020-10-25 18:05:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index d77fe0a9..060d0410 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-01-26 14:06:53 +Version: 2020-10-25 18:05:29 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 14:06:53 //-- + --// Version: 2020-10-25 18:05:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -432,7 +432,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 14:06:53 //-- + --// Version: 2020-10-25 18:05:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1129,7 +1129,7 @@ BEGIN --// Check directories //-- ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux') OR (DirectoryPath = 'NUL' AND @HostPlatform = 'Windows')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) + IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux') OR DirectoryPath = 'NUL') OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @Directory is not supported.', 16, 1 @@ -1477,12 +1477,6 @@ BEGIN SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.', 16, 2 END - IF @CleanupTime IS NOT NULL AND @HostPlatform = 'Linux' - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Linux.', 16, 3 - END - IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -3738,7 +3732,6 @@ BEGIN -- Delete old backup files, before backup IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE CreateOutput <> 0 OR CreateOutput IS NULL) - AND @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) AND @CurrentBackupType = @BackupType BEGIN @@ -4230,7 +4223,6 @@ BEGIN -- Delete old backup files, after backup IF ((@CurrentBackupOutput = 0 AND @Verify = 'N') OR (@CurrentBackupOutput = 0 AND @Verify = 'Y' AND NOT EXISTS (SELECT * FROM @CurrentBackupSet WHERE VerifyOutput <> 0 OR VerifyOutput IS NULL))) - AND @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) AND @CurrentBackupType = @BackupType BEGIN @@ -4449,7 +4441,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 14:06:53 //-- + --// Version: 2020-10-25 18:05:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6323,7 +6315,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-01-26 14:06:53 //-- + --// Version: 2020-10-25 18:05:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From a0661eff7bef9d141740ac70be69647aba414b6c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 1 Nov 2020 18:32:29 +0100 Subject: [PATCH 161/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 82 +++++++++++++++++----------------- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 90 ++++++++++++++++++++------------------ 5 files changed, 93 insertions(+), 85 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 3faffff2..55eb580b 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-10-25 18:05:29 //-- + --// Version: 2020-11-01 18:16:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 26ed0c22..0a9cc1c4 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-10-25 18:05:29 //-- + --// Version: 2020-11-01 18:16:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -688,12 +688,19 @@ BEGIN END ---------------------------------------------------------------------------------------------------- - --// Select directories //-- + --// Select default directory //-- ---------------------------------------------------------------------------------------------------- - IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + IF @Directory IS NULL AND @URL IS NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN - EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultDirectory OUTPUT + IF @Version >= 15 + BEGIN + SET @DefaultDirectory = CAST(SERVERPROPERTY('InstanceDefaultBackupPath') AS nvarchar(max)) + END + ELSE + BEGIN + EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultDirectory OUTPUT + END IF @DefaultDirectory LIKE 'http://%' OR @DefaultDirectory LIKE 'https://%' BEGIN @@ -705,42 +712,39 @@ BEGIN SELECT 1, @DefaultDirectory, 0, 0 END END - IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Linux' - BEGIN - INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) - SELECT 1, '.', 0, 0 - END - ELSE - BEGIN - SET @Directory = REPLACE(@Directory, CHAR(10), '') - SET @Directory = REPLACE(@Directory, CHAR(13), '') - WHILE CHARINDEX(@StringDelimiter + ' ', @Directory) > 0 SET @Directory = REPLACE(@Directory, @StringDelimiter + ' ', @StringDelimiter) - WHILE CHARINDEX(' ' + @StringDelimiter, @Directory) > 0 SET @Directory = REPLACE(@Directory, ' ' + @StringDelimiter, @StringDelimiter) + ---------------------------------------------------------------------------------------------------- + --// Select directories //-- + ---------------------------------------------------------------------------------------------------- - SET @Directory = LTRIM(RTRIM(@Directory)); + SET @Directory = REPLACE(@Directory, CHAR(10), '') + SET @Directory = REPLACE(@Directory, CHAR(13), '') - WITH Directories (StartPosition, EndPosition, Directory) AS - ( - SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, 1), 0), LEN(@Directory) + 1) AS EndPosition, - SUBSTRING(@Directory, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, 1), 0), LEN(@Directory) + 1) - 1) AS Directory - WHERE @Directory IS NOT NULL - UNION ALL - SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) AS EndPosition, - SUBSTRING(@Directory, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) - EndPosition - 1) AS Directory - FROM Directories - WHERE EndPosition < LEN(@Directory) + 1 - ) - INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) - SELECT ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS ID, - Directory, - 0, - 0 - FROM Directories - OPTION (MAXRECURSION 0) - END + WHILE CHARINDEX(@StringDelimiter + ' ', @Directory) > 0 SET @Directory = REPLACE(@Directory, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @Directory) > 0 SET @Directory = REPLACE(@Directory, ' ' + @StringDelimiter, @StringDelimiter) + + SET @Directory = LTRIM(RTRIM(@Directory)); + + WITH Directories (StartPosition, EndPosition, Directory) AS + ( + SELECT 1 AS StartPosition, + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, 1), 0), LEN(@Directory) + 1) AS EndPosition, + SUBSTRING(@Directory, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, 1), 0), LEN(@Directory) + 1) - 1) AS Directory + WHERE @Directory IS NOT NULL + UNION ALL + SELECT CAST(EndPosition AS int) + 1 AS StartPosition, + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) AS EndPosition, + SUBSTRING(@Directory, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) - EndPosition - 1) AS Directory + FROM Directories + WHERE EndPosition < LEN(@Directory) + 1 + ) + INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) + SELECT ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS ID, + Directory, + 0, + 0 + FROM Directories + OPTION (MAXRECURSION 0) SET @MirrorDirectory = REPLACE(@MirrorDirectory, CHAR(10), '') SET @MirrorDirectory = REPLACE(@MirrorDirectory, CHAR(13), '') @@ -775,7 +779,7 @@ BEGIN --// Check directories //-- ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux') OR DirectoryPath = 'NUL') OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) + IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR DirectoryPath = 'NUL') OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @Directory is not supported.', 16, 1 @@ -813,7 +817,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 1 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 590578f4..f033b911 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-10-25 18:05:29 //-- + --// Version: 2020-11-01 18:16:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 160fb931..79dc6aa1 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-10-25 18:05:29 //-- + --// Version: 2020-11-01 18:16:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 060d0410..ad7f580e 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-10-25 18:05:29 +Version: 2020-11-01 18:16:36 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-10-25 18:05:29 //-- + --// Version: 2020-11-01 18:16:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -432,7 +432,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-10-25 18:05:29 //-- + --// Version: 2020-11-01 18:16:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1042,12 +1042,19 @@ BEGIN END ---------------------------------------------------------------------------------------------------- - --// Select directories //-- + --// Select default directory //-- ---------------------------------------------------------------------------------------------------- - IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + IF @Directory IS NULL AND @URL IS NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN - EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultDirectory OUTPUT + IF @Version >= 15 + BEGIN + SET @DefaultDirectory = CAST(SERVERPROPERTY('InstanceDefaultBackupPath') AS nvarchar(max)) + END + ELSE + BEGIN + EXECUTE [master].dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultDirectory OUTPUT + END IF @DefaultDirectory LIKE 'http://%' OR @DefaultDirectory LIKE 'https://%' BEGIN @@ -1059,42 +1066,39 @@ BEGIN SELECT 1, @DefaultDirectory, 0, 0 END END - IF @Directory IS NULL AND @URL IS NULL AND @HostPlatform = 'Linux' - BEGIN - INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) - SELECT 1, '.', 0, 0 - END - ELSE - BEGIN - SET @Directory = REPLACE(@Directory, CHAR(10), '') - SET @Directory = REPLACE(@Directory, CHAR(13), '') - WHILE CHARINDEX(@StringDelimiter + ' ', @Directory) > 0 SET @Directory = REPLACE(@Directory, @StringDelimiter + ' ', @StringDelimiter) - WHILE CHARINDEX(' ' + @StringDelimiter, @Directory) > 0 SET @Directory = REPLACE(@Directory, ' ' + @StringDelimiter, @StringDelimiter) + ---------------------------------------------------------------------------------------------------- + --// Select directories //-- + ---------------------------------------------------------------------------------------------------- - SET @Directory = LTRIM(RTRIM(@Directory)); + SET @Directory = REPLACE(@Directory, CHAR(10), '') + SET @Directory = REPLACE(@Directory, CHAR(13), '') - WITH Directories (StartPosition, EndPosition, Directory) AS - ( - SELECT 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, 1), 0), LEN(@Directory) + 1) AS EndPosition, - SUBSTRING(@Directory, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, 1), 0), LEN(@Directory) + 1) - 1) AS Directory - WHERE @Directory IS NOT NULL - UNION ALL - SELECT CAST(EndPosition AS int) + 1 AS StartPosition, - ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) AS EndPosition, - SUBSTRING(@Directory, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) - EndPosition - 1) AS Directory - FROM Directories - WHERE EndPosition < LEN(@Directory) + 1 - ) - INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) - SELECT ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS ID, - Directory, - 0, - 0 - FROM Directories - OPTION (MAXRECURSION 0) - END + WHILE CHARINDEX(@StringDelimiter + ' ', @Directory) > 0 SET @Directory = REPLACE(@Directory, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @Directory) > 0 SET @Directory = REPLACE(@Directory, ' ' + @StringDelimiter, @StringDelimiter) + + SET @Directory = LTRIM(RTRIM(@Directory)); + + WITH Directories (StartPosition, EndPosition, Directory) AS + ( + SELECT 1 AS StartPosition, + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, 1), 0), LEN(@Directory) + 1) AS EndPosition, + SUBSTRING(@Directory, 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, 1), 0), LEN(@Directory) + 1) - 1) AS Directory + WHERE @Directory IS NOT NULL + UNION ALL + SELECT CAST(EndPosition AS int) + 1 AS StartPosition, + ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) AS EndPosition, + SUBSTRING(@Directory, EndPosition + 1, ISNULL(NULLIF(CHARINDEX(@StringDelimiter, @Directory, EndPosition + 1), 0), LEN(@Directory) + 1) - EndPosition - 1) AS Directory + FROM Directories + WHERE EndPosition < LEN(@Directory) + 1 + ) + INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) + SELECT ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS ID, + Directory, + 0, + 0 + FROM Directories + OPTION (MAXRECURSION 0) SET @MirrorDirectory = REPLACE(@MirrorDirectory, CHAR(10), '') SET @MirrorDirectory = REPLACE(@MirrorDirectory, CHAR(13), '') @@ -1129,7 +1133,7 @@ BEGIN --// Check directories //-- ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux') OR DirectoryPath = 'NUL') OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) + IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR DirectoryPath = 'NUL') OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @Directory is not supported.', 16, 1 @@ -1167,7 +1171,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux') OR (DirectoryPath LIKE '.' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) + IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 1 AND (NOT (DirectoryPath LIKE '_:' OR DirectoryPath LIKE '_:\%' OR DirectoryPath LIKE '\\%\%' OR (DirectoryPath LIKE '/%/%' AND @HostPlatform = 'Linux')) OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 1 @@ -4441,7 +4445,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-10-25 18:05:29 //-- + --// Version: 2020-11-01 18:16:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6315,7 +6319,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-10-25 18:05:29 //-- + --// Version: 2020-11-01 18:16:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 1f55a0f760fb1311142a92fe22a1a4f9423b77a7 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 15 Nov 2020 15:00:34 +0100 Subject: [PATCH 162/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 8 ++++---- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 16 ++++++++-------- 5 files changed, 15 insertions(+), 15 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 55eb580b..9660260c 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-01 18:16:36 //-- + --// Version: 2020-11-15 14:55:23 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 0a9cc1c4..ac10dea9 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-01 18:16:36 //-- + --// Version: 2020-11-15 14:55:23 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2590,7 +2590,7 @@ BEGIN SELECT @CurrentMaxTransferSize = CASE WHEN @MaxTransferSize IS NOT NULL THEN @MaxTransferSize - WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND @Version >= 13.04446 THEN 65537 + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8) THEN 65537 END IF @CurrentDatabaseState = 'ONLINE' @@ -2695,7 +2695,7 @@ BEGIN WHEN @NumberOfFiles = 1 THEN @NumberOfFiles WHEN @NumberOfFiles > 1 AND (BackupSize >= MinBackupSizeForMultipleFiles OR MinBackupSizeForMultipleFiles IS NULL OR BackupSize IS NULL) THEN @NumberOfFiles WHEN @NumberOfFiles > 1 AND (BackupSize < MinBackupSizeForMultipleFiles) THEN NumberOfDirectories - WHEN @NumberOfFiles IS NULL AND @MaxFileSize IS NOT NULL AND BackupSize IS NULL THEN NumberOfDirectories + WHEN @NumberOfFiles IS NULL AND @MaxFileSize IS NOT NULL AND (BackupSize IS NULL OR BackupSize = 0) THEN NumberOfDirectories WHEN @NumberOfFiles IS NULL AND @MaxFileSize IS NOT NULL THEN (SELECT MIN(NumberOfFilesInEachDirectory) FROM (SELECT ((BackupSize / NumberOfDirectories) / MaxFileSize + CASE WHEN (BackupSize / NumberOfDirectories) % MaxFileSize = 0 THEN 0 ELSE 1 END) AS NumberOfFilesInEachDirectory UNION @@ -3500,7 +3500,7 @@ BEGIN IF @Version >= 10 BEGIN - SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND @Version >= 13 AND @CurrentMaxTransferSize > 65536)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END + SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8) AND @CurrentMaxTransferSize >= 65537)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END END IF @CurrentBackupType = 'DIFF' SET @CurrentCommand += ', DIFFERENTIAL' diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index f033b911..ace55f59 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-01 18:16:36 //-- + --// Version: 2020-11-15 14:55:23 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 79dc6aa1..d8c22001 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-01 18:16:36 //-- + --// Version: 2020-11-15 14:55:23 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index ad7f580e..2adf3531 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-11-01 18:16:36 +Version: 2020-11-15 14:55:23 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-01 18:16:36 //-- + --// Version: 2020-11-15 14:55:23 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -432,7 +432,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-01 18:16:36 //-- + --// Version: 2020-11-15 14:55:23 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2944,7 +2944,7 @@ BEGIN SELECT @CurrentMaxTransferSize = CASE WHEN @MaxTransferSize IS NOT NULL THEN @MaxTransferSize - WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND @Version >= 13.04446 THEN 65537 + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8) THEN 65537 END IF @CurrentDatabaseState = 'ONLINE' @@ -3049,7 +3049,7 @@ BEGIN WHEN @NumberOfFiles = 1 THEN @NumberOfFiles WHEN @NumberOfFiles > 1 AND (BackupSize >= MinBackupSizeForMultipleFiles OR MinBackupSizeForMultipleFiles IS NULL OR BackupSize IS NULL) THEN @NumberOfFiles WHEN @NumberOfFiles > 1 AND (BackupSize < MinBackupSizeForMultipleFiles) THEN NumberOfDirectories - WHEN @NumberOfFiles IS NULL AND @MaxFileSize IS NOT NULL AND BackupSize IS NULL THEN NumberOfDirectories + WHEN @NumberOfFiles IS NULL AND @MaxFileSize IS NOT NULL AND (BackupSize IS NULL OR BackupSize = 0) THEN NumberOfDirectories WHEN @NumberOfFiles IS NULL AND @MaxFileSize IS NOT NULL THEN (SELECT MIN(NumberOfFilesInEachDirectory) FROM (SELECT ((BackupSize / NumberOfDirectories) / MaxFileSize + CASE WHEN (BackupSize / NumberOfDirectories) % MaxFileSize = 0 THEN 0 ELSE 1 END) AS NumberOfFilesInEachDirectory UNION @@ -3854,7 +3854,7 @@ BEGIN IF @Version >= 10 BEGIN - SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND @Version >= 13 AND @CurrentMaxTransferSize > 65536)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END + SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8) AND @CurrentMaxTransferSize >= 65537)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END END IF @CurrentBackupType = 'DIFF' SET @CurrentCommand += ', DIFFERENTIAL' @@ -4445,7 +4445,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-01 18:16:36 //-- + --// Version: 2020-11-15 14:55:23 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6319,7 +6319,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-01 18:16:36 //-- + --// Version: 2020-11-15 14:55:23 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 71cf3a299bede4c915a469751582c1d9e72e3243 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 15 Nov 2020 15:01:31 +0100 Subject: [PATCH 163/188] Add files via upload From c599c5545186ccafa111469f63f94d8f3f8ef4e4 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 15 Nov 2020 18:47:32 +0100 Subject: [PATCH 164/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 4 ++-- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 ++++++------ 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 9660260c..918b5099 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 14:55:23 //-- + --// Version: 2020-11-15 18:44:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index ac10dea9..b434d9e7 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,7 +78,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 14:55:23 //-- + --// Version: 2020-11-15 18:44:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2754,7 +2754,7 @@ BEGIN SET @DatabaseMessage = 'Differential base LSN: ' + ISNULL(CAST(@CurrentDifferentialBaseLSN AS nvarchar),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentBackupType = 'DIFF' + IF @CurrentBackupType = 'DIFF' OR @CurrentDifferentialBaseIsSnapshot IS NOT NULL BEGIN SET @DatabaseMessage = 'Differential base is snapshot: ' + CASE WHEN @CurrentDifferentialBaseIsSnapshot = 1 THEN 'Yes' WHEN @CurrentDifferentialBaseIsSnapshot = 0 THEN 'No' ELSE 'N/A' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index ace55f59..00a6e3b8 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 14:55:23 //-- + --// Version: 2020-11-15 18:44:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index d8c22001..7ddd6ef4 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 14:55:23 //-- + --// Version: 2020-11-15 18:44:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 2adf3531..71298e0e 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-11-15 14:55:23 +Version: 2020-11-15 18:44:03 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 14:55:23 //-- + --// Version: 2020-11-15 18:44:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -432,7 +432,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 14:55:23 //-- + --// Version: 2020-11-15 18:44:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3108,7 +3108,7 @@ BEGIN SET @DatabaseMessage = 'Differential base LSN: ' + ISNULL(CAST(@CurrentDifferentialBaseLSN AS nvarchar),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentBackupType = 'DIFF' + IF @CurrentBackupType = 'DIFF' OR @CurrentDifferentialBaseIsSnapshot IS NOT NULL BEGIN SET @DatabaseMessage = 'Differential base is snapshot: ' + CASE WHEN @CurrentDifferentialBaseIsSnapshot = 1 THEN 'Yes' WHEN @CurrentDifferentialBaseIsSnapshot = 0 THEN 'No' ELSE 'N/A' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -4445,7 +4445,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 14:55:23 //-- + --// Version: 2020-11-15 18:44:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6319,7 +6319,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 14:55:23 //-- + --// Version: 2020-11-15 18:44:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 1beb00e823d6e7cc6d7ffac66f3ef3e300f391e7 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 20 Nov 2020 21:03:37 +0100 Subject: [PATCH 165/188] Update issue templates --- .github/ISSUE_TEMPLATE/bug_report.md | 2 +- .github/ISSUE_TEMPLATE/feature_request.md | 2 +- .github/ISSUE_TEMPLATE/question.md | 10 ---------- 3 files changed, 2 insertions(+), 12 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/question.md diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 35847a4b..880cf271 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -2,7 +2,7 @@ name: Bug report about: Create a report to help us improve title: '' -labels: bug_report +labels: '' assignees: '' --- diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 83e55c31..90d6741a 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -2,7 +2,7 @@ name: Feature request about: Suggest an idea for this project title: '' -labels: feature_request +labels: '' assignees: '' --- diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md deleted file mode 100644 index 82d1e966..00000000 --- a/.github/ISSUE_TEMPLATE/question.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -name: Question -about: Ask a question about the project -title: '' -labels: question -assignees: '' - ---- - - From 431220e1c153bfad6c9d2b8665adc8d798114e15 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 21 Nov 2020 17:50:38 +0100 Subject: [PATCH 166/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 14 ++++++++++++-- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 22 ++++++++++++++++------ 5 files changed, 31 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 918b5099..6c687f82 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 18:44:03 //-- + --// Version: 2020-11-21 17:42:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index b434d9e7..301e7cd3 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -64,6 +64,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @Init nvarchar(max) = 'N', @Format nvarchar(max) = 'N', @ObjectLevelRecoveryMap nvarchar(max) = 'N', +@ExcludeLogShippedFromLogBackup nvarchar(max) = 'Y', @StringDelimiter nvarchar(max) = ',', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @@ -78,7 +79,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 18:44:03 //-- + --// Version: 2020-11-21 17:42:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -323,6 +324,7 @@ BEGIN SET @Parameters += ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') SET @Parameters += ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') SET @Parameters += ', @ObjectLevelRecoveryMap = ' + ISNULL('''' + REPLACE(@ObjectLevelRecoveryMap,'''','''''') + '''','NULL') + SET @Parameters += ', @ExcludeLogShippedFromLogBackup = ' + ISNULL('''' + REPLACE(@ExcludeLogShippedFromLogBackup,'''','''''') + '''','NULL') SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') @@ -2160,6 +2162,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @ExcludeLogShippedFromLogBackup NOT IN('Y','N') OR @ExcludeLogShippedFromLogBackup IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ExcludeLogShippedFromLogBackup is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -2795,7 +2805,7 @@ BEGIN AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupType = 'DIFF' AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupType = 'LOG' AND @CopyOnly = 'N' AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupType = 'LOG' AND @CopyOnly = 'Y' AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) - AND NOT ((@CurrentLogShippingRole = 'PRIMARY' AND @CurrentLogShippingRole IS NOT NULL) AND @CurrentBackupType = 'LOG') + AND NOT ((@CurrentLogShippingRole = 'PRIMARY' AND @CurrentLogShippingRole IS NOT NULL) AND @CurrentBackupType = 'LOG' AND @ExcludeLogShippedFromLogBackup = 'Y') AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') AND NOT (@CurrentBackupType = 'LOG' AND @LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NOT NULL AND NOT(@CurrentLogSizeSinceLastLogBackup >= @LogSizeSinceLastLogBackup OR @CurrentLogSizeSinceLastLogBackup IS NULL OR DATEDIFF(SECOND,@CurrentLastLogBackup,SYSDATETIME()) >= @TimeSinceLastLogBackup OR @CurrentLastLogBackup IS NULL)) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 00a6e3b8..a6caabd2 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 18:44:03 //-- + --// Version: 2020-11-21 17:42:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 7ddd6ef4..f3c57a1f 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 18:44:03 //-- + --// Version: 2020-11-21 17:42:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 71298e0e..594e8f83 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-11-15 18:44:03 +Version: 2020-11-21 17:42:54 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 18:44:03 //-- + --// Version: 2020-11-21 17:42:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -418,6 +418,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @Init nvarchar(max) = 'N', @Format nvarchar(max) = 'N', @ObjectLevelRecoveryMap nvarchar(max) = 'N', +@ExcludeLogShippedFromLogBackup nvarchar(max) = 'Y', @StringDelimiter nvarchar(max) = ',', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @@ -432,7 +433,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 18:44:03 //-- + --// Version: 2020-11-21 17:42:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -677,6 +678,7 @@ BEGIN SET @Parameters += ', @Init = ' + ISNULL('''' + REPLACE(@Init,'''','''''') + '''','NULL') SET @Parameters += ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') SET @Parameters += ', @ObjectLevelRecoveryMap = ' + ISNULL('''' + REPLACE(@ObjectLevelRecoveryMap,'''','''''') + '''','NULL') + SET @Parameters += ', @ExcludeLogShippedFromLogBackup = ' + ISNULL('''' + REPLACE(@ExcludeLogShippedFromLogBackup,'''','''''') + '''','NULL') SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') @@ -2514,6 +2516,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @ExcludeLogShippedFromLogBackup NOT IN('Y','N') OR @ExcludeLogShippedFromLogBackup IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ExcludeLogShippedFromLogBackup is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -3149,7 +3159,7 @@ BEGIN AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupType = 'DIFF' AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupType = 'LOG' AND @CopyOnly = 'N' AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupType = 'LOG' AND @CopyOnly = 'Y' AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) - AND NOT ((@CurrentLogShippingRole = 'PRIMARY' AND @CurrentLogShippingRole IS NOT NULL) AND @CurrentBackupType = 'LOG') + AND NOT ((@CurrentLogShippingRole = 'PRIMARY' AND @CurrentLogShippingRole IS NOT NULL) AND @CurrentBackupType = 'LOG' AND @ExcludeLogShippedFromLogBackup = 'Y') AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') AND NOT (@CurrentBackupType = 'LOG' AND @LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NOT NULL AND NOT(@CurrentLogSizeSinceLastLogBackup >= @LogSizeSinceLastLogBackup OR @CurrentLogSizeSinceLastLogBackup IS NULL OR DATEDIFF(SECOND,@CurrentLastLogBackup,SYSDATETIME()) >= @TimeSinceLastLogBackup OR @CurrentLastLogBackup IS NULL)) @@ -4445,7 +4455,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 18:44:03 //-- + --// Version: 2020-11-21 17:42:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6319,7 +6329,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-15 18:44:03 //-- + --// Version: 2020-11-21 17:42:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 3a70c13eac686ea6dcf3a005d8a87e4b2b5e9ee1 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 21 Nov 2020 18:01:57 +0100 Subject: [PATCH 167/188] Add files via upload From 6cafafff54cfaae413235f08246bd6ef3d8704cb Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 21 Nov 2020 23:14:20 +0100 Subject: [PATCH 168/188] Update README.md --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index a2627564..dc40e985 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,6 @@ [![issues badge]][issues] [![bug report badge]][bug report] [![feature request badge]][feature request] -[![question badge]][question] ## Getting Started @@ -38,7 +37,6 @@ Supported versions: SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Se [issues badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution.svg [bug report badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Bug%20Report.svg [feature request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Feature%20Request.svg -[question badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Question.svg [licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE [stars]:https://github.com/olahallengren/sql-server-maintenance-solution/stargazers @@ -46,4 +44,3 @@ Supported versions: SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Se [issues]:https://github.com/olahallengren/sql-server-maintenance-solution/issues [bug report]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3A%22Bug+Report%22 [feature request]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3A%22Feature+Request%22 -[question]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3AQuestion From a1964db255574b36b27cd319e9279d3332cc199a Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 22 Nov 2020 17:51:27 +0100 Subject: [PATCH 169/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 10 +++++++--- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 18 +++++++++++------- 5 files changed, 21 insertions(+), 13 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 6c687f82..fe93ad97 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-21 17:42:54 //-- + --// Version: 2020-11-22 17:45:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 301e7cd3..ff9319e2 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -79,7 +79,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-21 17:42:54 //-- + --// Version: 2020-11-22 17:45:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index a6caabd2..de852a43 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-21 17:42:54 //-- + --// Version: 2020-11-22 17:45:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1454,7 +1454,9 @@ BEGIN END -- Check filegroups - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' @@ -1615,7 +1617,9 @@ BEGIN END -- Check objects - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' diff --git a/IndexOptimize.sql b/IndexOptimize.sql index f3c57a1f..cde42e0c 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-21 17:42:54 //-- + --// Version: 2020-11-22 17:45:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 594e8f83..85bca954 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-11-21 17:42:54 +Version: 2020-11-22 17:45:07 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-21 17:42:54 //-- + --// Version: 2020-11-22 17:45:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -433,7 +433,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-21 17:42:54 //-- + --// Version: 2020-11-22 17:45:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4455,7 +4455,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-21 17:42:54 //-- + --// Version: 2020-11-22 17:45:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5870,7 +5870,9 @@ BEGIN END -- Check filegroups - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' @@ -6031,7 +6033,9 @@ BEGIN END -- Check objects - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' @@ -6329,7 +6333,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-21 17:42:54 //-- + --// Version: 2020-11-22 17:45:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 316c3bb8b2d0bcfa6338141f7f0e686944be0c19 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 26 Nov 2020 17:02:03 +0100 Subject: [PATCH 170/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 23 ++++++++---- DatabaseIntegrityCheck.sql | 22 ++++++++---- IndexOptimize.sql | 24 +++++++++---- MaintenanceSolution.sql | 73 +++++++++++++++++++++++++++----------- 5 files changed, 103 insertions(+), 41 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index fe93ad97..d01c7cea 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -35,7 +35,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-22 17:45:07 //-- + --// Version: 2020-11-26 16:54:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index ff9319e2..68a082f6 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -79,7 +79,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-22 17:45:07 //-- + --// Version: 2020-11-26 16:54:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -144,6 +144,8 @@ BEGIN DECLARE @CurrentDate datetime2 DECLARE @CurrentCleanupDate datetime2 DECLARE @CurrentIsDatabaseAccessible bit + DECLARE @CurrentReplicaID uniqueidentifier + DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) @@ -2617,13 +2619,19 @@ BEGIN IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN + SELECT @CurrentReplicaID = replica_id + FROM sys.databases + WHERE [name] = @CurrentDatabaseName + + SELECT @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + @CurrentAvailabilityGroupID = group_id + FROM sys.dm_hadr_availability_replica_states + WHERE replica_id = @CurrentReplicaID + SELECT @CurrentAvailabilityGroup = availability_groups.name, - @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) - FROM sys.databases databases - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id - INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id - WHERE databases.name = @CurrentDatabaseName + FROM sys.availability_groups + WHERE group_id = @CurrentAvailabilityGroupID END IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL @@ -2809,6 +2817,7 @@ BEGIN AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') AND NOT (@CurrentBackupType = 'LOG' AND @LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NOT NULL AND NOT(@CurrentLogSizeSinceLastLogBackup >= @LogSizeSinceLastLogBackup OR @CurrentLogSizeSinceLastLogBackup IS NULL OR DATEDIFF(SECOND,@CurrentLastLogBackup,SYSDATETIME()) >= @TimeSinceLastLogBackup OR @CurrentLastLogBackup IS NULL)) + AND NOT (@CurrentBackupType = 'LOG' AND @Updateability = 'READ_ONLY' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN IF @CurrentBackupType = 'LOG' AND (@CleanupTime IS NOT NULL OR @MirrorCleanupTime IS NOT NULL) @@ -4015,6 +4024,8 @@ BEGIN SET @CurrentDate = NULL SET @CurrentCleanupDate = NULL SET @CurrentIsDatabaseAccessible = NULL + SET @CurrentReplicaID = NULL + SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index de852a43..9f690c7d 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-22 17:45:07 //-- + --// Version: 2020-11-26 16:54:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -73,6 +73,8 @@ BEGIN DECLARE @CurrentRecoveryModel nvarchar(max) DECLARE @CurrentIsDatabaseAccessible bit + DECLARE @CurrentReplicaID uniqueidentifier + DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) @@ -1368,13 +1370,19 @@ BEGIN IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN + SELECT @CurrentReplicaID = replica_id + FROM sys.databases + WHERE [name] = @CurrentDatabaseName + + SELECT @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + @CurrentAvailabilityGroupID = group_id + FROM sys.dm_hadr_availability_replica_states + WHERE replica_id = @CurrentReplicaID + SELECT @CurrentAvailabilityGroup = availability_groups.name, - @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) - FROM sys.databases databases - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id - INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id - WHERE databases.name = @CurrentDatabaseName + FROM sys.availability_groups + WHERE group_id = @CurrentAvailabilityGroupID END IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL AND @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' @@ -1827,6 +1835,8 @@ BEGIN SET @CurrentRecoveryModel = NULL SET @CurrentIsDatabaseAccessible = NULL + SET @CurrentReplicaID = NULL + SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL diff --git a/IndexOptimize.sql b/IndexOptimize.sql index cde42e0c..3d95ff35 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -52,7 +52,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-22 17:45:07 //-- + --// Version: 2020-11-26 16:54:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -92,6 +92,8 @@ BEGIN DECLARE @CurrentRecoveryModel nvarchar(max) DECLARE @CurrentIsDatabaseAccessible bit + DECLARE @CurrentReplicaID uniqueidentifier + DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentDatabaseMirroringRole nvarchar(max) @@ -1464,12 +1466,18 @@ BEGIN IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @CurrentAvailabilityGroup = availability_groups.name, - @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc - FROM sys.databases databases - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id - INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id - WHERE databases.name = @CurrentDatabaseName + SELECT @CurrentReplicaID = replica_id + FROM sys.databases + WHERE [name] = @CurrentDatabaseName + + SELECT @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + @CurrentAvailabilityGroupID = group_id + FROM sys.dm_hadr_availability_replica_states + WHERE replica_id = @CurrentReplicaID + + SELECT @CurrentAvailabilityGroup = availability_groups.name + FROM sys.availability_groups + WHERE group_id = @CurrentAvailabilityGroupID END IF SERVERPROPERTY('EngineEdition') <> 5 @@ -2361,6 +2369,8 @@ BEGIN SET @CurrentRecoveryModel = NULL SET @CurrentIsDatabaseAccessible = NULL + SET @CurrentReplicaID = NULL + SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL SET @CurrentDatabaseMirroringRole = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 85bca954..ec96311c 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-11-22 17:45:07 +Version: 2020-11-26 16:54:49 You can contact me by e-mail at ola@hallengren.com. @@ -122,7 +122,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-22 17:45:07 //-- + --// Version: 2020-11-26 16:54:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -433,7 +433,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-22 17:45:07 //-- + --// Version: 2020-11-26 16:54:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,6 +498,8 @@ BEGIN DECLARE @CurrentDate datetime2 DECLARE @CurrentCleanupDate datetime2 DECLARE @CurrentIsDatabaseAccessible bit + DECLARE @CurrentReplicaID uniqueidentifier + DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) @@ -2971,13 +2973,19 @@ BEGIN IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN + SELECT @CurrentReplicaID = replica_id + FROM sys.databases + WHERE [name] = @CurrentDatabaseName + + SELECT @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + @CurrentAvailabilityGroupID = group_id + FROM sys.dm_hadr_availability_replica_states + WHERE replica_id = @CurrentReplicaID + SELECT @CurrentAvailabilityGroup = availability_groups.name, - @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) - FROM sys.databases databases - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id - INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id - WHERE databases.name = @CurrentDatabaseName + FROM sys.availability_groups + WHERE group_id = @CurrentAvailabilityGroupID END IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL @@ -3163,6 +3171,7 @@ BEGIN AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') AND NOT (@CurrentBackupType = 'LOG' AND @LogSizeSinceLastLogBackup IS NOT NULL AND @TimeSinceLastLogBackup IS NOT NULL AND NOT(@CurrentLogSizeSinceLastLogBackup >= @LogSizeSinceLastLogBackup OR @CurrentLogSizeSinceLastLogBackup IS NULL OR DATEDIFF(SECOND,@CurrentLastLogBackup,SYSDATETIME()) >= @TimeSinceLastLogBackup OR @CurrentLastLogBackup IS NULL)) + AND NOT (@CurrentBackupType = 'LOG' AND @Updateability = 'READ_ONLY' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') BEGIN IF @CurrentBackupType = 'LOG' AND (@CleanupTime IS NOT NULL OR @MirrorCleanupTime IS NOT NULL) @@ -4369,6 +4378,8 @@ BEGIN SET @CurrentDate = NULL SET @CurrentCleanupDate = NULL SET @CurrentIsDatabaseAccessible = NULL + SET @CurrentReplicaID = NULL + SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL @@ -4455,7 +4466,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-22 17:45:07 //-- + --// Version: 2020-11-26 16:54:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4489,6 +4500,8 @@ BEGIN DECLARE @CurrentRecoveryModel nvarchar(max) DECLARE @CurrentIsDatabaseAccessible bit + DECLARE @CurrentReplicaID uniqueidentifier + DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) @@ -5784,13 +5797,19 @@ BEGIN IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN + SELECT @CurrentReplicaID = replica_id + FROM sys.databases + WHERE [name] = @CurrentDatabaseName + + SELECT @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + @CurrentAvailabilityGroupID = group_id + FROM sys.dm_hadr_availability_replica_states + WHERE replica_id = @CurrentReplicaID + SELECT @CurrentAvailabilityGroup = availability_groups.name, - @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) - FROM sys.databases databases - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id - INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id - WHERE databases.name = @CurrentDatabaseName + FROM sys.availability_groups + WHERE group_id = @CurrentAvailabilityGroupID END IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL AND @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' @@ -6243,6 +6262,8 @@ BEGIN SET @CurrentRecoveryModel = NULL SET @CurrentIsDatabaseAccessible = NULL + SET @CurrentReplicaID = NULL + SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL @@ -6333,7 +6354,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-22 17:45:07 //-- + --// Version: 2020-11-26 16:54:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6373,6 +6394,8 @@ BEGIN DECLARE @CurrentRecoveryModel nvarchar(max) DECLARE @CurrentIsDatabaseAccessible bit + DECLARE @CurrentReplicaID uniqueidentifier + DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentDatabaseMirroringRole nvarchar(max) @@ -7745,12 +7768,18 @@ BEGIN IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @CurrentAvailabilityGroup = availability_groups.name, - @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc - FROM sys.databases databases - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id - INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id - WHERE databases.name = @CurrentDatabaseName + SELECT @CurrentReplicaID = replica_id + FROM sys.databases + WHERE [name] = @CurrentDatabaseName + + SELECT @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + @CurrentAvailabilityGroupID = group_id + FROM sys.dm_hadr_availability_replica_states + WHERE replica_id = @CurrentReplicaID + + SELECT @CurrentAvailabilityGroup = availability_groups.name + FROM sys.availability_groups + WHERE group_id = @CurrentAvailabilityGroupID END IF SERVERPROPERTY('EngineEdition') <> 5 @@ -8642,6 +8671,8 @@ BEGIN SET @CurrentRecoveryModel = NULL SET @CurrentIsDatabaseAccessible = NULL + SET @CurrentReplicaID = NULL + SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL SET @CurrentDatabaseMirroringRole = NULL From c3705fbaa0e8f4d099def874afeebaf2bba471f3 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 26 Nov 2020 17:03:15 +0100 Subject: [PATCH 171/188] Add files via upload From 75aee8de028904b29392605c7e6b69372015097e Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 28 Nov 2020 11:48:29 +0100 Subject: [PATCH 172/188] Add files via upload --- CommandExecute.sql | 27 ++++++++++++++++- DatabaseBackup.sql | 12 ++++---- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 16 +++++++++-- MaintenanceSolution.sql | 59 +++++++++++++++++++++++++++++++------- 5 files changed, 95 insertions(+), 21 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index d01c7cea..6469b245 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -24,6 +24,7 @@ ALTER PROCEDURE [dbo].[CommandExecute] @PartitionNumber int = NULL, @ExtendedInfo xml = NULL, @LockMessageSeverity int = 16, +@ExecuteAsUser nvarchar(max) = NULL, @LogToTable nvarchar(max), @Execute nvarchar(max) @@ -35,7 +36,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-26 16:54:49 //-- + --// Version: 2020-11-28 11:43:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -67,6 +68,8 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) + DECLARE @RevertCommand nvarchar(max) + ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- @@ -129,6 +132,12 @@ BEGIN SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 END + IF @ExecuteAsUser <> 'dbo' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ExecuteAsUser is not supported.', 16, 1 + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -169,6 +178,17 @@ BEGIN GOTO ReturnCode END + ---------------------------------------------------------------------------------------------------- + --// Execute as user //-- + ---------------------------------------------------------------------------------------------------- + + IF @ExecuteAsUser = 'dbo' + BEGIN + SET @Command = 'EXECUTE AS USER = ''dbo''; ' + @Command + '; REVERT;' + + SET @RevertCommand = 'REVERT' + END + ---------------------------------------------------------------------------------------------------- --// Log initial information //-- ---------------------------------------------------------------------------------------------------- @@ -226,6 +246,11 @@ BEGIN BEGIN SET @ReturnCode = ERROR_NUMBER() END + + IF @ExecuteAsUser IS NOT NULL + BEGIN + EXECUTE @sp_executesql @RevertCommand + END END CATCH END diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 68a082f6..4e4b048a 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -79,7 +79,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-26 16:54:49 //-- + --// Version: 2020-11-28 11:43:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2042,7 +2042,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The parameter @DirectoryStructure contains one or more tokens that are not supported.', 16, 1 @@ -2050,7 +2050,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS AvailabilityGroupDirectoryStructure) Temp WHERE AvailabilityGroupDirectoryStructure LIKE '%{%' OR AvailabilityGroupDirectoryStructure LIKE '%}%') + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS AvailabilityGroupDirectoryStructure) Temp WHERE AvailabilityGroupDirectoryStructure LIKE '%{%' OR AvailabilityGroupDirectoryStructure LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.', 16, 1 @@ -2058,7 +2058,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') AS [FileName]) Temp WHERE [FileName] LIKE '%{%' OR [FileName] LIKE '%}%') + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') AS [FileName]) Temp WHERE [FileName] LIKE '%{%' OR [FileName] LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The parameter @FileName contains one or more tokens that are not supported.', 16, 1 @@ -2066,7 +2066,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') AS AvailabilityGroupFileName) Temp WHERE AvailabilityGroupFileName LIKE '%{%' OR AvailabilityGroupFileName LIKE '%}%') + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') AS AvailabilityGroupFileName) Temp WHERE AvailabilityGroupFileName LIKE '%{%' OR AvailabilityGroupFileName LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.', 16, 1 @@ -3016,6 +3016,7 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) @@ -3170,6 +3171,7 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 9f690c7d..24be8eb0 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-26 16:54:49 //-- + --// Version: 2020-11-28 11:43:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 3d95ff35..b693e79b 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -41,6 +41,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @StringDelimiter nvarchar(max) = ',', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', +@ExecuteAsUser nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -52,7 +53,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-26 16:54:49 //-- + --// Version: 2020-11-28 11:43:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -307,6 +308,7 @@ BEGIN SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') + SET @Parameters += ', @ExecuteAsUser = ' + ISNULL('''' + REPLACE(@ExecuteAsUser,'''','''''') + '''','NULL') SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -1093,6 +1095,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @ExecuteAsUser <> 'dbo' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ExecuteAsUser is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -2147,7 +2157,7 @@ BEGIN IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand += @CurrentAlterIndexWithClause - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo, @LockMessageSeverity = @LockMessageSeverity, @ExecuteAsUser = @ExecuteAsUser, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput = @Error IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput @@ -2251,7 +2261,7 @@ BEGIN IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo, @LockMessageSeverity = @LockMessageSeverity, @ExecuteAsUser = @ExecuteAsUser, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput = @Error IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index ec96311c..1d9fbdce 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-11-26 16:54:49 +Version: 2020-11-28 11:43:26 You can contact me by e-mail at ola@hallengren.com. @@ -111,6 +111,7 @@ ALTER PROCEDURE [dbo].[CommandExecute] @PartitionNumber int = NULL, @ExtendedInfo xml = NULL, @LockMessageSeverity int = 16, +@ExecuteAsUser nvarchar(max) = NULL, @LogToTable nvarchar(max), @Execute nvarchar(max) @@ -122,7 +123,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-26 16:54:49 //-- + --// Version: 2020-11-28 11:43:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -154,6 +155,8 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) + DECLARE @RevertCommand nvarchar(max) + ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- @@ -216,6 +219,12 @@ BEGIN SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 END + IF @ExecuteAsUser <> 'dbo' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ExecuteAsUser is not supported.', 16, 1 + END + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -256,6 +265,17 @@ BEGIN GOTO ReturnCode END + ---------------------------------------------------------------------------------------------------- + --// Execute as user //-- + ---------------------------------------------------------------------------------------------------- + + IF @ExecuteAsUser = 'dbo' + BEGIN + SET @Command = 'EXECUTE AS USER = ''dbo''; ' + @Command + '; REVERT;' + + SET @RevertCommand = 'REVERT' + END + ---------------------------------------------------------------------------------------------------- --// Log initial information //-- ---------------------------------------------------------------------------------------------------- @@ -313,6 +333,11 @@ BEGIN BEGIN SET @ReturnCode = ERROR_NUMBER() END + + IF @ExecuteAsUser IS NOT NULL + BEGIN + EXECUTE @sp_executesql @RevertCommand + END END CATCH END @@ -433,7 +458,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-26 16:54:49 //-- + --// Version: 2020-11-28 11:43:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2396,7 +2421,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The parameter @DirectoryStructure contains one or more tokens that are not supported.', 16, 1 @@ -2404,7 +2429,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS AvailabilityGroupDirectoryStructure) Temp WHERE AvailabilityGroupDirectoryStructure LIKE '%{%' OR AvailabilityGroupDirectoryStructure LIKE '%}%') + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS AvailabilityGroupDirectoryStructure) Temp WHERE AvailabilityGroupDirectoryStructure LIKE '%{%' OR AvailabilityGroupDirectoryStructure LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.', 16, 1 @@ -2412,7 +2437,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') AS [FileName]) Temp WHERE [FileName] LIKE '%{%' OR [FileName] LIKE '%}%') + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') AS [FileName]) Temp WHERE [FileName] LIKE '%{%' OR [FileName] LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The parameter @FileName contains one or more tokens that are not supported.', 16, 1 @@ -2420,7 +2445,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') AS AvailabilityGroupFileName) Temp WHERE AvailabilityGroupFileName LIKE '%{%' OR AvailabilityGroupFileName LIKE '%}%') + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{FileNumber}',''),'{NumberOfFiles}',''),'{FileExtension}',''),'{MajorVersion}',''),'{MinorVersion}','') AS AvailabilityGroupFileName) Temp WHERE AvailabilityGroupFileName LIKE '%{%' OR AvailabilityGroupFileName LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.', 16, 1 @@ -3370,6 +3395,7 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) @@ -3524,6 +3550,7 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Year}',CAST(DATEPART(YEAR,@CurrentDate) AS nvarchar)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,@CurrentDate) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,@CurrentDate) AS nvarchar),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,@CurrentDate) AS nvarchar),2)) @@ -4466,7 +4493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-26 16:54:49 //-- + --// Version: 2020-11-28 11:43:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6343,6 +6370,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @StringDelimiter nvarchar(max) = ',', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', +@ExecuteAsUser nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', @Execute nvarchar(max) = 'Y' @@ -6354,7 +6382,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-26 16:54:49 //-- + --// Version: 2020-11-28 11:43:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6609,6 +6637,7 @@ BEGIN SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') + SET @Parameters += ', @ExecuteAsUser = ' + ISNULL('''' + REPLACE(@ExecuteAsUser,'''','''''') + '''','NULL') SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') @@ -7395,6 +7424,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @ExecuteAsUser <> 'dbo' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ExecuteAsUser is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -8449,7 +8486,7 @@ BEGIN IF @CurrentAlterIndexWithClause IS NOT NULL SET @CurrentCommand += @CurrentAlterIndexWithClause - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @PartitionNumber = @CurrentPartitionNumber, @ExtendedInfo = @CurrentExtendedInfo, @LockMessageSeverity = @LockMessageSeverity, @ExecuteAsUser = @ExecuteAsUser, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput = @Error IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput @@ -8553,7 +8590,7 @@ BEGIN IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo, @LockMessageSeverity = @LockMessageSeverity, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseName, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @ExtendedInfo = @CurrentExtendedInfo, @LockMessageSeverity = @LockMessageSeverity, @ExecuteAsUser = @ExecuteAsUser, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput = @Error IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput From 1af0651a0d59ba98b60bac6a1f357036d97fedb3 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 29 Nov 2020 18:26:53 +0100 Subject: [PATCH 173/188] Add files via upload --- CommandExecute.sql | 8 ++++---- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 22 ++++++++++++++++++++-- MaintenanceSolution.sql | 36 +++++++++++++++++++++++++++--------- 5 files changed, 53 insertions(+), 17 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 6469b245..21e51d9c 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -36,7 +36,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-28 11:43:26 //-- + --// Version: 2020-11-29 18:17:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -132,7 +132,7 @@ BEGIN SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 END - IF @ExecuteAsUser <> 'dbo' + IF LEN(@ExecuteAsUser) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @ExecuteAsUser is not supported.', 16, 1 @@ -182,9 +182,9 @@ BEGIN --// Execute as user //-- ---------------------------------------------------------------------------------------------------- - IF @ExecuteAsUser = 'dbo' + IF @ExecuteAsUser IS NOT NULL BEGIN - SET @Command = 'EXECUTE AS USER = ''dbo''; ' + @Command + '; REVERT;' + SET @Command = 'EXECUTE AS USER = ''' + REPLACE(@ExecuteAsUser,'''','''''') + '''; ' + @Command + '; REVERT;' SET @RevertCommand = 'REVERT' END diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 4e4b048a..5f8caa72 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -79,7 +79,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-28 11:43:26 //-- + --// Version: 2020-11-29 18:17:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 24be8eb0..a407f75a 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-28 11:43:26 //-- + --// Version: 2020-11-29 18:17:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index b693e79b..e90fcbc2 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -53,7 +53,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-28 11:43:26 //-- + --// Version: 2020-11-29 18:17:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -86,6 +86,7 @@ BEGIN DECLARE @CurrentDatabase_sp_executesql nvarchar(max) + DECLARE @CurrentExecuteAsUserExists bit DECLARE @CurrentUserAccess nvarchar(max) DECLARE @CurrentIsReadOnly bit DECLARE @CurrentDatabaseState nvarchar(max) @@ -1095,7 +1096,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @ExecuteAsUser <> 'dbo' + IF LEN(@ExecuteAsUser) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @ExecuteAsUser is not supported.', 16, 1 @@ -1429,6 +1430,14 @@ BEGIN SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + IF @ExecuteAsUser IS NOT NULL + BEGIN + SET @CurrentCommand = '' + SET @CurrentCommand += 'IF EXISTS(SELECT * FROM sys.database_principals database_principals WHERE database_principals.[name] = @ParamExecuteAsUser) BEGIN SET @ParamExecuteAsUserExists = 1 END ELSE BEGIN SET @ParamExecuteAsUserExists = 0 END' + + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamExecuteAsUser sysname, @ParamExecuteAsUserExists bit OUTPUT', @ParamExecuteAsUser = @ExecuteAsUser, @ParamExecuteAsUserExists = @CurrentExecuteAsUserExists OUTPUT + END + BEGIN SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -1520,9 +1529,17 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT + IF @CurrentExecuteAsUserExists = 0 + BEGIN + SET @DatabaseMessage = 'The user ' + QUOTENAME(@ExecuteAsUser) + ' does not exist in the database ' + QUOTENAME(@CurrentDatabaseName) + '.' + RAISERROR('%s',16,1,@DatabaseMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentUserAccess = 'SINGLE_USER' AND @CurrentIsDatabaseAccessible = 0) AND DATABASEPROPERTYEX(@CurrentDatabaseName,'Updateability') = 'READ_WRITE' + AND (@CurrentExecuteAsUserExists = 1 OR @CurrentExecuteAsUserExists IS NULL) BEGIN -- Select indexes in the current database @@ -2372,6 +2389,7 @@ BEGIN SET @CurrentDatabase_sp_executesql = NULL + SET @CurrentExecuteAsUserExists = NULL SET @CurrentUserAccess = NULL SET @CurrentIsReadOnly = NULL SET @CurrentDatabaseState = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 1d9fbdce..3b129f87 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-11-28 11:43:26 +Version: 2020-11-29 18:17:18 You can contact me by e-mail at ola@hallengren.com. @@ -123,7 +123,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-28 11:43:26 //-- + --// Version: 2020-11-29 18:17:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -219,7 +219,7 @@ BEGIN SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 END - IF @ExecuteAsUser <> 'dbo' + IF LEN(@ExecuteAsUser) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @ExecuteAsUser is not supported.', 16, 1 @@ -269,9 +269,9 @@ BEGIN --// Execute as user //-- ---------------------------------------------------------------------------------------------------- - IF @ExecuteAsUser = 'dbo' + IF @ExecuteAsUser IS NOT NULL BEGIN - SET @Command = 'EXECUTE AS USER = ''dbo''; ' + @Command + '; REVERT;' + SET @Command = 'EXECUTE AS USER = ''' + REPLACE(@ExecuteAsUser,'''','''''') + '''; ' + @Command + '; REVERT;' SET @RevertCommand = 'REVERT' END @@ -458,7 +458,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-28 11:43:26 //-- + --// Version: 2020-11-29 18:17:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4493,7 +4493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-28 11:43:26 //-- + --// Version: 2020-11-29 18:17:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6382,7 +6382,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-28 11:43:26 //-- + --// Version: 2020-11-29 18:17:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6415,6 +6415,7 @@ BEGIN DECLARE @CurrentDatabase_sp_executesql nvarchar(max) + DECLARE @CurrentExecuteAsUserExists bit DECLARE @CurrentUserAccess nvarchar(max) DECLARE @CurrentIsReadOnly bit DECLARE @CurrentDatabaseState nvarchar(max) @@ -7424,7 +7425,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @ExecuteAsUser <> 'dbo' + IF LEN(@ExecuteAsUser) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @ExecuteAsUser is not supported.', 16, 1 @@ -7758,6 +7759,14 @@ BEGIN SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + IF @ExecuteAsUser IS NOT NULL + BEGIN + SET @CurrentCommand = '' + SET @CurrentCommand += 'IF EXISTS(SELECT * FROM sys.database_principals database_principals WHERE database_principals.[name] = @ParamExecuteAsUser) BEGIN SET @ParamExecuteAsUserExists = 1 END ELSE BEGIN SET @ParamExecuteAsUserExists = 0 END' + + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamExecuteAsUser sysname, @ParamExecuteAsUserExists bit OUTPUT', @ParamExecuteAsUser = @ExecuteAsUser, @ParamExecuteAsUserExists = @CurrentExecuteAsUserExists OUTPUT + END + BEGIN SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -7849,9 +7858,17 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT + IF @CurrentExecuteAsUserExists = 0 + BEGIN + SET @DatabaseMessage = 'The user ' + QUOTENAME(@ExecuteAsUser) + ' does not exist in the database ' + QUOTENAME(@CurrentDatabaseName) + '.' + RAISERROR('%s',16,1,@DatabaseMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentUserAccess = 'SINGLE_USER' AND @CurrentIsDatabaseAccessible = 0) AND DATABASEPROPERTYEX(@CurrentDatabaseName,'Updateability') = 'READ_WRITE' + AND (@CurrentExecuteAsUserExists = 1 OR @CurrentExecuteAsUserExists IS NULL) BEGIN -- Select indexes in the current database @@ -8701,6 +8718,7 @@ BEGIN SET @CurrentDatabase_sp_executesql = NULL + SET @CurrentExecuteAsUserExists = NULL SET @CurrentUserAccess = NULL SET @CurrentIsReadOnly = NULL SET @CurrentDatabaseState = NULL From b4e7cf1c146f2c7c5923b1ed860689441c3fc433 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 29 Nov 2020 20:11:28 +0100 Subject: [PATCH 174/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 19 ++++++------ DatabaseIntegrityCheck.sql | 19 ++++++------ IndexOptimize.sql | 17 +++++------ MaintenanceSolution.sql | 59 ++++++++++++++++++++------------------ 5 files changed, 61 insertions(+), 55 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 21e51d9c..08bb78e0 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -36,7 +36,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 18:17:18 //-- + --// Version: 2020-11-29 19:56:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 5f8caa72..acc3687f 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -79,7 +79,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 18:17:18 //-- + --// Version: 2020-11-29 19:56:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -496,8 +496,8 @@ BEGIN SELECT databases.name, availability_groups.name FROM sys.databases databases - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id - INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id + INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id + INNER JOIN sys.availability_groups availability_groups ON availability_replicas.group_id = availability_groups.group_id END INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) @@ -2619,17 +2619,18 @@ BEGIN IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @CurrentReplicaID = replica_id - FROM sys.databases - WHERE [name] = @CurrentDatabaseName + SELECT @CurrentReplicaID = databases.replica_id + FROM sys.databases databases + INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id + WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + SELECT @CurrentAvailabilityGroupRole = role_desc, @CurrentAvailabilityGroupID = group_id FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentReplicaID - SELECT @CurrentAvailabilityGroup = availability_groups.name, - @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) + SELECT @CurrentAvailabilityGroup = [name], + @CurrentAvailabilityGroupBackupPreference = UPPER(automated_backup_preference_desc) FROM sys.availability_groups WHERE group_id = @CurrentAvailabilityGroupID END diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index a407f75a..f8076202 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 18:17:18 //-- + --// Version: 2020-11-29 19:56:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -376,8 +376,8 @@ BEGIN SELECT databases.name, availability_groups.name FROM sys.databases databases - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id - INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id + INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id + INNER JOIN sys.availability_groups availability_groups ON availability_replicas.group_id = availability_groups.group_id END INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], [Order], Selected, Completed) @@ -1370,17 +1370,18 @@ BEGIN IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @CurrentReplicaID = replica_id - FROM sys.databases - WHERE [name] = @CurrentDatabaseName + SELECT @CurrentReplicaID = databases.replica_id + FROM sys.databases databases + INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id + WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + SELECT @CurrentAvailabilityGroupRole = role_desc, @CurrentAvailabilityGroupID = group_id FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentReplicaID - SELECT @CurrentAvailabilityGroup = availability_groups.name, - @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) + SELECT @CurrentAvailabilityGroup = [name], + @CurrentAvailabilityGroupBackupPreference = UPPER(automated_backup_preference_desc) FROM sys.availability_groups WHERE group_id = @CurrentAvailabilityGroupID END diff --git a/IndexOptimize.sql b/IndexOptimize.sql index e90fcbc2..1cf2cf54 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -53,7 +53,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 18:17:18 //-- + --// Version: 2020-11-29 19:56:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -470,8 +470,8 @@ BEGIN SELECT databases.name, availability_groups.name FROM sys.databases databases - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id - INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id + INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id + INNER JOIN sys.availability_groups availability_groups ON availability_replicas.group_id = availability_groups.group_id END INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) @@ -1485,16 +1485,17 @@ BEGIN IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @CurrentReplicaID = replica_id - FROM sys.databases - WHERE [name] = @CurrentDatabaseName + SELECT @CurrentReplicaID = databases.replica_id + FROM sys.databases databases + INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id + WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + SELECT @CurrentAvailabilityGroupRole = role_desc, @CurrentAvailabilityGroupID = group_id FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentReplicaID - SELECT @CurrentAvailabilityGroup = availability_groups.name + SELECT @CurrentAvailabilityGroup = [name] FROM sys.availability_groups WHERE group_id = @CurrentAvailabilityGroupID END diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 3b129f87..dbfdaa80 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-11-29 18:17:18 +Version: 2020-11-29 19:56:45 You can contact me by e-mail at ola@hallengren.com. @@ -123,7 +123,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 18:17:18 //-- + --// Version: 2020-11-29 19:56:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -458,7 +458,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 18:17:18 //-- + --// Version: 2020-11-29 19:56:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -875,8 +875,8 @@ BEGIN SELECT databases.name, availability_groups.name FROM sys.databases databases - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id - INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id + INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id + INNER JOIN sys.availability_groups availability_groups ON availability_replicas.group_id = availability_groups.group_id END INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) @@ -2998,17 +2998,18 @@ BEGIN IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @CurrentReplicaID = replica_id - FROM sys.databases - WHERE [name] = @CurrentDatabaseName + SELECT @CurrentReplicaID = databases.replica_id + FROM sys.databases databases + INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id + WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + SELECT @CurrentAvailabilityGroupRole = role_desc, @CurrentAvailabilityGroupID = group_id FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentReplicaID - SELECT @CurrentAvailabilityGroup = availability_groups.name, - @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) + SELECT @CurrentAvailabilityGroup = [name], + @CurrentAvailabilityGroupBackupPreference = UPPER(automated_backup_preference_desc) FROM sys.availability_groups WHERE group_id = @CurrentAvailabilityGroupID END @@ -4493,7 +4494,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 18:17:18 //-- + --// Version: 2020-11-29 19:56:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4830,8 +4831,8 @@ BEGIN SELECT databases.name, availability_groups.name FROM sys.databases databases - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id - INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id + INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id + INNER JOIN sys.availability_groups availability_groups ON availability_replicas.group_id = availability_groups.group_id END INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot], [Order], Selected, Completed) @@ -5824,17 +5825,18 @@ BEGIN IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @CurrentReplicaID = replica_id - FROM sys.databases - WHERE [name] = @CurrentDatabaseName + SELECT @CurrentReplicaID = databases.replica_id + FROM sys.databases databases + INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id + WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + SELECT @CurrentAvailabilityGroupRole = role_desc, @CurrentAvailabilityGroupID = group_id FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentReplicaID - SELECT @CurrentAvailabilityGroup = availability_groups.name, - @CurrentAvailabilityGroupBackupPreference = UPPER(availability_groups.automated_backup_preference_desc) + SELECT @CurrentAvailabilityGroup = [name], + @CurrentAvailabilityGroupBackupPreference = UPPER(automated_backup_preference_desc) FROM sys.availability_groups WHERE group_id = @CurrentAvailabilityGroupID END @@ -6382,7 +6384,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 18:17:18 //-- + --// Version: 2020-11-29 19:56:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6799,8 +6801,8 @@ BEGIN SELECT databases.name, availability_groups.name FROM sys.databases databases - INNER JOIN sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states ON databases.replica_id = dm_hadr_availability_replica_states.replica_id - INNER JOIN sys.availability_groups availability_groups ON dm_hadr_availability_replica_states.group_id = availability_groups.group_id + INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id + INNER JOIN sys.availability_groups availability_groups ON availability_replicas.group_id = availability_groups.group_id END INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Order], Selected, Completed) @@ -7814,16 +7816,17 @@ BEGIN IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @CurrentReplicaID = replica_id - FROM sys.databases - WHERE [name] = @CurrentDatabaseName + SELECT @CurrentReplicaID = databases.replica_id + FROM sys.databases databases + INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id + WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc, + SELECT @CurrentAvailabilityGroupRole = role_desc, @CurrentAvailabilityGroupID = group_id FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentReplicaID - SELECT @CurrentAvailabilityGroup = availability_groups.name + SELECT @CurrentAvailabilityGroup = [name] FROM sys.availability_groups WHERE group_id = @CurrentAvailabilityGroupID END From 64c7201c0f5e0ab072f5ccd53070ac2b846bec68 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 29 Nov 2020 22:38:57 +0100 Subject: [PATCH 175/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 4 ++-- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 ++++++------ 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 08bb78e0..22e962fb 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -36,7 +36,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 19:56:45 //-- + --// Version: 2020-11-29 22:30:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index acc3687f..0107fd15 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -79,7 +79,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 19:56:45 //-- + --// Version: 2020-11-29 22:30:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2042,7 +2042,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The parameter @DirectoryStructure contains one or more tokens that are not supported.', 16, 1 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index f8076202..b66626e8 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 19:56:45 //-- + --// Version: 2020-11-29 22:30:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 1cf2cf54..562e2bb4 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -53,7 +53,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 19:56:45 //-- + --// Version: 2020-11-29 22:30:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index dbfdaa80..92c7c49a 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-11-29 19:56:45 +Version: 2020-11-29 22:30:00 You can contact me by e-mail at ola@hallengren.com. @@ -123,7 +123,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 19:56:45 //-- + --// Version: 2020-11-29 22:30:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -458,7 +458,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 19:56:45 //-- + --// Version: 2020-11-29 22:30:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2421,7 +2421,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Day}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') + IF EXISTS (SELECT * FROM (SELECT REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The parameter @DirectoryStructure contains one or more tokens that are not supported.', 16, 1 @@ -4494,7 +4494,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 19:56:45 //-- + --// Version: 2020-11-29 22:30:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6384,7 +6384,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 19:56:45 //-- + --// Version: 2020-11-29 22:30:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 47af302ab7c14a6dbf01558a5cc32f888f4fb243 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 5 Dec 2020 18:35:38 +0100 Subject: [PATCH 176/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 3 ++- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 11 ++++++----- 5 files changed, 11 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 22e962fb..83022ff2 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -36,7 +36,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 22:30:00 //-- + --// Version: 2020-12-05 18:28:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 0107fd15..fa7ca1a9 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -79,7 +79,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 22:30:00 //-- + --// Version: 2020-12-05 18:28:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3729,6 +3729,7 @@ BEGIN IF @DataDomainBoostDevicePath IS NOT NULL SET @CurrentCommand += ' -a "NSR_DFA_SI_DEVICE_PATH=' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '"' IF @DataDomainBoostLockboxPath IS NOT NULL SET @CurrentCommand += ' -a "NSR_DFA_SI_DD_LOCKBOX_PATH=' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '"' SET @CurrentCommand += ' -a "NSR_SKIP_NON_BACKUPABLE_STATE_DB=TRUE"' + SET @CurrentCommand += ' -a "BACKUP_PROMOTION=NONE"' IF @CopyOnly = 'Y' SET @CurrentCommand += ' -a "NSR_COPY_ONLY=TRUE"' IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand += ' "MSSQL' + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index b66626e8..b7e188ae 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 22:30:00 //-- + --// Version: 2020-12-05 18:28:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 562e2bb4..2e6bb6b6 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -53,7 +53,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 22:30:00 //-- + --// Version: 2020-12-05 18:28:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 92c7c49a..f0c5c5d0 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-11-29 22:30:00 +Version: 2020-12-05 18:28:36 You can contact me by e-mail at ola@hallengren.com. @@ -123,7 +123,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 22:30:00 //-- + --// Version: 2020-12-05 18:28:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -458,7 +458,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 22:30:00 //-- + --// Version: 2020-12-05 18:28:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4108,6 +4108,7 @@ BEGIN IF @DataDomainBoostDevicePath IS NOT NULL SET @CurrentCommand += ' -a "NSR_DFA_SI_DEVICE_PATH=' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '"' IF @DataDomainBoostLockboxPath IS NOT NULL SET @CurrentCommand += ' -a "NSR_DFA_SI_DD_LOCKBOX_PATH=' + REPLACE(@DataDomainBoostLockboxPath,'''','''''') + '"' SET @CurrentCommand += ' -a "NSR_SKIP_NON_BACKUPABLE_STATE_DB=TRUE"' + SET @CurrentCommand += ' -a "BACKUP_PROMOTION=NONE"' IF @CopyOnly = 'Y' SET @CurrentCommand += ' -a "NSR_COPY_ONLY=TRUE"' IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand += ' "MSSQL' + ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' @@ -4494,7 +4495,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 22:30:00 //-- + --// Version: 2020-12-05 18:28:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6384,7 +6385,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-11-29 22:30:00 //-- + --// Version: 2020-12-05 18:28:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From bde8aebadbf0ee532486ecc66c40ffc93c2929cf Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 6 Dec 2020 00:45:26 +0100 Subject: [PATCH 177/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 13 +++++++---- DatabaseIntegrityCheck.sql | 22 +++++++++++++---- IndexOptimize.sql | 9 ++++--- MaintenanceSolution.sql | 48 ++++++++++++++++++++++++++------------ 5 files changed, 65 insertions(+), 29 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 83022ff2..d5f3d587 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -36,7 +36,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-05 18:28:36 //-- + --// Version: 2020-12-06 00:32:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index fa7ca1a9..9b5893e5 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -79,7 +79,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-05 18:28:36 //-- + --// Version: 2020-12-06 00:32:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1978,7 +1978,7 @@ BEGIN SELECT 'The value for the parameter @FileName is not supported.', 16, 3 END - IF @FileName LIKE '%{DirectorySeperator}%' + IF @FileName LIKE '%{DirectorySeparator}%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @FileName is not supported.', 16, 4 @@ -2022,7 +2022,7 @@ BEGIN SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 4 END - IF @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' + IF @AvailabilityGroupFileName LIKE '%{DirectorySeparator}%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 5 @@ -2624,8 +2624,11 @@ BEGIN INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupRole = role_desc, - @CurrentAvailabilityGroupID = group_id + SELECT @CurrentAvailabilityGroupID = group_id + FROM sys.availability_replicas + WHERE replica_id = @CurrentReplicaID + + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentReplicaID diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index b7e188ae..0b29a500 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-05 18:28:36 //-- + --// Version: 2020-12-06 00:32:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -78,6 +78,7 @@ BEGIN DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) + DECLARE @CurrentSecondaryRoleAllowConnections nvarchar(max) DECLARE @CurrentIsPreferredBackupReplica bit DECLARE @CurrentDatabaseMirroringRole nvarchar(max) @@ -1375,8 +1376,12 @@ BEGIN INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupRole = role_desc, - @CurrentAvailabilityGroupID = group_id + SELECT @CurrentAvailabilityGroupID = group_id, + @CurrentSecondaryRoleAllowConnections = secondary_role_allow_connections_desc + FROM sys.availability_replicas + WHERE replica_id = @CurrentReplicaID + + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentReplicaID @@ -1412,6 +1417,12 @@ BEGIN SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + IF @CurrentAvailabilityGroupRole = 'SECONDARY' + BEGIN + SET @DatabaseMessage = 'Readable Secondary: ' + ISNULL(@CurrentSecondaryRoleAllowConnections,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + IF @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' BEGIN SET @DatabaseMessage = 'Availability group backup preference: ' + ISNULL(@CurrentAvailabilityGroupBackupPreference,'N/A') @@ -1464,7 +1475,7 @@ BEGIN -- Check filegroups IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') - AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR (@CurrentAvailabilityGroupRole = 'SECONDARY' AND @CurrentSecondaryRoleAllowConnections = 'ALL') OR @CurrentAvailabilityGroupRole IS NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' @@ -1627,7 +1638,7 @@ BEGIN -- Check objects IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') - AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR (@CurrentAvailabilityGroupRole = 'SECONDARY' AND @CurrentSecondaryRoleAllowConnections = 'ALL') OR @CurrentAvailabilityGroupRole IS NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' @@ -1841,6 +1852,7 @@ BEGIN SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL + SET @CurrentSecondaryRoleAllowConnections = NULL SET @CurrentIsPreferredBackupReplica = NULL SET @CurrentDatabaseMirroringRole = NULL diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 2e6bb6b6..8824ca3d 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -53,7 +53,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-05 18:28:36 //-- + --// Version: 2020-12-06 00:32:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1490,8 +1490,11 @@ BEGIN INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupRole = role_desc, - @CurrentAvailabilityGroupID = group_id + SELECT @CurrentAvailabilityGroupID = group_id + FROM sys.availability_replicas + WHERE replica_id = @CurrentReplicaID + + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentReplicaID diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index f0c5c5d0..f5f7b00b 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-12-05 18:28:36 +Version: 2020-12-06 00:32:13 You can contact me by e-mail at ola@hallengren.com. @@ -123,7 +123,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-05 18:28:36 //-- + --// Version: 2020-12-06 00:32:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -458,7 +458,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-05 18:28:36 //-- + --// Version: 2020-12-06 00:32:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2357,7 +2357,7 @@ BEGIN SELECT 'The value for the parameter @FileName is not supported.', 16, 3 END - IF @FileName LIKE '%{DirectorySeperator}%' + IF @FileName LIKE '%{DirectorySeparator}%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @FileName is not supported.', 16, 4 @@ -2401,7 +2401,7 @@ BEGIN SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 4 END - IF @AvailabilityGroupFileName LIKE '%{DirectorySeperator}%' + IF @AvailabilityGroupFileName LIKE '%{DirectorySeparator}%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 5 @@ -3003,8 +3003,11 @@ BEGIN INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupRole = role_desc, - @CurrentAvailabilityGroupID = group_id + SELECT @CurrentAvailabilityGroupID = group_id + FROM sys.availability_replicas + WHERE replica_id = @CurrentReplicaID + + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentReplicaID @@ -4495,7 +4498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-05 18:28:36 //-- + --// Version: 2020-12-06 00:32:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4534,6 +4537,7 @@ BEGIN DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) + DECLARE @CurrentSecondaryRoleAllowConnections nvarchar(max) DECLARE @CurrentIsPreferredBackupReplica bit DECLARE @CurrentDatabaseMirroringRole nvarchar(max) @@ -5831,8 +5835,12 @@ BEGIN INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupRole = role_desc, - @CurrentAvailabilityGroupID = group_id + SELECT @CurrentAvailabilityGroupID = group_id, + @CurrentSecondaryRoleAllowConnections = secondary_role_allow_connections_desc + FROM sys.availability_replicas + WHERE replica_id = @CurrentReplicaID + + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentReplicaID @@ -5868,6 +5876,12 @@ BEGIN SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + IF @CurrentAvailabilityGroupRole = 'SECONDARY' + BEGIN + SET @DatabaseMessage = 'Readable Secondary: ' + ISNULL(@CurrentSecondaryRoleAllowConnections,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + IF @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' BEGIN SET @DatabaseMessage = 'Availability group backup preference: ' + ISNULL(@CurrentAvailabilityGroupBackupPreference,'N/A') @@ -5920,7 +5934,7 @@ BEGIN -- Check filegroups IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') - AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR (@CurrentAvailabilityGroupRole = 'SECONDARY' AND @CurrentSecondaryRoleAllowConnections = 'ALL') OR @CurrentAvailabilityGroupRole IS NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.filegroups filegroups WHERE [type] <> ''FX'' ORDER BY CASE WHEN filegroups.name = ''PRIMARY'' THEN 1 ELSE 0 END DESC, filegroups.name ASC' @@ -6083,7 +6097,7 @@ BEGIN -- Check objects IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') - AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR (@CurrentAvailabilityGroupRole = 'SECONDARY' AND @CurrentSecondaryRoleAllowConnections = 'ALL') OR @CurrentAvailabilityGroupRole IS NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT schemas.[schema_id] AS SchemaID, schemas.[name] AS SchemaName, objects.[object_id] AS ObjectID, objects.[name] AS ObjectName, RTRIM(objects.[type]) AS ObjectType, 0 AS [Order], 0 AS Selected, 0 AS Completed FROM sys.objects objects INNER JOIN sys.schemas schemas ON objects.schema_id = schemas.schema_id LEFT OUTER JOIN sys.tables tables ON objects.object_id = tables.object_id WHERE objects.[type] IN(''U'',''V'') AND EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.object_id = objects.object_id)' + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL)' ELSE '' END + ' ORDER BY schemas.name ASC, objects.name ASC' @@ -6297,6 +6311,7 @@ BEGIN SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL + SET @CurrentSecondaryRoleAllowConnections = NULL SET @CurrentIsPreferredBackupReplica = NULL SET @CurrentDatabaseMirroringRole = NULL @@ -6385,7 +6400,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-05 18:28:36 //-- + --// Version: 2020-12-06 00:32:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7822,8 +7837,11 @@ BEGIN INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupRole = role_desc, - @CurrentAvailabilityGroupID = group_id + SELECT @CurrentAvailabilityGroupID = group_id + FROM sys.availability_replicas + WHERE replica_id = @CurrentReplicaID + + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentReplicaID From 0ec396b4915ade05a2e4dc906eb35da13726cc85 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 31 Dec 2020 19:03:19 +0100 Subject: [PATCH 178/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 6 +++--- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 14 +++++++------- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index d5f3d587..53f8ff4e 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -36,7 +36,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-06 00:32:13 //-- + --// Version: 2020-12-31 18:58:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 9b5893e5..e64e5a8a 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -79,7 +79,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-06 00:32:13 //-- + --// Version: 2020-12-31 18:58:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2602,7 +2602,7 @@ BEGIN SELECT @CurrentMaxTransferSize = CASE WHEN @MaxTransferSize IS NOT NULL THEN @MaxTransferSize - WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8) THEN 65537 + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version >= 13 AND @Version < 15.0404316) THEN 65537 END IF @CurrentDatabaseState = 'ONLINE' @@ -3525,7 +3525,7 @@ BEGIN IF @Version >= 10 BEGIN - SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8) AND @CurrentMaxTransferSize >= 65537)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END + SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND ((@Version >= 13 AND @CurrentMaxTransferSize >= 65537) OR @Version >= 15.0404316 OR SERVERPROPERTY('EngineEdition') = 8))) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END END IF @CurrentBackupType = 'DIFF' SET @CurrentCommand += ', DIFFERENTIAL' diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 0b29a500..6210fdbd 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-06 00:32:13 //-- + --// Version: 2020-12-31 18:58:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 8824ca3d..17e89f3e 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -53,7 +53,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-06 00:32:13 //-- + --// Version: 2020-12-31 18:58:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index f5f7b00b..a94bb999 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-12-06 00:32:13 +Version: 2020-12-31 18:58:56 You can contact me by e-mail at ola@hallengren.com. @@ -123,7 +123,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-06 00:32:13 //-- + --// Version: 2020-12-31 18:58:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -458,7 +458,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-06 00:32:13 //-- + --// Version: 2020-12-31 18:58:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2981,7 +2981,7 @@ BEGIN SELECT @CurrentMaxTransferSize = CASE WHEN @MaxTransferSize IS NOT NULL THEN @MaxTransferSize - WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8) THEN 65537 + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version >= 13 AND @Version < 15.0404316) THEN 65537 END IF @CurrentDatabaseState = 'ONLINE' @@ -3904,7 +3904,7 @@ BEGIN IF @Version >= 10 BEGIN - SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND (@Version >= 13 OR SERVERPROPERTY('EngineEdition') = 8) AND @CurrentMaxTransferSize >= 65537)) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END + SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND ((@Version >= 13 AND @CurrentMaxTransferSize >= 65537) OR @Version >= 15.0404316 OR SERVERPROPERTY('EngineEdition') = 8))) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END END IF @CurrentBackupType = 'DIFF' SET @CurrentCommand += ', DIFFERENTIAL' @@ -4498,7 +4498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-06 00:32:13 //-- + --// Version: 2020-12-31 18:58:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6400,7 +6400,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-06 00:32:13 //-- + --// Version: 2020-12-31 18:58:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 4e6c9326c61d8d8d16bb2f05c467a1181cdc73f7 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 1 Jan 2021 11:13:19 +0100 Subject: [PATCH 179/188] Update LICENSE --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index a4ea749a..a1f226c7 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2020 Ola Hallengren +Copyright (c) 2021 Ola Hallengren Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From 5f5e9d365d342cee43b71fcf7ff62bd8974e3fda Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 30 Dec 2021 19:54:45 +0100 Subject: [PATCH 180/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 19 +++++++++++++++---- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 27 +++++++++++++++++++-------- 5 files changed, 37 insertions(+), 15 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 53f8ff4e..e8c04070 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -36,7 +36,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-31 18:58:56 //-- + --// Version: 2021-12-30 19:45:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index e64e5a8a..115522c9 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -65,6 +65,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @Format nvarchar(max) = 'N', @ObjectLevelRecoveryMap nvarchar(max) = 'N', @ExcludeLogShippedFromLogBackup nvarchar(max) = 'Y', +@DirectoryCheck nvarchar(max) = 'Y', @StringDelimiter nvarchar(max) = ',', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @@ -79,7 +80,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-31 18:58:56 //-- + --// Version: 2021-12-30 19:45:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -327,6 +328,7 @@ BEGIN SET @Parameters += ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') SET @Parameters += ', @ObjectLevelRecoveryMap = ' + ISNULL('''' + REPLACE(@ObjectLevelRecoveryMap,'''','''''') + '''','NULL') SET @Parameters += ', @ExcludeLogShippedFromLogBackup = ' + ISNULL('''' + REPLACE(@ExcludeLogShippedFromLogBackup,'''','''''') + '''','NULL') + SET @Parameters += ', @DirectoryCheck = ' + ISNULL('''' + REPLACE(@DirectoryCheck,'''','''''') + '''','NULL') SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') @@ -871,7 +873,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF NOT EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) + IF NOT EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) AND @DirectoryCheck = 'Y' BEGIN WHILE (1 = 1) BEGIN @@ -2172,6 +2174,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @DirectoryCheck NOT IN('Y','N') OR @DirectoryCheck IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DirectoryCheck is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -3332,7 +3342,7 @@ BEGIN -- Create directory IF @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) - AND NOT EXISTS(SELECT * FROM @CurrentDirectories WHERE DirectoryPath = 'NUL') + AND NOT EXISTS(SELECT * FROM @CurrentDirectories WHERE DirectoryPath = 'NUL' OR DirectoryPath IN(SELECT DirectoryPath FROM @Directories)) BEGIN WHILE (1 = 1) BEGIN @@ -3484,7 +3494,8 @@ BEGIN END -- Perform a backup - IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE DirectoryPath <> 'NUL' AND (CreateOutput <> 0 OR CreateOutput IS NULL)) OR @HostPlatform = 'Linux' + IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE DirectoryPath <> 'NUL' AND DirectoryPath NOT IN(SELECT DirectoryPath FROM @Directories) AND (CreateOutput <> 0 OR CreateOutput IS NULL)) + OR @HostPlatform = 'Linux' BEGIN IF @BackupSoftware IS NULL BEGIN diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 6210fdbd..1ed09bb3 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-31 18:58:56 //-- + --// Version: 2021-12-30 19:45:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 17e89f3e..10801db8 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -53,7 +53,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-31 18:58:56 //-- + --// Version: 2021-12-30 19:45:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index a94bb999..338d7623 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2020-12-31 18:58:56 +Version: 2021-12-30 19:45:09 You can contact me by e-mail at ola@hallengren.com. @@ -123,7 +123,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-31 18:58:56 //-- + --// Version: 2021-12-30 19:45:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -444,6 +444,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @Format nvarchar(max) = 'N', @ObjectLevelRecoveryMap nvarchar(max) = 'N', @ExcludeLogShippedFromLogBackup nvarchar(max) = 'Y', +@DirectoryCheck nvarchar(max) = 'Y', @StringDelimiter nvarchar(max) = ',', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @@ -458,7 +459,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-31 18:58:56 //-- + --// Version: 2021-12-30 19:45:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -706,6 +707,7 @@ BEGIN SET @Parameters += ', @Format = ' + ISNULL('''' + REPLACE(@Format,'''','''''') + '''','NULL') SET @Parameters += ', @ObjectLevelRecoveryMap = ' + ISNULL('''' + REPLACE(@ObjectLevelRecoveryMap,'''','''''') + '''','NULL') SET @Parameters += ', @ExcludeLogShippedFromLogBackup = ' + ISNULL('''' + REPLACE(@ExcludeLogShippedFromLogBackup,'''','''''') + '''','NULL') + SET @Parameters += ', @DirectoryCheck = ' + ISNULL('''' + REPLACE(@DirectoryCheck,'''','''''') + '''','NULL') SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') @@ -1250,7 +1252,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF NOT EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) + IF NOT EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) AND @DirectoryCheck = 'Y' BEGIN WHILE (1 = 1) BEGIN @@ -2551,6 +2553,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @DirectoryCheck NOT IN('Y','N') OR @DirectoryCheck IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DirectoryCheck is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -3711,7 +3721,7 @@ BEGIN -- Create directory IF @HostPlatform = 'Windows' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) - AND NOT EXISTS(SELECT * FROM @CurrentDirectories WHERE DirectoryPath = 'NUL') + AND NOT EXISTS(SELECT * FROM @CurrentDirectories WHERE DirectoryPath = 'NUL' OR DirectoryPath IN(SELECT DirectoryPath FROM @Directories)) BEGIN WHILE (1 = 1) BEGIN @@ -3863,7 +3873,8 @@ BEGIN END -- Perform a backup - IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE DirectoryPath <> 'NUL' AND (CreateOutput <> 0 OR CreateOutput IS NULL)) OR @HostPlatform = 'Linux' + IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE DirectoryPath <> 'NUL' AND DirectoryPath NOT IN(SELECT DirectoryPath FROM @Directories) AND (CreateOutput <> 0 OR CreateOutput IS NULL)) + OR @HostPlatform = 'Linux' BEGIN IF @BackupSoftware IS NULL BEGIN @@ -4498,7 +4509,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-31 18:58:56 //-- + --// Version: 2021-12-30 19:45:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6400,7 +6411,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2020-12-31 18:58:56 //-- + --// Version: 2021-12-30 19:45:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 36b123697d77839c9cfefd573887197c234afd49 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 31 Dec 2021 19:53:18 +0100 Subject: [PATCH 181/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 10 ++++++---- DatabaseIntegrityCheck.sql | 6 +++--- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 22 ++++++++++++---------- 5 files changed, 23 insertions(+), 19 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index e8c04070..dc221ac6 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -36,7 +36,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-30 19:45:09 //-- + --// Version: 2021-12-31 19:48:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 115522c9..1b409a35 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -80,7 +80,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-30 19:45:09 //-- + --// Version: 2021-12-31 19:48:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1849,13 +1849,13 @@ BEGIN IF @ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ModificationLevel is not supported.', 16, 2 + SELECT 'The parameter @ModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 2 END IF @ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ModificationLevel is not supported.', 16, 3 + SELECT 'The parameter @ModificationLevel can only be used for differential backups.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -2612,7 +2612,7 @@ BEGIN SELECT @CurrentMaxTransferSize = CASE WHEN @MaxTransferSize IS NOT NULL THEN @MaxTransferSize - WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version >= 13 AND @Version < 15.0404316) THEN 65537 + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version >= 13 AND @Version < 15.0404316) AND @Credential IS NULL THEN 65537 END IF @CurrentDatabaseState = 'ONLINE' @@ -2667,6 +2667,8 @@ BEGIN END IF @CurrentDatabaseState = 'ONLINE' AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND @CurrentDatabaseName <> 'master')) + AND (@ModificationLevel IS NOT NULL OR @MinBackupSizeForMultipleFiles IS NOT NULL OR @MaxFileSize IS NOT NULL) BEGIN SET @CurrentCommand = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 1ed09bb3..1056dfb2 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-30 19:45:09 //-- + --// Version: 2021-12-31 19:48:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1357,7 +1357,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - IF @CurrentDatabaseState = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 + IF @CurrentDatabaseState IN('ONLINE','EMERGENCY') AND SERVERPROPERTY('EngineEdition') <> 5 BEGIN IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) AND database_guid IS NOT NULL) BEGIN @@ -1441,7 +1441,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT - IF @CurrentDatabaseState = 'ONLINE' + IF @CurrentDatabaseState IN('ONLINE','EMERGENCY') AND NOT (@CurrentUserAccess = 'SINGLE_USER' AND @CurrentIsDatabaseAccessible = 0) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR SERVERPROPERTY('EngineEdition') = 3) AND ((@AvailabilityGroupReplicas = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY') OR (@AvailabilityGroupReplicas = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY') OR (@AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' AND @CurrentIsPreferredBackupReplica = 1) OR @AvailabilityGroupReplicas = 'ALL' OR @CurrentAvailabilityGroupRole IS NULL) diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 10801db8..a50f8d89 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -53,7 +53,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-30 19:45:09 //-- + --// Version: 2021-12-31 19:48:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 338d7623..e45cfda5 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2021-12-30 19:45:09 +Version: 2021-12-31 19:48:31 You can contact me by e-mail at ola@hallengren.com. @@ -123,7 +123,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-30 19:45:09 //-- + --// Version: 2021-12-31 19:48:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -459,7 +459,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-30 19:45:09 //-- + --// Version: 2021-12-31 19:48:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2228,13 +2228,13 @@ BEGIN IF @ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ModificationLevel is not supported.', 16, 2 + SELECT 'The parameter @ModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 2 END IF @ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ModificationLevel is not supported.', 16, 3 + SELECT 'The parameter @ModificationLevel can only be used for differential backups.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -2991,7 +2991,7 @@ BEGIN SELECT @CurrentMaxTransferSize = CASE WHEN @MaxTransferSize IS NOT NULL THEN @MaxTransferSize - WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version >= 13 AND @Version < 15.0404316) THEN 65537 + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version >= 13 AND @Version < 15.0404316) AND @Credential IS NULL THEN 65537 END IF @CurrentDatabaseState = 'ONLINE' @@ -3046,6 +3046,8 @@ BEGIN END IF @CurrentDatabaseState = 'ONLINE' AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND @CurrentDatabaseName <> 'master')) + AND (@ModificationLevel IS NOT NULL OR @MinBackupSizeForMultipleFiles IS NOT NULL OR @MaxFileSize IS NOT NULL) BEGIN SET @CurrentCommand = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' @@ -4509,7 +4511,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-30 19:45:09 //-- + --// Version: 2021-12-31 19:48:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5827,7 +5829,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - IF @CurrentDatabaseState = 'ONLINE' AND SERVERPROPERTY('EngineEdition') <> 5 + IF @CurrentDatabaseState IN('ONLINE','EMERGENCY') AND SERVERPROPERTY('EngineEdition') <> 5 BEGIN IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) AND database_guid IS NOT NULL) BEGIN @@ -5911,7 +5913,7 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT - IF @CurrentDatabaseState = 'ONLINE' + IF @CurrentDatabaseState IN('ONLINE','EMERGENCY') AND NOT (@CurrentUserAccess = 'SINGLE_USER' AND @CurrentIsDatabaseAccessible = 0) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR SERVERPROPERTY('EngineEdition') = 3) AND ((@AvailabilityGroupReplicas = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY') OR (@AvailabilityGroupReplicas = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY') OR (@AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' AND @CurrentIsPreferredBackupReplica = 1) OR @AvailabilityGroupReplicas = 'ALL' OR @CurrentAvailabilityGroupRole IS NULL) @@ -6411,7 +6413,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-30 19:45:09 //-- + --// Version: 2021-12-31 19:48:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 7c88f4f7e00259bf3201f2663583dadb1b44aefe Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 1 Jan 2022 22:28:44 +0100 Subject: [PATCH 182/188] Update LICENSE --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index a1f226c7..b9d71604 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2021 Ola Hallengren +Copyright (c) 2022 Ola Hallengren Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From af934efd3f30aa01b096f6ebebe89d5d8ba72c7e Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 2 Jan 2022 14:04:24 +0100 Subject: [PATCH 183/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 37 ++++++++++++------------------- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 45 +++++++++++++++----------------------- 5 files changed, 35 insertions(+), 53 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index dc221ac6..6b3304ec 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -36,7 +36,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-31 19:48:31 //-- + --// Version: 2022-01-02 13:58:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 1b409a35..777fc567 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -80,7 +80,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-31 19:48:31 //-- + --// Version: 2022-01-02 13:58:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -800,7 +800,7 @@ BEGIN IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Directory is not supported.', 16, 3 + SELECT 'The number of directories for the parameters @Directory and @MirrorDirectory has to be the same.', 16, 3 END IF (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') @@ -818,7 +818,7 @@ BEGIN IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Directory is not supported.', 16, 6 + SELECT 'Mirrored backup is not supported when backing up to NUL', 16, 6 END ---------------------------------------------------------------------------------------------------- @@ -835,12 +835,6 @@ BEGIN SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 2 END - IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 3 - END - IF @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -859,12 +853,6 @@ BEGIN SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 6 END - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 7 - END - IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -1176,7 +1164,7 @@ BEGIN IF @Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786)))) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Compress is not supported.', 16, 2 + SELECT 'The value for the parameter @Compress is not supported. Backup compression is not supported in this version and edition of SQL Server.', 16, 2 END IF @Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1) @@ -1276,7 +1264,7 @@ BEGIN IF @BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BlockSize is not supported.', 16, 4 + SELECT 'BLOCKSIZE is not supported when backing up to URL with page blobs. See https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url', 16, 4 END IF @BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' @@ -1328,7 +1316,7 @@ BEGIN IF @MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 4 + SELECT 'MAXTRANSFERSIZE is not supported when backing up to URL with page blobs. See https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url', 16, 4 END IF @MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' @@ -1366,7 +1354,7 @@ BEGIN IF @URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 5 + SELECT 'Backup striping to URL with page blobs is not supported. See https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url', 16, 5 END IF @NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) @@ -2615,7 +2603,7 @@ BEGIN WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version >= 13 AND @Version < 15.0404316) AND @Credential IS NULL THEN 65537 END - IF @CurrentDatabaseState = 'ONLINE' + IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentInStandby = 1) BEGIN IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) AND database_guid IS NOT NULL) BEGIN @@ -2659,14 +2647,16 @@ BEGIN AND [type] = 0 AND [file_id] = 1 - IF @CurrentDatabaseState = 'ONLINE' + IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentInStandby = 1) BEGIN SELECT @CurrentLogLSN = last_log_backup_lsn FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) END - IF @CurrentDatabaseState = 'ONLINE' AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentInStandby = 1) + AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND @CurrentDatabaseName <> 'master')) AND (@ModificationLevel IS NOT NULL OR @MinBackupSizeForMultipleFiles IS NOT NULL OR @MaxFileSize IS NOT NULL) BEGIN @@ -2689,7 +2679,8 @@ BEGIN END END - IF @CurrentDatabaseState = 'ONLINE' AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') + IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentInStandby = 1) + AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN SELECT @CurrentLastLogBackup = log_backup_time, @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 1056dfb2..b39e8454 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-31 19:48:31 //-- + --// Version: 2022-01-02 13:58:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index a50f8d89..840e30ef 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -53,7 +53,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-31 19:48:31 //-- + --// Version: 2022-01-02 13:58:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index e45cfda5..d3e4e6d5 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2021-12-31 19:48:31 +Version: 2022-01-02 13:58:13 You can contact me by e-mail at ola@hallengren.com. @@ -123,7 +123,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-31 19:48:31 //-- + --// Version: 2022-01-02 13:58:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -459,7 +459,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-31 19:48:31 //-- + --// Version: 2022-01-02 13:58:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1179,7 +1179,7 @@ BEGIN IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Directory is not supported.', 16, 3 + SELECT 'The number of directories for the parameters @Directory and @MirrorDirectory has to be the same.', 16, 3 END IF (@Directory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') @@ -1197,7 +1197,7 @@ BEGIN IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Directory is not supported.', 16, 6 + SELECT 'Mirrored backup is not supported when backing up to NUL', 16, 6 END ---------------------------------------------------------------------------------------------------- @@ -1214,12 +1214,6 @@ BEGIN SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 2 END - IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) <> (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 0 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 3 - END - IF @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -1238,12 +1232,6 @@ BEGIN SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 6 END - IF EXISTS(SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 7 - END - IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -1555,7 +1543,7 @@ BEGIN IF @Compress = 'Y' AND @BackupSoftware IS NULL AND NOT ((@Version >= 10 AND @Version < 10.5 AND SERVERPROPERTY('EngineEdition') = 3) OR (@Version >= 10.5 AND (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786)))) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Compress is not supported.', 16, 2 + SELECT 'The value for the parameter @Compress is not supported. Backup compression is not supported in this version and edition of SQL Server.', 16, 2 END IF @Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevel IS NULL OR @CompressionLevel >= 1) @@ -1655,7 +1643,7 @@ BEGIN IF @BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BlockSize is not supported.', 16, 4 + SELECT 'BLOCKSIZE is not supported when backing up to URL with page blobs. See https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url', 16, 4 END IF @BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' @@ -1707,7 +1695,7 @@ BEGIN IF @MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 4 + SELECT 'MAXTRANSFERSIZE is not supported when backing up to URL with page blobs. See https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url', 16, 4 END IF @MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' @@ -1745,7 +1733,7 @@ BEGIN IF @URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 5 + SELECT 'Backup striping to URL with page blobs is not supported. See https://docs.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url', 16, 5 END IF @NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) @@ -2994,7 +2982,7 @@ BEGIN WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version >= 13 AND @Version < 15.0404316) AND @Credential IS NULL THEN 65537 END - IF @CurrentDatabaseState = 'ONLINE' + IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentInStandby = 1) BEGIN IF EXISTS (SELECT * FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) AND database_guid IS NOT NULL) BEGIN @@ -3038,14 +3026,16 @@ BEGIN AND [type] = 0 AND [file_id] = 1 - IF @CurrentDatabaseState = 'ONLINE' + IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentInStandby = 1) BEGIN SELECT @CurrentLogLSN = last_log_backup_lsn FROM sys.database_recovery_status WHERE database_id = DB_ID(@CurrentDatabaseName) END - IF @CurrentDatabaseState = 'ONLINE' AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) + IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentInStandby = 1) + AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND @CurrentDatabaseName <> 'master')) AND (@ModificationLevel IS NOT NULL OR @MinBackupSizeForMultipleFiles IS NOT NULL OR @MaxFileSize IS NOT NULL) BEGIN @@ -3068,7 +3058,8 @@ BEGIN END END - IF @CurrentDatabaseState = 'ONLINE' AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') + IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentInStandby = 1) + AND EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_log_stats') AND name = 'log_since_last_log_backup_mb') BEGIN SELECT @CurrentLastLogBackup = log_backup_time, @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb @@ -4511,7 +4502,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-31 19:48:31 //-- + --// Version: 2022-01-02 13:58:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6413,7 +6404,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2021-12-31 19:48:31 //-- + --// Version: 2022-01-02 13:58:13 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 499c42bec571f5e214a64c01a4cb5c012bf3a6e8 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 3 Dec 2022 17:31:28 +0100 Subject: [PATCH 184/188] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 ++++++------ 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 6b3304ec..a30695e1 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -36,7 +36,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2022-01-02 13:58:13 //-- + --// Version: 2022-12-03 17:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 777fc567..60e4684a 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -80,7 +80,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2022-01-02 13:58:13 //-- + --// Version: 2022-12-03 17:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index b39e8454..f4f3e063 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -39,7 +39,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2022-01-02 13:58:13 //-- + --// Version: 2022-12-03 17:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 840e30ef..3410ce7f 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -53,7 +53,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2022-01-02 13:58:13 //-- + --// Version: 2022-12-03 17:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index d3e4e6d5..48be1f80 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -1,6 +1,6 @@ /* -SQL Server Maintenance Solution - SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, and SQL Server 2019 +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 Backup: https://ola.hallengren.com/sql-server-backup.html Integrity Check: https://ola.hallengren.com/sql-server-integrity-check.html @@ -10,7 +10,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2022-01-02 13:58:13 +Version: 2022-12-03 17:23:44 You can contact me by e-mail at ola@hallengren.com. @@ -123,7 +123,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2022-01-02 13:58:13 //-- + --// Version: 2022-12-03 17:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -459,7 +459,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2022-01-02 13:58:13 //-- + --// Version: 2022-12-03 17:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4502,7 +4502,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2022-01-02 13:58:13 //-- + --// Version: 2022-12-03 17:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6404,7 +6404,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2022-01-02 13:58:13 //-- + --// Version: 2022-12-03 17:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 8686995d4526f6561bf16795868a9720df5b7ffa Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 3 Dec 2022 17:32:30 +0100 Subject: [PATCH 185/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dc40e985..009a1f32 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ You can also download the objects as separate scripts: Note that you always need CommandExecute; DatabaseBackup, DatabaseIntegrityCheck, and IndexOptimize are using it. You need CommandLog if you are going to use the option to log commands to a table. -Supported versions: SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, SQL Server 2019, Azure SQL Database, and Azure SQL Database Managed Instance +Supported versions: SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, SQL Server 2019, SQL Server 2022, Azure SQL Database, and Azure SQL Database Managed Instance ## Documentation From 9ee2513a4156a7e7252a1cb430173421b3c71053 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 3 Dec 2022 17:33:03 +0100 Subject: [PATCH 186/188] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 009a1f32..9583a0e5 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ You can also download the objects as separate scripts: Note that you always need CommandExecute; DatabaseBackup, DatabaseIntegrityCheck, and IndexOptimize are using it. You need CommandLog if you are going to use the option to log commands to a table. -Supported versions: SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, SQL Server 2019, SQL Server 2022, Azure SQL Database, and Azure SQL Database Managed Instance +Supported versions: SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, SQL Server 2019, SQL Server 2022, Azure SQL Database, and Azure SQL Managed Instance ## Documentation From 3fb051dd500c4656190eb2959cf28270b7e47fc1 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 8 Jan 2023 17:00:05 +0100 Subject: [PATCH 187/188] Update LICENSE --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index b9d71604..3522472b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2022 Ola Hallengren +Copyright (c) 2023 Ola Hallengren Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From bd9f54f024a5ad2f5de4e8838bb7736575b77115 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 19 Oct 2024 20:56:02 +0200 Subject: [PATCH 188/188] Update LICENSE --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 3522472b..9b375a04 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2023 Ola Hallengren +Copyright (c) 2024 Ola Hallengren Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal