From 5fc7b997c9b0acaee2c9b972d6b1a006d38f3564 Mon Sep 17 00:00:00 2001 From: Ysaias Portes Date: Wed, 20 May 2026 09:18:57 -0400 Subject: [PATCH 001/177] Add @MinIndexUsageDays to IndexOptimize Adds a single user-facing parameter that skips apparently-unused non-clustered indexes, but only when sys.dm_db_index_usage_stats has accumulated enough history to be trusted (>= @MinIndexUsageDays). Trust is derived internally from MAX(sqlserver_start_time, database create_date, earliest DMV activity); the user cannot override it. When the DMV is too young, the script logs a clear diagnostic and falls back to fragmentation-only behavior. Backward compatible: default NULL preserves existing behavior. --- IndexOptimize.sql | 83 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 81 insertions(+), 2 deletions(-) diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 04a9428c..1d4dbb94 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -9,7 +9,6 @@ END GO ALTER PROCEDURE [dbo].[IndexOptimize] - @Databases nvarchar(max) = NULL, @FragmentationLow nvarchar(max) = NULL, @FragmentationMedium nvarchar(max) = 'INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', @@ -44,6 +43,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @DatabasesInParallel nvarchar(max) = 'N', @ExecuteAsUser nvarchar(max) = NULL, @LogToTable nvarchar(max) = 'N', +@MinIndexUsageDays int = NULL, @Execute nvarchar(max) = 'Y' AS @@ -255,6 +255,12 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) + + DECLARE @CurrentStatsResetEstimate datetime2 + DECLARE @CurrentHoursSinceReset int + DECLARE @CurrentStatsTrusted bit + DECLARE @RequiredTrustHours int = @MinIndexUsageDays * 24 + 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 @@ -307,6 +313,7 @@ BEGIN SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') SET @Parameters += ', @ExecuteAsUser = ' + ISNULL('''' + REPLACE(@ExecuteAsUser,'''','''''') + '''','NULL') SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') + SET @Parameters += ', @MinIndexUsageDays = ' + ISNULL(CAST(@MinIndexUsageDays AS nvarchar),'NULL') SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) @@ -976,6 +983,13 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @MinIndexUsageDays < 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @MinIndexUsageDays is not supported.', 16, 1 + END + ---------------------------------------------------------------------------------------------------- + IF @Delay < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -1456,7 +1470,44 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Recovery model: ' + @CurrentRecoveryModel + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + -- Reset internal trust state for this database. + SET @CurrentStatsResetEstimate = NULL + SET @CurrentHoursSinceReset = NULL + SET @CurrentStatsTrusted = NULL + + -- Only compute the estimate when the user actually opted in. + -- take the LATEST of + -- 1) instance start time -- a restart wipes the DMV + -- 2) database create_date -- catches attach / restore-with-new-id + -- 3) earliest activity in the DMV -- a lower bound; usage must be at least this old + IF @MinIndexUsageDays IS NOT NULL + AND @CurrentDatabaseState = 'ONLINE' + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) + AND NOT (@AmazonRDS = 1 AND @CurrentDatabaseName = 'rdsadmin') + BEGIN + SELECT @CurrentStatsResetEstimate = + (SELECT MAX(t) FROM (VALUES + ((SELECT sqlserver_start_time FROM sys.dm_os_sys_info)), + ((SELECT create_date FROM sys.databases WHERE [name] = @CurrentDatabaseName)), + ((SELECT MIN(x) FROM (VALUES + ((SELECT MIN(last_user_seek) FROM sys.dm_db_index_usage_stats WHERE database_id = DB_ID(@CurrentDatabaseName))), + ((SELECT MIN(last_user_scan) FROM sys.dm_db_index_usage_stats WHERE database_id = DB_ID(@CurrentDatabaseName))), + ((SELECT MIN(last_user_lookup) FROM sys.dm_db_index_usage_stats WHERE database_id = DB_ID(@CurrentDatabaseName))), + ((SELECT MIN(last_user_update) FROM sys.dm_db_index_usage_stats WHERE database_id = DB_ID(@CurrentDatabaseName))) + ) AS u(x))) + ) AS r(t)) + + SET @CurrentHoursSinceReset = DATEDIFF(HOUR, @CurrentStatsResetEstimate, SYSDATETIME()) + SET @CurrentStatsTrusted = CASE WHEN @CurrentHoursSinceReset >= @RequiredTrustHours + THEN 1 ELSE 0 END + + SET @DatabaseMessage = 'Usage stats reset estimate: ' + ISNULL(CONVERT(nvarchar(30), @CurrentStatsResetEstimate, 121),'N/A') + + ' (hours since: ' + ISNULL(CAST(@CurrentHoursSinceReset AS nvarchar), 'N/A') + ')' + + ' - Trusted: ' + CASE WHEN @CurrentStatsTrusted = 1 THEN 'Yes' ELSE 'NO - Insufficient history in sys.dm_db_index_usage_stats (likely restart, failover, detach/attach, or recent index DDL). Skipping the unused-index filter for this database to avoid false positives; fragmentation-based maintenance will still run.' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 @@ -1749,6 +1800,30 @@ BEGIN AND (tmpIndexesStatistics.StatisticsName = SelectedIndexes2.StatisticsName OR tmpIndexesStatistics.StatisticsName IS NULL) END; + + -- Skip indexes that look unused, but ONLY when the DMV is old enough to trust. + -- If the DMV is too young (@CurrentStatsTrusted = 0), do nothing here: + -- we fall back to the existing fragmentation-based behavior rather than + -- making decisions on data we cannot trust. + IF @MinIndexUsageDays IS NOT NULL AND @CurrentStatsTrusted = 1 + BEGIN + UPDATE tis + SET tis.Selected = 0 + FROM @tmpIndexesStatistics tis + WHERE tis.IndexID IS NOT NULL + AND tis.IndexID > 1 -- never deselect the clustered index / heap entry + AND NOT EXISTS ( + SELECT 1 + FROM sys.dm_db_index_usage_stats us + WHERE us.database_id = DB_ID(@CurrentDatabaseName) + AND us.object_id = tis.ObjectID + AND us.index_id = tis.IndexID + AND (us.user_seeks + us.user_scans + us.user_lookups) > 0 + ) + END; + + + WITH tmpIndexesStatistics AS ( 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 @@ -2391,6 +2466,10 @@ BEGIN END -- Clear variables + SET @CurrentStatsResetEstimate = NULL + SET @CurrentHoursSinceReset = NULL + SET @CurrentStatsTrusted = NULL + SET @CurrentDBID = NULL SET @CurrentDatabaseName = NULL @@ -2417,7 +2496,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- --// Log completing information //-- - ---------------------------------------------------------------------------------------------------- + ---------------------------------------------C:\Users\yportest\source\repos\sql-server-maintenance-solution\IndexOptimize.sql------------------------------------------------------- Logging: SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) From 4a59638b9e5b211336c10455e00116ca63a15f35 Mon Sep 17 00:00:00 2001 From: Ysaias Portes Date: Wed, 20 May 2026 10:27:11 -0400 Subject: [PATCH 002/177] Fix: move trust check after AG role discovery MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The trust-check block was inserted before @CurrentAvailabilityGroup and @CurrentAvailabilityGroupRole are populated, so the guard condition evaluated NULL IS NOT NULL = FALSE and the block ran on AG secondaries — exactly the case it was meant to skip. Move the block to immediately before the @ExecuteAsUser check, after the AG and mirroring role discovery and their RAISERROR messages, so the guard sees real values. No change to the block's contents. --- IndexOptimize.sql | 74 ++++++++++++++--------------------------------- 1 file changed, 22 insertions(+), 52 deletions(-) diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 1d4dbb94..d03a4dc1 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -1477,11 +1477,20 @@ BEGIN SET @CurrentHoursSinceReset = NULL SET @CurrentStatsTrusted = NULL - -- Only compute the estimate when the user actually opted in. - -- take the LATEST of + -- Reset internal trust state for this database. + SET @CurrentStatsResetEstimate = NULL + SET @CurrentHoursSinceReset = NULL + SET @CurrentStatsTrusted = NULL + + -- Estimate when sys.dm_db_index_usage_stats was last reset for this DB. + -- Take the LATEST of: -- 1) instance start time -- a restart wipes the DMV - -- 2) database create_date -- catches attach / restore-with-new-id + -- 2) database create_date -- catches attach / restore / new DBs -- 3) earliest activity in the DMV -- a lower bound; usage must be at least this old + -- Skip the computation entirely on contexts where the DMV would be misleading or unavailable: + -- - DB not ONLINE + -- - AG secondary (or DB whose AG role cannot be determined) + -- - Amazon RDS rdsadmin IF @MinIndexUsageDays IS NOT NULL AND @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) @@ -1503,58 +1512,19 @@ BEGIN SET @CurrentStatsTrusted = CASE WHEN @CurrentHoursSinceReset >= @RequiredTrustHours THEN 1 ELSE 0 END - SET @DatabaseMessage = 'Usage stats reset estimate: ' + ISNULL(CONVERT(nvarchar(30), @CurrentStatsResetEstimate, 121),'N/A') - + ' (hours since: ' + ISNULL(CAST(@CurrentHoursSinceReset AS nvarchar), 'N/A') + ')' - + ' - Trusted: ' + CASE WHEN @CurrentStatsTrusted = 1 THEN 'Yes' ELSE 'NO - Insufficient history in sys.dm_db_index_usage_stats (likely restart, failover, detach/attach, or recent index DDL). Skipping the unused-index filter for this database to avoid false positives; fragmentation-based maintenance will still run.' END + SET @DatabaseMessage = 'Usage stats reset estimate: ' + + ISNULL(CONVERT(nvarchar(30), @CurrentStatsResetEstimate, 121),'N/A') + + ' (DMV age: ' + ISNULL(CAST(@CurrentHoursSinceReset AS nvarchar), 'N/A') + ' h' + + ', required: ' + CAST(@RequiredTrustHours AS nvarchar) + ' h / ' + + CAST(@MinIndexUsageDays AS nvarchar) + ' d) - Trusted: ' + + CASE WHEN @CurrentStatsTrusted = 1 + THEN 'Yes' + ELSE 'NO - Insufficient history in sys.dm_db_index_usage_stats (likely restart, failover, detach/attach, or recent index DDL). Unused-index skip disabled for this database; fragmentation-based maintenance will still run.' + END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 - BEGIN - 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 @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 - - SELECT @CurrentAvailabilityGroup = [name] - FROM sys.availability_groups - WHERE group_id = @CurrentAvailabilityGroupID - END - - IF SERVERPROPERTY('EngineEdition') <> 5 - BEGIN - SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) - FROM sys.database_mirroring database_mirroring - INNER JOIN sys.databases databases ON database_mirroring.database_id = databases.database_id - WHERE databases.[name] = @CurrentDatabaseName - END - - IF @CurrentAvailabilityGroup IS NOT NULL - BEGIN - SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - - SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - END - - IF @CurrentDatabaseMirroringRole IS NOT NULL - BEGIN - SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - END - - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - IF @ExecuteAsUser IS NOT NULL AND @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentUserAccess = 'SINGLE_USER') @@ -2496,7 +2466,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- --// Log completing information //-- - ---------------------------------------------C:\Users\yportest\source\repos\sql-server-maintenance-solution\IndexOptimize.sql------------------------------------------------------- + ---------------------------------------------------------------------------------------------------- Logging: SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) From edc8eb0c8b754dacb3619255e75a14699ee4919e Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 20 May 2026 18:57:58 +0200 Subject: [PATCH 003/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 29 +++++++++++++++-------------- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 37 +++++++++++++++++++------------------ 5 files changed, 37 insertions(+), 35 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 6cea42f2..9743efeb 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: 2026-05-18 20:15:56 //-- + --// Version: 2026-05-20 18:56:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 698f334d..aee03383 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-18 20:15:56 //-- + --// Version: 2026-05-20 18:56:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -260,7 +260,8 @@ BEGIN FilePath nvarchar(max), Mirror bit) - DECLARE @CurrentCleanupDates TABLE (CleanupDate datetime2, + DECLARE @CurrentCleanupDates TABLE ([Type] nvarchar(max), + CleanupDate datetime2, Mirror bit) DECLARE @Error int = 0 @@ -3067,13 +3068,13 @@ BEGIN SET @CurrentDate = SYSDATETIME() SET @CurrentDateUTC = SYSUTCDATETIME() - INSERT INTO @CurrentCleanupDates (CleanupDate) - SELECT @CurrentDate + INSERT INTO @CurrentCleanupDates ([Type], CleanupDate) + SELECT 'CurrentTime', @CurrentDate IF @CurrentBackupType = 'LOG' BEGIN - INSERT INTO @CurrentCleanupDates (CleanupDate) - SELECT @CurrentLatestBackup + INSERT INTO @CurrentCleanupDates ([Type], CleanupDate) + SELECT 'LatestBackupTime', @CurrentLatestBackup END SELECT @CurrentDirectoryStructure = CASE @@ -3645,8 +3646,8 @@ BEGIN IF @CleanupMode = 'BEFORE_BACKUP' BEGIN - INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 + INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) + SELECT 'CleanupTime', DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 0 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -3661,8 +3662,8 @@ BEGIN IF @MirrorCleanupMode = 'BEFORE_BACKUP' BEGIN - INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 + INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) + SELECT 'MirrorCleanupTime', DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 1 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -4166,8 +4167,8 @@ BEGIN IF @CleanupMode = 'AFTER_BACKUP' BEGIN - INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 + INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) + SELECT 'CleanupTime', DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 0 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -4182,8 +4183,8 @@ BEGIN IF @MirrorCleanupMode = 'AFTER_BACKUP' BEGIN - INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 + INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) + SELECT 'MirrorCleanupTime', DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 1 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index e15e2244..b180a408 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-18 20:15:56 //-- + --// Version: 2026-05-20 18:56:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 04a9428c..3ab9dace 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-18 20:15:56 //-- + --// Version: 2026-05-20 18:56:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 6fc95474..84aa04cf 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: 2026-05-18 20:15:56 +Version: 2026-05-20 18:56:46 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-18 20:15:56 //-- + --// Version: 2026-05-20 18:56:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -484,7 +484,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-18 20:15:56 //-- + --// Version: 2026-05-20 18:56:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -653,7 +653,8 @@ BEGIN FilePath nvarchar(max), Mirror bit) - DECLARE @CurrentCleanupDates TABLE (CleanupDate datetime2, + DECLARE @CurrentCleanupDates TABLE ([Type] nvarchar(max), + CleanupDate datetime2, Mirror bit) DECLARE @Error int = 0 @@ -3460,13 +3461,13 @@ BEGIN SET @CurrentDate = SYSDATETIME() SET @CurrentDateUTC = SYSUTCDATETIME() - INSERT INTO @CurrentCleanupDates (CleanupDate) - SELECT @CurrentDate + INSERT INTO @CurrentCleanupDates ([Type], CleanupDate) + SELECT 'CurrentTime', @CurrentDate IF @CurrentBackupType = 'LOG' BEGIN - INSERT INTO @CurrentCleanupDates (CleanupDate) - SELECT @CurrentLatestBackup + INSERT INTO @CurrentCleanupDates ([Type], CleanupDate) + SELECT 'LatestBackupTime', @CurrentLatestBackup END SELECT @CurrentDirectoryStructure = CASE @@ -4038,8 +4039,8 @@ BEGIN IF @CleanupMode = 'BEFORE_BACKUP' BEGIN - INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 + INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) + SELECT 'CleanupTime', DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 0 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -4054,8 +4055,8 @@ BEGIN IF @MirrorCleanupMode = 'BEFORE_BACKUP' BEGIN - INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 + INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) + SELECT 'MirrorCleanupTime', DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 1 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -4559,8 +4560,8 @@ BEGIN IF @CleanupMode = 'AFTER_BACKUP' BEGIN - INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 + INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) + SELECT 'CleanupTime', DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 0 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -4575,8 +4576,8 @@ BEGIN IF @MirrorCleanupMode = 'AFTER_BACKUP' BEGIN - INSERT INTO @CurrentCleanupDates (CleanupDate, Mirror) - SELECT DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 + INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) + SELECT 'MirrorCleanupTime', DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 1 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -4816,7 +4817,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-18 20:15:56 //-- + --// Version: 2026-05-20 18:56:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6715,7 +6716,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-18 20:15:56 //-- + --// Version: 2026-05-20 18:56:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From c8679e7650bb80619cab86a5af77aeed7b023cc8 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 22 May 2026 18:50:18 +0200 Subject: [PATCH 004/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 12 ++---------- MaintenanceSolution.sql | 20 ++++++-------------- 5 files changed, 11 insertions(+), 27 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 9743efeb..905c3ff5 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: 2026-05-20 18:56:46 //-- + --// Version: 2026-05-22 18:49:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index aee03383..3b79a60a 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-20 18:56:46 //-- + --// Version: 2026-05-22 18:49:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index b180a408..d532b9e4 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-20 18:56:46 //-- + --// Version: 2026-05-22 18:49:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 3ab9dace..17253438 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-20 18:56:46 //-- + --// Version: 2026-05-22 18:49:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1913,20 +1913,12 @@ BEGIN 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 @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' END - ELSE - BEGIN - 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 = @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 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 @@ -2067,7 +2059,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 ((@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 ((@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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL) 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' diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 84aa04cf..a40e6cc4 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: 2026-05-20 18:56:46 +Version: 2026-05-22 18:49:29 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-20 18:56:46 //-- + --// Version: 2026-05-22 18:49:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -484,7 +484,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-20 18:56:46 //-- + --// Version: 2026-05-22 18:49:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4817,7 +4817,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-20 18:56:46 //-- + --// Version: 2026-05-22 18:49:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6716,7 +6716,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-20 18:56:46 //-- + --// Version: 2026-05-22 18:49:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8575,20 +8575,12 @@ BEGIN 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 @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' END - ELSE - BEGIN - 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 = @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 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 @@ -8729,7 +8721,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 ((@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 ((@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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL) 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' From eb473d14de237168feda3c4bf446d2cde818126d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 23 May 2026 17:07:19 +0200 Subject: [PATCH 005/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 13 +++++-------- MaintenanceSolution.sql | 21 +++++++++------------ 5 files changed, 17 insertions(+), 23 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 905c3ff5..0c46223c 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: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:06:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 3b79a60a..37b980e2 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:06:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index d532b9e4..ced4bff6 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:06:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 17253438..419fdff6 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:06:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2045,15 +2045,12 @@ BEGIN SET @CurrentAction = 'INDEX_REBUILD_ONLINE' END + SET @CurrentMaxDOP = @MaxDOP + -- Workaround for limitation in SQL Server, http://support.microsoft.com/kb/2292737 - IF @CurrentIndexID IS NOT NULL + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentIndexType IN (1, 2) AND @CurrentAllowPageLocks = 0 BEGIN - SET @CurrentMaxDOP = @MaxDOP - - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentAllowPageLocks = 0 - BEGIN - SET @CurrentMaxDOP = 1 - END + SET @CurrentMaxDOP = 1 END -- Update statistics? diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index a40e6cc4..53a81d5f 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: 2026-05-22 18:49:29 +Version: 2026-05-23 17:06:30 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:06:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -484,7 +484,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:06:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4817,7 +4817,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:06:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6716,7 +6716,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:06:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8707,15 +8707,12 @@ BEGIN SET @CurrentAction = 'INDEX_REBUILD_ONLINE' END + SET @CurrentMaxDOP = @MaxDOP + -- Workaround for limitation in SQL Server, http://support.microsoft.com/kb/2292737 - IF @CurrentIndexID IS NOT NULL + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentIndexType IN (1, 2) AND @CurrentAllowPageLocks = 0 BEGIN - SET @CurrentMaxDOP = @MaxDOP - - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentAllowPageLocks = 0 - BEGIN - SET @CurrentMaxDOP = 1 - END + SET @CurrentMaxDOP = 1 END -- Update statistics? From 142908cedcd65d51e28aabf8f83e2385dab5d3fe Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 23 May 2026 17:25:14 +0200 Subject: [PATCH 006/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 15 ++++++--------- MaintenanceSolution.sql | 23 ++++++++++------------- 5 files changed, 19 insertions(+), 25 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 905c3ff5..a0819099 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: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 3b79a60a..e3e5f6b4 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index d532b9e4..85d631c3 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 17253438..e09680ab 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2045,15 +2045,12 @@ BEGIN SET @CurrentAction = 'INDEX_REBUILD_ONLINE' END + SET @CurrentMaxDOP = @MaxDOP + -- Workaround for limitation in SQL Server, http://support.microsoft.com/kb/2292737 - IF @CurrentIndexID IS NOT NULL + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentIndexType IN (1, 2) AND @CurrentAllowPageLocks = 0 BEGIN - SET @CurrentMaxDOP = @MaxDOP - - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentAllowPageLocks = 0 - BEGIN - SET @CurrentMaxDOP = 1 - END + SET @CurrentMaxDOP = 1 END -- Update statistics? @@ -2219,7 +2216,7 @@ 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 += 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' 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 diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index a40e6cc4..ad78d11d 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: 2026-05-22 18:49:29 +Version: 2026-05-23 17:23:48 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -484,7 +484,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4817,7 +4817,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6716,7 +6716,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-22 18:49:29 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8707,15 +8707,12 @@ BEGIN SET @CurrentAction = 'INDEX_REBUILD_ONLINE' END + SET @CurrentMaxDOP = @MaxDOP + -- Workaround for limitation in SQL Server, http://support.microsoft.com/kb/2292737 - IF @CurrentIndexID IS NOT NULL + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentIndexType IN (1, 2) AND @CurrentAllowPageLocks = 0 BEGIN - SET @CurrentMaxDOP = @MaxDOP - - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentAllowPageLocks = 0 - BEGIN - SET @CurrentMaxDOP = 1 - END + SET @CurrentMaxDOP = 1 END -- Update statistics? @@ -8881,7 +8878,7 @@ 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 += 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' 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 From 7f9defd042d30f4e602f193e1fc8cc1fb20a3c10 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 23 May 2026 17:35:02 +0200 Subject: [PATCH 007/177] Add files via upload From 50d86e1b859260417352f83f7be268bab58d13b6 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 23 May 2026 17:37:06 +0200 Subject: [PATCH 008/177] 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 0c46223c..a0819099 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: 2026-05-23 17:06:30 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 37b980e2..e3e5f6b4 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 17:06:30 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index ced4bff6..85d631c3 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 17:06:30 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 419fdff6..e09680ab 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 17:06:30 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2216,7 +2216,7 @@ 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 += 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' 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 diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 53a81d5f..ad78d11d 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: 2026-05-23 17:06:30 +Version: 2026-05-23 17:23:48 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 17:06:30 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -484,7 +484,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 17:06:30 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4817,7 +4817,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 17:06:30 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6716,7 +6716,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 17:06:30 //-- + --// Version: 2026-05-23 17:23:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8878,7 +8878,7 @@ 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 += 'Incremental: ' + CASE WHEN @CurrentIsIncremental = 1 THEN 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' 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 From e6b2d2be4cf779676e55fba7381d6ecce08bdf0b Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 23 May 2026 21:27:04 +0200 Subject: [PATCH 009/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 73 ++++++++-------------------------- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 81 ++++++++++---------------------------- 5 files changed, 39 insertions(+), 121 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index a0819099..8ccade5b 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: 2026-05-23 17:23:48 //-- + --// Version: 2026-05-23 21:25:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index e3e5f6b4..d04cb1a1 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 17:23:48 //-- + --// Version: 2026-05-23 21:25:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -108,6 +108,7 @@ BEGIN DECLARE @Parameters nvarchar(max) DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 DECLARE @DirectorySeparator nvarchar(max) DECLARE @Updated bit @@ -281,6 +282,11 @@ BEGIN SET @HostPlatform = 'Windows' END + IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + BEGIN + SET @ContainedAvailabilityGroupListenerConnection = 1 + END + DECLARE @AmazonRDS bit = CASE WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -376,6 +382,9 @@ BEGIN SET @StartMessage = 'Platform: ' + @HostPlatform RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -1519,18 +1528,6 @@ BEGIN 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, [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, [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 @@ -1545,18 +1542,6 @@ BEGIN 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, [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, [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 @CompressionLevelNumeric IS NOT NULL) @@ -1960,12 +1945,6 @@ BEGIN ---------------------------------------------------------------------------------------------------- - 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 <= 0 OR @ModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -2000,12 +1979,6 @@ BEGIN ---------------------------------------------------------------------------------------------------- - 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]) @@ -2014,12 +1987,6 @@ BEGIN ---------------------------------------------------------------------------------------------------- - 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]) @@ -2398,12 +2365,6 @@ 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 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 - END - IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -2863,7 +2824,6 @@ BEGIN END 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 OR @MinDatabaseSizeForDifferentialBackup IS NOT NULL) @@ -2877,18 +2837,17 @@ BEGIN IF @ChangeBackupType = 'Y' BEGIN - IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND @CurrentDatabaseName <> 'master' + IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) BEGIN SET @CurrentBackupType = 'DIFF' END - IF @CurrentBackupType = 'DIFF' AND (@CurrentDatabaseName = 'master' OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @ModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) + IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @ModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) BEGIN SET @CurrentBackupType = 'FULL' END END 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 @@ -2899,7 +2858,7 @@ BEGIN BEGIN SELECT @CurrentDifferentialBaseIsSnapshot = is_snapshot FROM msdb.dbo.backupset - WHERE database_name = @CurrentDatabaseName + WHERE [database_name] = @CurrentDatabaseName AND [type] = 'D' AND checkpoint_lsn = @CurrentDifferentialBaseLSN END @@ -3018,7 +2977,7 @@ 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 EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') + IF @CurrentBackupType IN('DIFF','FULL') BEGIN 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 @@ -3027,7 +2986,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - 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') + IF @CurrentBackupType = 'LOG' 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 @@ -3044,7 +3003,7 @@ BEGIN 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 (@CurrentBackupType IN('DIFF','LOG') AND (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') AND NOT ((@CurrentLogShippingRole = 'PRIMARY' AND @CurrentLogShippingRole IS NOT NULL) AND @CurrentBackupType = 'LOG' AND @ExcludeLogShippedFromLogBackup = 'Y') diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 85d631c3..ec7cb51c 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 17:23:48 //-- + --// Version: 2026-05-23 21:25:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index e09680ab..378d9b76 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 17:23:48 //-- + --// Version: 2026-05-23 21:25:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index ad78d11d..842c63fb 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: 2026-05-23 17:23:48 +Version: 2026-05-23 21:25:44 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 17:23:48 //-- + --// Version: 2026-05-23 21:25:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -484,7 +484,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 17:23:48 //-- + --// Version: 2026-05-23 21:25:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -501,6 +501,7 @@ BEGIN DECLARE @Parameters nvarchar(max) DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 DECLARE @DirectorySeparator nvarchar(max) DECLARE @Updated bit @@ -674,6 +675,11 @@ BEGIN SET @HostPlatform = 'Windows' END + IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + BEGIN + SET @ContainedAvailabilityGroupListenerConnection = 1 + END + DECLARE @AmazonRDS bit = CASE WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -769,6 +775,9 @@ BEGIN SET @StartMessage = 'Platform: ' + @HostPlatform RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -1912,18 +1921,6 @@ BEGIN 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, [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, [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 @@ -1938,18 +1935,6 @@ BEGIN 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, [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, [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 @CompressionLevelNumeric IS NOT NULL) @@ -2353,12 +2338,6 @@ BEGIN ---------------------------------------------------------------------------------------------------- - 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 <= 0 OR @ModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -2393,12 +2372,6 @@ BEGIN ---------------------------------------------------------------------------------------------------- - 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]) @@ -2407,12 +2380,6 @@ BEGIN ---------------------------------------------------------------------------------------------------- - 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]) @@ -2791,12 +2758,6 @@ 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 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 - END - IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -3256,7 +3217,6 @@ BEGIN END 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 OR @MinDatabaseSizeForDifferentialBackup IS NOT NULL) @@ -3270,18 +3230,17 @@ BEGIN IF @ChangeBackupType = 'Y' BEGIN - IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND @CurrentDatabaseName <> 'master' + IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) BEGIN SET @CurrentBackupType = 'DIFF' END - IF @CurrentBackupType = 'DIFF' AND (@CurrentDatabaseName = 'master' OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @ModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) + IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @ModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) BEGIN SET @CurrentBackupType = 'FULL' END END 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 @@ -3292,7 +3251,7 @@ BEGIN BEGIN SELECT @CurrentDifferentialBaseIsSnapshot = is_snapshot FROM msdb.dbo.backupset - WHERE database_name = @CurrentDatabaseName + WHERE [database_name] = @CurrentDatabaseName AND [type] = 'D' AND checkpoint_lsn = @CurrentDifferentialBaseLSN END @@ -3411,7 +3370,7 @@ 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 EXISTS(SELECT * FROM sys.all_columns WHERE object_id = OBJECT_ID('sys.dm_db_file_space_usage') AND name = 'modified_extent_page_count') + IF @CurrentBackupType IN('DIFF','FULL') BEGIN 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 @@ -3420,7 +3379,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - 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') + IF @CurrentBackupType = 'LOG' 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 @@ -3437,7 +3396,7 @@ BEGIN 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 (@CurrentBackupType IN('DIFF','LOG') AND (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') AND NOT ((@CurrentLogShippingRole = 'PRIMARY' AND @CurrentLogShippingRole IS NOT NULL) AND @CurrentBackupType = 'LOG' AND @ExcludeLogShippedFromLogBackup = 'Y') @@ -4817,7 +4776,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 17:23:48 //-- + --// Version: 2026-05-23 21:25:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6716,7 +6675,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 17:23:48 //-- + --// Version: 2026-05-23 21:25:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 3bbb0cb3e0a9d09882fd3b3ecf88ee28470fec29 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 23 May 2026 21:51:05 +0200 Subject: [PATCH 010/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 14 ++++---------- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 22 ++++++++-------------- 5 files changed, 15 insertions(+), 27 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 8ccade5b..ce97db0f 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: 2026-05-23 21:25:44 //-- + --// Version: 2026-05-23 21:50:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index d04cb1a1..8c53c3a2 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 21:25:44 //-- + --// Version: 2026-05-23 21:50:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -272,17 +272,11 @@ BEGIN 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 - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info - END - ELSE - BEGIN - SET @HostPlatform = 'Windows' - END + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) BEGIN SET @ContainedAvailabilityGroupListenerConnection = 1 END diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index ec7cb51c..3e4acc59 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 21:25:44 //-- + --// Version: 2026-05-23 21:50:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 378d9b76..915b1f67 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 21:25:44 //-- + --// Version: 2026-05-23 21:50:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 842c63fb..d98e79b3 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: 2026-05-23 21:25:44 +Version: 2026-05-23 21:50:15 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 21:25:44 //-- + --// Version: 2026-05-23 21:50:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -484,7 +484,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 21:25:44 //-- + --// Version: 2026-05-23 21:50:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -665,17 +665,11 @@ BEGIN 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 - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info - END - ELSE - BEGIN - SET @HostPlatform = 'Windows' - END + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) BEGIN SET @ContainedAvailabilityGroupListenerConnection = 1 END @@ -4776,7 +4770,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 21:25:44 //-- + --// Version: 2026-05-23 21:50:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6675,7 +6669,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 21:25:44 //-- + --// Version: 2026-05-23 21:50:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From c58d86b589a46cfec5d63ebe3494e60edfe3adf7 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 23 May 2026 23:43:37 +0200 Subject: [PATCH 011/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 19 +++++++++------- IndexOptimize.sql | 19 +++++++++------- MaintenanceSolution.sql | 44 ++++++++++++++++++++++---------------- 5 files changed, 49 insertions(+), 37 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index ce97db0f..7e625161 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: 2026-05-23 21:50:15 //-- + --// Version: 2026-05-23 23:42:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 8c53c3a2..5fd96ce8 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 21:50:15 //-- + --// Version: 2026-05-23 23:42:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 3e4acc59..e1c82aaf 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 21:50:15 //-- + --// Version: 2026-05-23 23:42:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -58,6 +58,7 @@ BEGIN DECLARE @Parameters nvarchar(max) DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -182,14 +183,13 @@ BEGIN 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 - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info - END - ELSE + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + + IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) BEGIN - SET @HostPlatform = 'Windows' + SET @ContainedAvailabilityGroupListenerConnection = 1 END DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END @@ -236,6 +236,9 @@ BEGIN SET @StartMessage = 'Platform: ' + @HostPlatform RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 915b1f67..c855e849 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 21:50:15 //-- + --// Version: 2026-05-23 23:42:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -76,6 +76,7 @@ BEGIN DECLARE @Parameters nvarchar(max) DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 DECLARE @PartitionLevelStatistics bit @@ -257,14 +258,13 @@ BEGIN 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 - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info - END - ELSE + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + + IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) BEGIN - SET @HostPlatform = 'Windows' + SET @ContainedAvailabilityGroupListenerConnection = 1 END DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END @@ -324,6 +324,9 @@ BEGIN SET @StartMessage = 'Platform: ' + @HostPlatform RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index d98e79b3..1ee581d1 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: 2026-05-23 21:50:15 +Version: 2026-05-23 23:42:56 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 21:50:15 //-- + --// Version: 2026-05-23 23:42:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -484,7 +484,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 21:50:15 //-- + --// Version: 2026-05-23 23:42:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4770,7 +4770,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 21:50:15 //-- + --// Version: 2026-05-23 23:42:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4788,6 +4788,7 @@ BEGIN DECLARE @Parameters nvarchar(max) DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -4912,14 +4913,13 @@ BEGIN 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 - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info - END - ELSE + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + + IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) BEGIN - SET @HostPlatform = 'Windows' + SET @ContainedAvailabilityGroupListenerConnection = 1 END DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END @@ -4966,6 +4966,9 @@ BEGIN SET @StartMessage = 'Platform: ' + @HostPlatform RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -6669,7 +6672,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 21:50:15 //-- + --// Version: 2026-05-23 23:42:56 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6691,6 +6694,7 @@ BEGIN DECLARE @Parameters nvarchar(max) DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 DECLARE @PartitionLevelStatistics bit @@ -6872,14 +6876,13 @@ BEGIN 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 - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info - END - ELSE + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + + IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) BEGIN - SET @HostPlatform = 'Windows' + SET @ContainedAvailabilityGroupListenerConnection = 1 END DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END @@ -6939,6 +6942,9 @@ BEGIN SET @StartMessage = 'Platform: ' + @HostPlatform RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT From be5ce7e7f2fbf9452e4b7df4e89773b52c02d815 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 24 May 2026 08:39:05 +0200 Subject: [PATCH 012/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 55 +++++++++++--------------------------- 5 files changed, 19 insertions(+), 44 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 7e625161..4894d27a 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: 2026-05-23 23:42:56 //-- + --// Version: 2026-05-24 08:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 5fd96ce8..3fb03dfa 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 23:42:56 //-- + --// Version: 2026-05-24 08:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index e1c82aaf..1101870e 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 23:42:56 //-- + --// Version: 2026-05-24 08:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index c855e849..26bd21aa 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 23:42:56 //-- + --// Version: 2026-05-24 08:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 1ee581d1..007f42df 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: 2026-05-23 23:42:56 +Version: 2026-05-24 08:38:27 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 23:42:56 //-- + --// Version: 2026-05-24 08:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -484,7 +484,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 23:42:56 //-- + --// Version: 2026-05-24 08:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4770,7 +4770,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 23:42:56 //-- + --// Version: 2026-05-24 08:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6672,7 +6672,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-23 23:42:56 //-- + --// Version: 2026-05-24 08:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -9048,7 +9048,6 @@ GO IF (SELECT [Value] FROM #Config WHERE Name = 'CreateJobs') = 'Y' AND SERVERPROPERTY('EngineEdition') NOT IN(4, 5) AND (IS_SRVROLEMEMBER('sysadmin') = 1 OR (EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa')) - AND (SELECT [compatibility_level] FROM sys.databases WHERE [name] = DB_NAME()) >= 90 AND NOT (EXISTS (SELECT * FROM #Config WHERE Name = 'BackupDirectory' AND [Value] IS NOT NULL) AND EXISTS (SELECT * FROM #Config WHERE Name = 'BackupURL' AND [Value] IS NOT NULL)) AND NOT (EXISTS (SELECT * FROM #Config WHERE Name = 'BackupURL' AND [Value] IS NOT NULL) AND EXISTS (SELECT * FROM #Config WHERE Name = 'CleanupTime' AND [Value] IS NOT NULL)) BEGIN @@ -9104,15 +9103,8 @@ BEGIN DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') 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 @HostPlatform = host_platform + FROM sys.dm_os_host_info SELECT @DirectorySeparator = CASE WHEN @HostPlatform = 'Windows' THEN '\' @@ -9124,14 +9116,10 @@ BEGIN SET @TokenStepID = '$' + '(ESCAPE_SQUOTE(STEPID))' SET @TokenDate = '$' + '(ESCAPE_SQUOTE(DATE))' SET @TokenTime = '$' + '(ESCAPE_SQUOTE(TIME))' + SET @TokenJobName = '$' + '(ESCAPE_SQUOTE(JOBNAME))' + SET @TokenStepName = '$' + '(ESCAPE_SQUOTE(STEPNAME))' - IF @Version >= 13 - BEGIN - SET @TokenJobName = '$' + '(ESCAPE_SQUOTE(JOBNAME))' - SET @TokenStepName = '$' + '(ESCAPE_SQUOTE(STEPNAME))' - END - - IF @Version >= 12 AND @HostPlatform = 'Windows' + IF @HostPlatform = 'Windows' BEGIN SET @TokenLogDirectory = '$' + '(ESCAPE_SQUOTE(SQLLOGDIR))' END @@ -9160,15 +9148,8 @@ BEGIN FROM #Config WHERE [Name] = 'DatabaseName' - IF @Version >= 11 - BEGIN - SELECT @LogDirectory = [path] - FROM sys.dm_os_server_diagnostics_log_configurations - END - ELSE - 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 + SELECT @LogDirectory = [path] + FROM sys.dm_os_server_diagnostics_log_configurations IF @OutputFileDirectory IS NOT NULL AND RIGHT(@OutputFileDirectory,1) = @DirectorySeparator BEGIN @@ -9218,13 +9199,13 @@ BEGIN 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 + '''', + 'EXECUTE [dbo].[DatabaseIntegrityCheck]' + CHAR(13) + CHAR(10) + '@Databases = ''SYSTEM_DATABASES'',' + CHAR(13) + CHAR(10) + '@NoInformationalMessages = ''Y'',' + 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'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', + 'EXECUTE [dbo].[DatabaseIntegrityCheck]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + '@NoInformationalMessages = ''Y'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', @DatabaseName, 'DatabaseIntegrityCheck' @@ -9313,18 +9294,12 @@ BEGIN SET @CurrentJobStepCommand = @CurrentCommandTSQL SET @CurrentJobStepDatabaseName = @CurrentDatabaseName END - ELSE IF @CurrentCommandTSQL IS NOT NULL AND @HostPlatform = 'Windows' AND @Version >= 11 + ELSE IF @CurrentCommandTSQL IS NOT NULL AND @HostPlatform = 'Windows' 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' - SET @CurrentJobStepDatabaseName = NULL - END ELSE IF @CurrentCommandCmdExec IS NOT NULL AND @HostPlatform = 'Windows' BEGIN SET @CurrentJobStepSubSystem = 'CMDEXEC' From 0f8af09815bcd12edf2ebbe2d3fc0de5ec9aa034 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 24 May 2026 08:56:36 +0200 Subject: [PATCH 013/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 30 ++++++------------------------ 5 files changed, 10 insertions(+), 28 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 4894d27a..eb4fd125 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: 2026-05-24 08:38:27 //-- + --// Version: 2026-05-24 08:51:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 3fb03dfa..94d66b07 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-24 08:38:27 //-- + --// Version: 2026-05-24 08:51:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 1101870e..9bd06d24 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-24 08:38:27 //-- + --// Version: 2026-05-24 08:51:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 26bd21aa..68ea5850 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-24 08:38:27 //-- + --// Version: 2026-05-24 08:51:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 007f42df..c3a0406e 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: 2026-05-24 08:38:27 +Version: 2026-05-24 08:51:53 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-24 08:38:27 //-- + --// Version: 2026-05-24 08:51:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -484,7 +484,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-24 08:38:27 //-- + --// Version: 2026-05-24 08:51:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4770,7 +4770,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-24 08:38:27 //-- + --// Version: 2026-05-24 08:51:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6672,7 +6672,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-24 08:38:27 //-- + --// Version: 2026-05-24 08:51:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -9276,25 +9276,7 @@ BEGIN 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 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' - SET @CurrentJobStepCommand = @CurrentCommandTSQL - SET @CurrentJobStepDatabaseName = @CurrentDatabaseName - END - ELSE IF @CurrentCommandTSQL IS NOT NULL AND @HostPlatform = 'Windows' + IF @CurrentCommandTSQL IS NOT NULL BEGIN SET @CurrentJobStepSubSystem = 'TSQL' SET @CurrentJobStepCommand = @CurrentCommandTSQL From f5653eda7a9d59baa1e77c286fd89bc61eea419c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 24 May 2026 12:36:59 +0200 Subject: [PATCH 014/177] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 1571725e..83d5ceeb 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ [![forks badge]][forks] [![issues badge]][issues] [![bug report badge]][bug report] +[![SQL Server bug badge]][SQL Server bug] [![feature request badge]][feature request] ## Getting Started @@ -36,6 +37,7 @@ Supported versions: SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, 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%20Report.svg +[SQL Server bug badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/SQL%20Server%20Bug.svg [feature request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Feature%20Request.svg [licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE @@ -43,4 +45,5 @@ Supported versions: SQL Server 2008, SQL Server 2008 R2, SQL Server 2012, 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%3A%22Bug+Report%22 +[SQL Server bug]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3A%22SQL+Server+Bug%22 [feature request]:https://github.com/olahallengren/sql-server-maintenance-solution/issues?q=is%3Aopen+is%3Aissue+label%3A%22Feature+Request%22 From fd85eb34ca9e3fdcb75cf7172f001d89479602be Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 25 May 2026 19:51:32 +0200 Subject: [PATCH 015/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 15 ++++++++------- DatabaseIntegrityCheck.sql | 10 +++++----- IndexOptimize.sql | 8 ++++---- MaintenanceSolution.sql | 37 +++++++++++++++++++------------------ 5 files changed, 37 insertions(+), 35 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index eb4fd125..0dabb6bf 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: 2026-05-24 08:51:53 //-- + --// Version: 2026-05-25 19:42:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 94d66b07..a7320052 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-24 08:51:53 //-- + --// Version: 2026-05-25 19:42:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -516,7 +516,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, @@ -589,7 +589,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF @AvailabilityGroups IS NOT NULL AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -674,7 +674,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 OR SERVERPROPERTY('IsHadrEnabled') = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 @@ -2471,7 +2471,7 @@ BEGIN --// Check Availability Group cluster name //-- ---------------------------------------------------------------------------------------------------- - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @Cluster = NULLIF(cluster_name,'') FROM sys.dm_hadr_cluster @@ -2772,7 +2772,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 @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @CurrentReplicaID = databases.replica_id FROM sys.databases databases @@ -2799,7 +2799,7 @@ BEGIN WHERE group_id = @CurrentAvailabilityGroupID END - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) END @@ -2911,6 +2911,7 @@ BEGIN OR (@CurrentBackupType = 'DIFF' AND @CopyOnly = 'N' AND @Version >= 17) OR (@CurrentBackupType = 'FULL' AND @CopyOnly = 'Y') OR (@CurrentBackupType = 'LOG' AND @CopyOnly = 'N')) + AND SERVERPROPERTY('EngineEdition') IN (3) BEGIN SET @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 END diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 9bd06d24..99881efd 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-24 08:51:53 //-- + --// Version: 2026-05-25 19:42:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -370,7 +370,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, @@ -443,7 +443,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF @AvailabilityGroups IS NOT NULL AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -1369,7 +1369,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @CurrentReplicaID = databases.replica_id FROM sys.databases databases @@ -1391,7 +1391,7 @@ BEGIN WHERE group_id = @CurrentAvailabilityGroupID END - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL AND @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' + IF 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 diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 68ea5850..a4d5e62b 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-24 08:51:53 //-- + --// Version: 2026-05-25 19:42:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -458,7 +458,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, @@ -530,7 +530,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF @AvailabilityGroups IS NOT NULL AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -1462,7 +1462,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @CurrentReplicaID = databases.replica_id FROM sys.databases databases diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index c3a0406e..33547251 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: 2026-05-24 08:51:53 +Version: 2026-05-25 19:42:41 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-24 08:51:53 //-- + --// Version: 2026-05-25 19:42:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -484,7 +484,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-24 08:51:53 //-- + --// Version: 2026-05-25 19:42:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -909,7 +909,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, @@ -982,7 +982,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF @AvailabilityGroups IS NOT NULL AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -1067,7 +1067,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 OR SERVERPROPERTY('IsHadrEnabled') = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 @@ -2864,7 +2864,7 @@ BEGIN --// Check Availability Group cluster name //-- ---------------------------------------------------------------------------------------------------- - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @Cluster = NULLIF(cluster_name,'') FROM sys.dm_hadr_cluster @@ -3165,7 +3165,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 @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @CurrentReplicaID = databases.replica_id FROM sys.databases databases @@ -3192,7 +3192,7 @@ BEGIN WHERE group_id = @CurrentAvailabilityGroupID END - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) END @@ -3304,6 +3304,7 @@ BEGIN OR (@CurrentBackupType = 'DIFF' AND @CopyOnly = 'N' AND @Version >= 17) OR (@CurrentBackupType = 'FULL' AND @CopyOnly = 'Y') OR (@CurrentBackupType = 'LOG' AND @CopyOnly = 'N')) + AND SERVERPROPERTY('EngineEdition') IN (3) BEGIN SET @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 END @@ -4770,7 +4771,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-24 08:51:53 //-- + --// Version: 2026-05-25 19:42:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5100,7 +5101,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, @@ -5173,7 +5174,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF @AvailabilityGroups IS NOT NULL AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -6099,7 +6100,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @CurrentReplicaID = databases.replica_id FROM sys.databases databases @@ -6121,7 +6122,7 @@ BEGIN WHERE group_id = @CurrentAvailabilityGroupID END - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL AND @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' + IF 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 @@ -6672,7 +6673,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-24 08:51:53 //-- + --// Version: 2026-05-25 19:42:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7076,7 +7077,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) SELECT name AS AvailabilityGroupName, @@ -7148,7 +7149,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF @AvailabilityGroups IS NOT NULL AND SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -8080,7 +8081,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - IF @Version >= 11 AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN SELECT @CurrentReplicaID = databases.replica_id FROM sys.databases databases From 2801b66bb419085d52349f38ffcd082e6481fa2d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 25 May 2026 19:58:39 +0200 Subject: [PATCH 016/177] 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 0dabb6bf..dff6b535 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: 2026-05-25 19:42:41 //-- + --// Version: 2026-05-25 19:57:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index a7320052..63bcde83 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-25 19:42:41 //-- + --// Version: 2026-05-25 19:57:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2911,7 +2911,7 @@ BEGIN OR (@CurrentBackupType = 'DIFF' AND @CopyOnly = 'N' AND @Version >= 17) OR (@CurrentBackupType = 'FULL' AND @CopyOnly = 'Y') OR (@CurrentBackupType = 'LOG' AND @CopyOnly = 'N')) - AND SERVERPROPERTY('EngineEdition') IN (3) + AND SERVERPROPERTY('EngineEdition') = 3 BEGIN SET @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 END diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 99881efd..d4aa14a2 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-25 19:42:41 //-- + --// Version: 2026-05-25 19:57:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index a4d5e62b..a7e4563f 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-25 19:42:41 //-- + --// Version: 2026-05-25 19:57:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 33547251..33d3b3cd 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: 2026-05-25 19:42:41 +Version: 2026-05-25 19:57:22 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-25 19:42:41 //-- + --// Version: 2026-05-25 19:57:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -484,7 +484,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-25 19:42:41 //-- + --// Version: 2026-05-25 19:57:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3304,7 +3304,7 @@ BEGIN OR (@CurrentBackupType = 'DIFF' AND @CopyOnly = 'N' AND @Version >= 17) OR (@CurrentBackupType = 'FULL' AND @CopyOnly = 'Y') OR (@CurrentBackupType = 'LOG' AND @CopyOnly = 'N')) - AND SERVERPROPERTY('EngineEdition') IN (3) + AND SERVERPROPERTY('EngineEdition') = 3 BEGIN SET @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 END @@ -4771,7 +4771,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-25 19:42:41 //-- + --// Version: 2026-05-25 19:57:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6673,7 +6673,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-25 19:42:41 //-- + --// Version: 2026-05-25 19:57:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 2b7b74ba9a4fa35944e2be1204bfa5b8603aefae Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 28 May 2026 01:30:57 +0200 Subject: [PATCH 017/177] Add files via upload --- CommandExecute.sql | 16 +- DatabaseBackup.sql | 260 +++++++++++-------- DatabaseIntegrityCheck.sql | 99 ++++--- IndexOptimize.sql | 141 ++++++---- MaintenanceSolution.sql | 518 ++++++++++++++++++++++--------------- 5 files changed, 613 insertions(+), 421 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index dff6b535..10a7a5c6 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: 2026-05-25 19:57:22 //-- + --// Version: 2026-05-28 01:22:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -74,12 +74,6 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- - IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE [name] = DB_NAME()) >= 90 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The database ' + QUOTENAME(DB_NAME()) + ' 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, [State]) @@ -195,7 +189,7 @@ BEGIN SET @StartTime = SYSDATETIME() - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Database context: ' + QUOTENAME(@DatabaseContext) @@ -238,7 +232,7 @@ BEGIN SET @Error = ERROR_NUMBER() SET @ErrorMessageOriginal = ERROR_MESSAGE() - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205, 1222, 5245) THEN @LockMessageSeverity ELSE ERROR_SEVERITY() END RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT @@ -263,10 +257,10 @@ BEGIN 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(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) + SET @EndMessage = 'Duration: ' + CASE WHEN (DATEDIFF(SECOND,@StartTime,@EndTime) / (24 * 3600)) > 0 THEN CAST((DATEDIFF(SECOND,@StartTime,@EndTime) / (24 * 3600)) AS nvarchar(max)) + '.' ELSE '' END + CONVERT(nvarchar(max),DATEADD(SECOND,DATEDIFF(SECOND,@StartTime,@EndTime),'1900-01-01'),108) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTime,120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar(max),@EndTime,120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 63bcde83..24b8312d 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-25 19:57:22 //-- + --// Version: 2026-05-28 01:22:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -157,13 +157,17 @@ BEGIN DECLARE @CurrentDate datetime2 DECLARE @CurrentDateUTC datetime2 DECLARE @CurrentCleanupDate datetime2 - DECLARE @CurrentReplicaID uniqueidentifier + DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState nvarchar(max) DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) + DECLARE @CurrentDistributedAvailabilityGroupID uniqueidentifier + DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) + DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier + DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) DECLARE @CurrentIsPreferredBackupReplica bit DECLARE @CurrentDatabaseMirroringRole nvarchar(max) DECLARE @CurrentLogShippingRole nvarchar(max) @@ -291,7 +295,7 @@ BEGIN 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 += ', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar(max)),'NULL') SET @Parameters += ', @CleanupMode = ' + ISNULL('''' + REPLACE(@CleanupMode,'''','''''') + '''','NULL') SET @Parameters += ', @Compress = ' + ISNULL('''' + REPLACE(@Compress,'''','''''') + '''','NULL') SET @Parameters += ', @CompressionAlgorithm = ' + ISNULL('''' + REPLACE(@CompressionAlgorithm,'''','''''') + '''','NULL') @@ -300,17 +304,17 @@ BEGIN 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 += ', @MinBackupSizeForMultipleFiles = ' + ISNULL(CAST(@MinBackupSizeForMultipleFiles AS nvarchar),'NULL') - SET @Parameters += ', @MaxFileSize = ' + ISNULL(CAST(@MaxFileSize AS nvarchar),'NULL') - SET @Parameters += ', @CompressionLevelNumeric = ' + ISNULL(CAST(@CompressionLevelNumeric AS nvarchar),'NULL') + SET @Parameters += ', @BlockSize = ' + ISNULL(CAST(@BlockSize AS nvarchar(max)),'NULL') + SET @Parameters += ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar(max)),'NULL') + SET @Parameters += ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar(max)),'NULL') + SET @Parameters += ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar(max)),'NULL') + SET @Parameters += ', @MinBackupSizeForMultipleFiles = ' + ISNULL(CAST(@MinBackupSizeForMultipleFiles AS nvarchar(max)),'NULL') + SET @Parameters += ', @MaxFileSize = ' + ISNULL(CAST(@MaxFileSize AS nvarchar(max)),'NULL') + SET @Parameters += ', @CompressionLevelNumeric = ' + ISNULL(CAST(@CompressionLevelNumeric AS nvarchar(max)),'NULL') SET @Parameters += ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL') SET @Parameters += ', @BackupSetName = ' + ISNULL('''' + REPLACE(@BackupSetName,'''','''''') + '''','NULL') - SET @Parameters += ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar),'NULL') - SET @Parameters += ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar),'NULL') + SET @Parameters += ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar(max)),'NULL') + SET @Parameters += ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar(max)),'NULL') SET @Parameters += ', @Encrypt = ' + ISNULL('''' + REPLACE(@Encrypt,'''','''''') + '''','NULL') SET @Parameters += ', @EncryptionAlgorithm = ' + ISNULL('''' + REPLACE(@EncryptionAlgorithm,'''','''''') + '''','NULL') SET @Parameters += ', @ServerCertificate = ' + ISNULL('''' + REPLACE(@ServerCertificate,'''','''''') + '''','NULL') @@ -322,16 +326,16 @@ BEGIN 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 += ', @MirrorCleanupTime = ' + ISNULL(CAST(@MirrorCleanupTime AS nvarchar(max)),'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 += ', @MinDatabaseSizeForDifferentialBackup = ' + ISNULL('''' + REPLACE(@MinDatabaseSizeForDifferentialBackup,'''','''''') + '''','NULL') - SET @Parameters += ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar),'NULL') - SET @Parameters += ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar),'NULL') + SET @Parameters += ', @ModificationLevel = ' + ISNULL(CAST(@ModificationLevel AS nvarchar(max)),'NULL') + SET @Parameters += ', @MinDatabaseSizeForDifferentialBackup = ' + ISNULL(CAST(@MinDatabaseSizeForDifferentialBackup AS nvarchar(max)),'NULL') + SET @Parameters += ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar(max)),'NULL') + SET @Parameters += ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar(max)),'NULL') SET @Parameters += ', @DataDomainBoostHost = ' + ISNULL('''' + REPLACE(@DataDomainBoostHost,'''','''''') + '''','NULL') SET @Parameters += ', @DataDomainBoostUser = ' + ISNULL('''' + REPLACE(@DataDomainBoostUser,'''','''''') + '''','NULL') SET @Parameters += ', @DataDomainBoostDevicePath = ' + ISNULL('''' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '''','NULL') @@ -352,16 +356,16 @@ BEGIN SET @Parameters += ', @ExcludeLogShippedFromLogBackup = ' + ISNULL('''' + REPLACE(@ExcludeLogShippedFromLogBackup,'''','''''') + '''','NULL') SET @Parameters += ', @DirectoryCheck = ' + ISNULL('''' + REPLACE(@DirectoryCheck,'''','''''') + '''','NULL') SET @Parameters += ', @BackupOptions = ' + ISNULL('''' + REPLACE(@BackupOptions,'''','''''') + '''','NULL') - SET @Parameters += ', @Stats = ' + ISNULL(CAST(@Stats AS nvarchar),'NULL') - SET @Parameters += ', @ExpireDate = ' + ISNULL('''' + CONVERT(nvarchar, @ExpireDate, 21) + '''','NULL') - SET @Parameters += ', @RetainDays = ' + ISNULL(CAST(@RetainDays AS nvarchar),'NULL') + SET @Parameters += ', @Stats = ' + ISNULL(CAST(@Stats AS nvarchar(max)),'NULL') + SET @Parameters += ', @ExpireDate = ' + ISNULL('''' + CONVERT(nvarchar(max), @ExpireDate, 21) + '''','NULL') + SET @Parameters += ', @RetainDays = ' + ISNULL(CAST(@RetainDays AS nvarchar(max)),'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') SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) @@ -397,12 +401,6 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- - IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE [name] = DB_NAME()) >= 90 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The database ' + QUOTENAME(DB_NAME()) + ' 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, [State]) @@ -783,8 +781,8 @@ BEGIN SET @MirrorDirectory = REPLACE(@MirrorDirectory, CHAR(10), '') SET @MirrorDirectory = REPLACE(@MirrorDirectory, CHAR(13), '') - WHILE CHARINDEX(', ',@MirrorDirectory) > 0 SET @MirrorDirectory = REPLACE(@MirrorDirectory,', ',',') - WHILE CHARINDEX(' ,',@MirrorDirectory) > 0 SET @MirrorDirectory = REPLACE(@MirrorDirectory,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @MirrorDirectory) > 0 SET @MirrorDirectory = REPLACE(@MirrorDirectory, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @MirrorDirectory) > 0 SET @MirrorDirectory = REPLACE(@MirrorDirectory, ' ' + @StringDelimiter, @StringDelimiter) SET @MirrorDirectory = LTRIM(RTRIM(@MirrorDirectory)); @@ -2661,7 +2659,7 @@ BEGIN BEGIN ROLLBACK TRANSACTION END - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() @@ -2730,7 +2728,7 @@ BEGIN SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' BEGIN - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar(max),SYSDATETIME(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) @@ -2774,23 +2772,23 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @CurrentReplicaID = databases.replica_id + SELECT @CurrentAvailabilityGroupReplicaID = 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 @CurrentAvailabilityGroupID = group_id FROM sys.availability_replicas - WHERE replica_id = @CurrentReplicaID + WHERE replica_id = @CurrentAvailabilityGroupReplicaID SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states - WHERE replica_id = @CurrentReplicaID + WHERE replica_id = @CurrentAvailabilityGroupReplicaID SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc FROM sys.dm_hadr_database_replica_states - WHERE replica_id = @CurrentReplicaID + WHERE replica_id = @CurrentAvailabilityGroupReplicaID AND database_id = DB_ID(@CurrentDatabaseName) SELECT @CurrentAvailabilityGroup = [name], @@ -2804,6 +2802,22 @@ BEGIN SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) END + IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SELECT @CurrentDistributedAvailabilityGroupID = availability_groups.group_id, + @CurrentDistributedAvailabilityGroup = availability_groups.[name], + @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id + FROM sys.availability_groups availability_groups + INNER JOIN sys.availability_replicas availability_replicas ON availability_groups.group_id = availability_replicas.group_id + INNER JOIN sys.availability_groups availability_groups_local ON availability_replicas.replica_server_name = availability_groups_local.[name] + WHERE availability_groups.is_distributed = 1 + AND availability_groups_local.group_id = @CurrentAvailabilityGroupID + + SELECT @CurrentDistributedAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc + FROM sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states + WHERE dm_hadr_availability_replica_states.replica_id = @CurrentDistributedAvailabilityGroupReplicaID + END + SELECT @CurrentDifferentialBaseLSN = differential_base_lsn FROM sys.master_files WHERE database_id = DB_ID(@CurrentDatabaseName) @@ -2819,8 +2833,8 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentInStandby = 1) 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 OR @MinDatabaseSizeForDifferentialBackup IS NOT NULL) + AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) + AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) BEGIN SET @CurrentCommand = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' @@ -2948,6 +2962,21 @@ BEGIN END END + IF @CurrentDistributedAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Distributed availability group: ' + ISNULL(@CurrentDistributedAvailabilityGroup,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Distributed availability group role: ' + ISNULL(@CurrentDistributedAvailabilityGroupRole,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Replica role in distributed availability group: ' + CASE WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Global primary' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Forwarder' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in secondary availability group' + WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in primary availability group' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + IF @CurrentDatabaseMirroringRole IS NOT NULL BEGIN SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole @@ -2960,7 +2989,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Differential base LSN: ' + ISNULL(CAST(@CurrentDifferentialBaseLSN AS nvarchar),'N/A') + SET @DatabaseMessage = 'Differential base LSN: ' + ISNULL(CAST(@CurrentDifferentialBaseLSN AS nvarchar(max)),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentBackupType = 'DIFF' OR @CurrentDifferentialBaseIsSnapshot IS NOT NULL @@ -2969,15 +2998,15 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') + SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar(max)),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentBackupType IN('DIFF','FULL') BEGIN - SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar) + ' (' + CAST(@CurrentAllocatedExtentPageCount * 1. * 8 / 1024 AS nvarchar) + ' MB)','N/A') + SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar(max)) + ' (' + CAST(@CurrentAllocatedExtentPageCount * 1. * 8 / 1024 AS nvarchar(max)) + ' MB)','N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Modified extent page count: ' + ISNULL(CAST(@CurrentModifiedExtentPageCount AS nvarchar) + ' (' + CAST(@CurrentModifiedExtentPageCount * 1. * 8 / 1024 AS nvarchar) + ' MB)','N/A') + SET @DatabaseMessage = 'Modified extent page count: ' + ISNULL(CAST(@CurrentModifiedExtentPageCount AS nvarchar(max)) + ' (' + CAST(@CurrentModifiedExtentPageCount * 1. * 8 / 1024 AS nvarchar(max)) + ' MB)','N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END @@ -2986,7 +3015,7 @@ 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 - SET @DatabaseMessage = 'Log size since last log backup (MB): ' + ISNULL(CAST(@CurrentLogSizeSinceLastLogBackup AS nvarchar),'N/A') + SET @DatabaseMessage = 'Log size since last log backup (MB): ' + ISNULL(CAST(@CurrentLogSizeSinceLastLogBackup AS nvarchar(max)),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END @@ -3001,6 +3030,7 @@ BEGIN AND NOT (@CurrentBackupType IN('DIFF','LOG') AND (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') + AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole = 'SECONDARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) 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') @@ -3205,18 +3235,18 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{CopyOnly}','COPY_ONLY') SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ISNULL(@Description,''),'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupSetName}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ISNULL(@BackupSetName,''),'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Year}',CAST(DATEPART(YEAR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Year}',CAST(DATEPART(YEAR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max))) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Weekday}',DATENAME(WEEKDAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),3)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) 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))) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),3)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),6)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4))) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3))) END IF @DirectoryStructureCase IS NOT NULL @@ -3369,20 +3399,20 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{CopyOnly}','COPY_ONLY') SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ISNULL(@Description,''),'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{BackupSetName}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ISNULL(@BackupSetName,''),'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Year}',CAST(DATEPART(YEAR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Year}',CAST(DATEPART(YEAR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max))) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Weekday}',DATENAME(WEEKDAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),3)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),6)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),3)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),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))) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4))) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3))) SELECT @CurrentMaxFilePathLength = CASE WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) @@ -3420,7 +3450,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) END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles >= 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) END) IF @CurrentDirectoryPath = 'NUL' BEGIN @@ -3457,7 +3487,7 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) AND Mirror = 1 - 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(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -3487,7 +3517,7 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs 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(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -3513,11 +3543,11 @@ BEGIN SELECT @CurrentDirectoryPath = DirectoryPath FROM @CurrentURLs - WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + 1 - AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 1) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 1) AND Mirror = 1 - 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(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -3566,7 +3596,7 @@ BEGIN 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)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_create_subdir N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''' IF @ReturnCode <> 0 OR @ReturnCode IS NULL 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 @@ -3657,7 +3687,7 @@ BEGIN 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)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' @@ -3666,7 +3696,7 @@ BEGIN 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)' + 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(max)) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -3675,7 +3705,7 @@ BEGIN 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)' + 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(max)) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' @@ -3684,7 +3714,7 @@ BEGIN SET @CurrentCommandType = 'xp_ss_delete' - 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)' + 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(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -3770,20 +3800,20 @@ BEGIN 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 @BlockSize IS NOT NULL SET @CurrentCommand += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar(max)) + IF @BufferCount IS NOT NULL SET @CurrentCommand += ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar(max)) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar(max)) IF @Description IS NOT NULL SET @CurrentCommand += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' IF @BackupSetName IS NOT NULL SET @CurrentCommand += ', NAME = N''' + REPLACE(@BackupSetName,'''','''''') + '''' - IF @Stats IS NOT NULL SET @CurrentCommand += ', STATS = ' + CAST(@Stats AS nvarchar) + IF @Stats IS NOT NULL SET @CurrentCommand += ', STATS = ' + CAST(@Stats AS nvarchar(max)) IF @BackupOptions IS NOT NULL SET @CurrentCommand += ', BACKUP_OPTIONS = N''' + REPLACE(@BackupOptions,'''','''''') + '''' 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,'''','''''') + '''' - IF @ExpireDate IS NOT NULL SET @CurrentCommand += ', EXPIREDATE = ''' + CONVERT(nvarchar, @ExpireDate, 21) + '''' - IF @RetainDays IS NOT NULL SET @CurrentCommand += ', RETAINDAYS = ' + CAST(@RetainDays AS nvarchar) + IF @ExpireDate IS NOT NULL SET @CurrentCommand += ', EXPIREDATE = ''' + CONVERT(nvarchar(max), @ExpireDate, 21) + '''' + IF @RetainDays IS NOT NULL SET @CurrentCommand += ', RETAINDAYS = ' + CAST(@RetainDays AS nvarchar(max)) END IF @BackupSoftware = 'LITESPEED' @@ -3819,21 +3849,21 @@ BEGIN 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) + IF @BlockSize IS NOT NULL SET @CurrentCommand += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar(max)) SET @CurrentCommand += '''' IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand += ', @read_write_filegroups = 1' - IF @CompressionLevelNumeric IS NOT NULL SET @CurrentCommand += ', @compressionlevel = ' + CAST(@CompressionLevelNumeric AS nvarchar) + IF @CompressionLevelNumeric IS NOT NULL SET @CurrentCommand += ', @compressionlevel = ' + CAST(@CompressionLevelNumeric AS nvarchar(max)) 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 @BufferCount IS NOT NULL SET @CurrentCommand += ', @buffercount = ' + CAST(@BufferCount AS nvarchar(max)) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand += ', @maxtransfersize = ' + CAST(@CurrentMaxTransferSize AS nvarchar(max)) + IF @Threads IS NOT NULL SET @CurrentCommand += ', @threads = ' + CAST(@Threads AS nvarchar(max)) 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 @Throttle IS NOT NULL SET @CurrentCommand += ', @throttle = ' + CAST(@Throttle AS nvarchar(max)) IF @Description IS NOT NULL SET @CurrentCommand += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' IF @ObjectLevelRecoveryMap = 'Y' SET @CurrentCommand += ', @olrmap = 1' - IF @ExpireDate IS NOT NULL SET @CurrentCommand += ', @expiration = ''' + CONVERT(nvarchar, @ExpireDate, 21) + '''' - IF @RetainDays IS NOT NULL SET @CurrentCommand += ', @retaindays = ' + CAST(@RetainDays AS nvarchar) + IF @ExpireDate IS NOT NULL SET @CurrentCommand += ', @expiration = ''' + CONVERT(nvarchar(max), @ExpireDate, 21) + '''' + IF @RetainDays IS NOT NULL SET @CurrentCommand += ', @retaindays = ' + CAST(@RetainDays AS nvarchar(max)) IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand += ', @cryptlevel = ' + CASE WHEN @EncryptionAlgorithm = 'RC2_40' THEN '0' @@ -3848,7 +3878,7 @@ BEGIN END IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error performing LiteSpeed backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing LiteSpeed backup.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -3885,9 +3915,9 @@ BEGIN IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand += ', NORECOVERY' IF @Init = 'Y' SET @CurrentCommand += ', INIT' IF @Format = 'Y' SET @CurrentCommand += ', FORMAT' - IF @CompressionLevelNumeric IS NOT NULL SET @CurrentCommand += ', COMPRESSION = ' + CAST(@CompressionLevelNumeric 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 @CompressionLevelNumeric IS NOT NULL SET @CurrentCommand += ', COMPRESSION = ' + CAST(@CompressionLevelNumeric AS nvarchar(max)) + IF @Threads IS NOT NULL SET @CurrentCommand += ', THREADCOUNT = ' + CAST(@Threads AS nvarchar(max)) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar(max)) IF @Description IS NOT NULL SET @CurrentCommand += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand += ', KEYSIZE = ' + CASE @@ -3896,7 +3926,7 @@ BEGIN END 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)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand,'''','''''') + '"''' + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing SQLBackup backup.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' @@ -3929,8 +3959,8 @@ BEGIN 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 @CompressionLevelNumeric IS NOT NULL SET @CurrentCommand += ', @compressionlevel = ' + CAST(@CompressionLevelNumeric AS nvarchar) - IF @Threads IS NOT NULL SET @CurrentCommand += ', @threads = ' + CAST(@Threads AS nvarchar) + IF @CompressionLevelNumeric IS NOT NULL SET @CurrentCommand += ', @compressionlevel = ' + CAST(@CompressionLevelNumeric AS nvarchar(max)) + IF @Threads IS NOT NULL SET @CurrentCommand += ', @threads = ' + CAST(@Threads AS nvarchar(max)) IF @Init = 'Y' SET @CurrentCommand += ', @overwrite = 1' IF @Description IS NOT NULL SET @CurrentCommand += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' @@ -3940,7 +3970,7 @@ BEGIN END + '''' IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptedbackuppassword = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' @@ -3951,7 +3981,7 @@ BEGIN SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.emc_run_backup ''' - SET @CurrentCommand += ' -c ' + CASE WHEN @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar) END + SET @CurrentCommand += ' -c ' + CASE WHEN @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)) END SET @CurrentCommand += ' -l ' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'full' @@ -3961,15 +3991,15 @@ BEGIN IF @NoRecovery = 'Y' SET @CurrentCommand += ' -H' - 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 @CleanupTime IS NOT NULL SET @CurrentCommand += ' -y +' + CAST(@CleanupTime/24 + CASE WHEN @CleanupTime%24 > 0 THEN 1 ELSE 0 END AS nvarchar(max)) + 'd' IF @Checksum = 'Y' SET @CurrentCommand += ' -k' - SET @CurrentCommand += ' -S ' + CAST(@CurrentNumberOfFiles AS nvarchar) + SET @CurrentCommand += ' -S ' + CAST(@CurrentNumberOfFiles AS nvarchar(max)) IF @Description IS NOT NULL SET @CurrentCommand += ' -b "' + REPLACE(@Description,'''','''''') + '"' - IF @BufferCount IS NOT NULL SET @CurrentCommand += ' -O "BUFFERCOUNT=' + CAST(@BufferCount AS nvarchar) + '"' + IF @BufferCount IS NOT NULL SET @CurrentCommand += ' -O "BUFFERCOUNT=' + CAST(@BufferCount AS nvarchar(max)) + '"' IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand += ' -O "READ_WRITE_FILEGROUPS"' @@ -3983,12 +4013,12 @@ BEGIN IF @BackupSetName IS NOT NULL SET @CurrentCommand += ' -N "' + REPLACE(@BackupSetName,'''','''''') + '"' IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand += ' "MSSQL' - IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand += ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar) + IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand += ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max)) SET @CurrentCommand += ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' SET @CurrentCommand += '''' - SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' END EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -4030,7 +4060,7 @@ BEGIN SET @CurrentCommand += ' WITH ' IF @Checksum = 'Y' SET @CurrentCommand += 'CHECKSUM' IF @Checksum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' - IF @Stats IS NOT NULL SET @CurrentCommand += ', STATS = ' + CAST(@Stats AS nvarchar) + IF @Stats IS NOT NULL SET @CurrentCommand += ', STATS = ' + CAST(@Stats AS nvarchar(max)) IF @BackupOptions IS NOT NULL SET @CurrentCommand += ', RESTORE_OPTIONS = N''' + REPLACE(@BackupOptions,'''','''''') + '''' IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand += ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' END @@ -4054,7 +4084,7 @@ BEGIN SET @CurrentCommand += '''' IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying LiteSpeed backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error verifying LiteSpeed backup.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -4075,7 +4105,7 @@ BEGIN IF @Checksum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' 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 verifying SQLBackup backup.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand,'''','''''') + '"''' + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error verifying SQLBackup backup.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' @@ -4096,7 +4126,7 @@ BEGIN WITHIN GROUP (ORDER BY RowNumber ASC) FROM CurrentFiles - SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' END EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -4179,7 +4209,7 @@ BEGIN 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)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' @@ -4188,7 +4218,7 @@ BEGIN 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)' + 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(max)) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -4197,7 +4227,7 @@ BEGIN 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)' + 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(max)) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' @@ -4206,7 +4236,7 @@ BEGIN SET @CurrentCommandType = 'xp_ss_delete' - 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)' + 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(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -4286,7 +4316,7 @@ BEGIN SET @CurrentDate = NULL SET @CurrentDateUTC = NULL SET @CurrentCleanupDate = NULL - SET @CurrentReplicaID = NULL + SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL @@ -4294,6 +4324,10 @@ BEGIN SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL SET @CurrentIsPreferredBackupReplica = NULL + SET @CurrentDistributedAvailabilityGroupID = NULL + SET @CurrentDistributedAvailabilityGroup = NULL + SET @CurrentDistributedAvailabilityGroupReplicaID = NULL + SET @CurrentDistributedAvailabilityGroupRole = NULL SET @CurrentDatabaseMirroringRole = NULL SET @CurrentLogShippingRole = NULL SET @CurrentBackupOperationSupportedOnSecondaryReplicas = NULL @@ -4322,7 +4356,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- Logging: - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar(max),SYSDATETIME(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index d4aa14a2..719ffb38 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-25 19:57:22 //-- + --// Version: 2026-05-28 01:22:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -74,13 +74,17 @@ BEGIN DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) - DECLARE @CurrentReplicaID uniqueidentifier + DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) DECLARE @CurrentSecondaryRoleAllowConnections nvarchar(max) DECLARE @CurrentIsPreferredBackupReplica bit + DECLARE @CurrentDistributedAvailabilityGroupID uniqueidentifier + DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) + DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier + DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) DECLARE @CurrentDatabaseMirroringRole nvarchar(max) DECLARE @CurrentFGID int @@ -208,20 +212,20 @@ BEGIN 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 += ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar(max)),'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 += ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar(max)),'NULL') + SET @Parameters += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar(max)),'NULL') + SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar(max)),'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') SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) @@ -257,12 +261,6 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- - IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE [name] = DB_NAME()) >= 90 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The database ' + QUOTENAME(DB_NAME()) + ' 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, [State]) @@ -1270,7 +1268,7 @@ BEGIN BEGIN ROLLBACK TRANSACTION END - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() @@ -1337,7 +1335,7 @@ BEGIN SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' BEGIN - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar(max),SYSDATETIME(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) @@ -1371,7 +1369,7 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @CurrentReplicaID = databases.replica_id + SELECT @CurrentAvailabilityGroupReplicaID = 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 @@ -1379,11 +1377,11 @@ BEGIN SELECT @CurrentAvailabilityGroupID = group_id, @CurrentSecondaryRoleAllowConnections = secondary_role_allow_connections_desc FROM sys.availability_replicas - WHERE replica_id = @CurrentReplicaID + WHERE replica_id = @CurrentAvailabilityGroupReplicaID SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states - WHERE replica_id = @CurrentReplicaID + WHERE replica_id = @CurrentAvailabilityGroupReplicaID SELECT @CurrentAvailabilityGroup = [name], @CurrentAvailabilityGroupBackupPreference = UPPER(automated_backup_preference_desc) @@ -1396,6 +1394,22 @@ BEGIN SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) END + IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SELECT @CurrentDistributedAvailabilityGroupID = availability_groups.group_id, + @CurrentDistributedAvailabilityGroup = availability_groups.[name], + @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id + FROM sys.availability_groups availability_groups + INNER JOIN sys.availability_replicas availability_replicas ON availability_groups.group_id = availability_replicas.group_id + INNER JOIN sys.availability_groups availability_groups_local ON availability_replicas.replica_server_name = availability_groups_local.[name] + WHERE availability_groups.is_distributed = 1 + AND availability_groups_local.group_id = @CurrentAvailabilityGroupID + + SELECT @CurrentDistributedAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc + FROM sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states + WHERE dm_hadr_availability_replica_states.replica_id = @CurrentDistributedAvailabilityGroupReplicaID + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) @@ -1428,6 +1442,21 @@ BEGIN END END + IF @CurrentDistributedAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Distributed availability group: ' + ISNULL(@CurrentDistributedAvailabilityGroup,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Distributed availability group role: ' + ISNULL(@CurrentDistributedAvailabilityGroupRole,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Replica role in distributed availability group: ' + CASE WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Global primary' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Forwarder' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in secondary availability group' + WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in primary availability group' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + IF @CurrentDatabaseMirroringRole IS NOT NULL BEGIN SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole @@ -1453,7 +1482,7 @@ BEGIN SET @CurrentCommandType = 'DBCC_CHECKDB' SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'DBCC CHECKDB (' + QUOTENAME(@CurrentDatabaseName) IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' SET @CurrentCommand += ') WITH ALL_ERRORMSGS' @@ -1462,7 +1491,7 @@ BEGIN IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand += ', EXTENDED_LOGICAL_CHECKS' IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ', NO_INFOMSGS' IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar(max)) EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -1555,7 +1584,7 @@ BEGIN -- Does the filegroup exist? SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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 @@ -1564,7 +1593,7 @@ 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 + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @@ -1582,14 +1611,14 @@ BEGIN SET @CurrentCommandType = 'DBCC_CHECKFILEGROUP' SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' SET @CurrentCommand += ') WITH ALL_ERRORMSGS' IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ', NO_INFOMSGS' IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar(max)) EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -1623,7 +1652,7 @@ BEGIN SET @CurrentCommandType = 'DBCC_CHECKALLOC' SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'DBCC CHECKALLOC (' + QUOTENAME(@CurrentDatabaseName) SET @CurrentCommand += ') WITH ALL_ERRORMSGS' IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ', NO_INFOMSGS' @@ -1724,7 +1753,7 @@ BEGIN -- Does the object exist? SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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 @@ -1733,7 +1762,7 @@ 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 + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @@ -1751,7 +1780,7 @@ BEGIN SET @CurrentCommandType = 'DBCC_CHECKTABLE' SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'DBCC CHECKTABLE (N' + QUOTENAME(QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName),'''') IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' SET @CurrentCommand += ') WITH ALL_ERRORMSGS' @@ -1760,7 +1789,7 @@ BEGIN IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand += ', EXTENDED_LOGICAL_CHECKS' IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ', NO_INFOMSGS' IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar(max)) 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 @@ -1790,14 +1819,14 @@ BEGIN END -- Check catalog - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') AND @CurrentAvailabilityGroupRole = 'PRIMARY' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentDatabaseContext = CASE WHEN SERVERPROPERTY('EngineEdition') = 5 THEN @CurrentDatabaseName ELSE 'master' END SET @CurrentCommandType = 'DBCC_CHECKCATALOG' SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) SET @CurrentCommand += ')' IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ' WITH NO_INFOMSGS' @@ -1847,13 +1876,17 @@ BEGIN SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL - SET @CurrentReplicaID = NULL + SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL SET @CurrentSecondaryRoleAllowConnections = NULL SET @CurrentIsPreferredBackupReplica = NULL + SET @CurrentDistributedAvailabilityGroupID = NULL + SET @CurrentDistributedAvailabilityGroup = NULL + SET @CurrentDistributedAvailabilityGroupReplicaID = NULL + SET @CurrentDistributedAvailabilityGroupRole = NULL SET @CurrentDatabaseMirroringRole = NULL SET @CurrentDatabaseContext = NULL @@ -1871,7 +1904,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- Logging: - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar(max),SYSDATETIME(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT diff --git a/IndexOptimize.sql b/IndexOptimize.sql index a7e4563f..b2729962 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-25 19:57:22 //-- + --// Version: 2026-05-28 01:22:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -95,10 +95,14 @@ BEGIN DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) - DECLARE @CurrentReplicaID uniqueidentifier + DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) + DECLARE @CurrentDistributedAvailabilityGroupID uniqueidentifier + DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) + DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier + DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) DECLARE @CurrentDatabaseMirroringRole nvarchar(max) DECLARE @CurrentDatabaseContext nvarchar(max) @@ -277,31 +281,31 @@ BEGIN 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 += ', @FragmentationLevel1 = ' + ISNULL(CAST(@FragmentationLevel1 AS nvarchar(max)),'NULL') + SET @Parameters += ', @FragmentationLevel2 = ' + ISNULL(CAST(@FragmentationLevel2 AS nvarchar(max)),'NULL') + SET @Parameters += ', @MinNumberOfPages = ' + ISNULL(CAST(@MinNumberOfPages AS nvarchar(max)),'NULL') + SET @Parameters += ', @MaxNumberOfPages = ' + ISNULL(CAST(@MaxNumberOfPages AS nvarchar(max)),'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 += ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar(max)),'NULL') + SET @Parameters += ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar(max)),'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 += ', @StatisticsModificationLevel = ' + ISNULL(CAST(@StatisticsModificationLevel AS nvarchar(max)),'NULL') + SET @Parameters += ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar(max)),'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 += ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar(max)),'NULL') + SET @Parameters += ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar(max)),'NULL') + SET @Parameters += ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)),'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 += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar(max)),'NULL') + SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar(max)),'NULL') SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') @@ -309,7 +313,7 @@ BEGIN SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) @@ -345,12 +349,6 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- - IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE [name] = DB_NAME()) >= 90 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The database ' + QUOTENAME(DB_NAME()) + ' 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, [State]) @@ -1363,7 +1361,7 @@ BEGIN BEGIN ROLLBACK TRANSACTION END - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() @@ -1430,7 +1428,7 @@ BEGIN SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' BEGIN - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar(max),SYSDATETIME(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) @@ -1464,24 +1462,40 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @CurrentReplicaID = databases.replica_id + SELECT @CurrentAvailabilityGroupReplicaID = 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 @CurrentAvailabilityGroupID = group_id FROM sys.availability_replicas - WHERE replica_id = @CurrentReplicaID + WHERE replica_id = @CurrentAvailabilityGroupReplicaID SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states - WHERE replica_id = @CurrentReplicaID + WHERE replica_id = @CurrentAvailabilityGroupReplicaID SELECT @CurrentAvailabilityGroup = [name] FROM sys.availability_groups WHERE group_id = @CurrentAvailabilityGroupID END + IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SELECT @CurrentDistributedAvailabilityGroupID = availability_groups.group_id, + @CurrentDistributedAvailabilityGroup = availability_groups.[name], + @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id + FROM sys.availability_groups availability_groups + INNER JOIN sys.availability_replicas availability_replicas ON availability_groups.group_id = availability_replicas.group_id + INNER JOIN sys.availability_groups availability_groups_local ON availability_replicas.replica_server_name = availability_groups_local.[name] + WHERE availability_groups.is_distributed = 1 + AND availability_groups_local.group_id = @CurrentAvailabilityGroupID + + SELECT @CurrentDistributedAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc + FROM sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states + WHERE dm_hadr_availability_replica_states.replica_id = @CurrentDistributedAvailabilityGroupReplicaID + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) @@ -1499,6 +1513,21 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END + IF @CurrentDistributedAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Distributed availability group: ' + ISNULL(@CurrentDistributedAvailabilityGroup,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Distributed availability group role: ' + ISNULL(@CurrentDistributedAvailabilityGroupRole,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Replica role in distributed availability group: ' + CASE WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Global primary' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Forwarder' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in secondary availability group' + WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in primary availability group' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + IF @CurrentDatabaseMirroringRole IS NOT NULL BEGIN SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole @@ -1529,6 +1558,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentUserAccess = 'SINGLE_USER') AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) + AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) AND NOT (@AmazonRDS = 1 AND @CurrentDatabaseName = 'rdsadmin') AND NOT (@CurrentIsReadOnly = 1) AND (@CurrentExecuteAsUserExists = 1 OR @CurrentExecuteAsUserExists IS NULL) @@ -1842,7 +1872,7 @@ BEGIN BEGIN SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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' @@ -1857,7 +1887,7 @@ 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 + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @@ -1876,7 +1906,7 @@ BEGIN BEGIN SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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' @@ -1890,7 +1920,7 @@ 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 + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @@ -1909,7 +1939,7 @@ BEGIN BEGIN SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN @@ -1924,7 +1954,7 @@ BEGIN 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 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 + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @@ -1947,7 +1977,7 @@ BEGIN BEGIN SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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' @@ -1955,7 +1985,7 @@ BEGIN 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 + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @@ -2101,15 +2131,15 @@ BEGIN IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 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') + SET @CurrentComment += 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar(max)),'N/A') + ', ' + SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar(max)),'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 + FROM (SELECT CAST(@CurrentPageCount AS nvarchar(max)) AS [PageCount], + CAST(@CurrentFragmentationLevel AS nvarchar(max)) AS Fragmentation ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END @@ -2120,12 +2150,12 @@ BEGIN SET @CurrentCommandType = 'ALTER_INDEX' SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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 @CurrentIsPartition = 1 AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand += ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar(max)) IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN @@ -2142,7 +2172,7 @@ BEGIN 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 + SELECT 'ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END END IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) AND @CurrentResumableIndexOperation = 0 @@ -2154,13 +2184,13 @@ BEGIN 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) + SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max)) 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) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'FILLFACTOR = ' + CAST(@FillFactor AS nvarchar) + SELECT 'FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max)) END 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 @@ -2220,15 +2250,15 @@ BEGIN 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 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' - SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') + SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar(max)),'N/A') + ', ' + SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar(max)),'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 + FROM (SELECT CAST(@CurrentRowCount AS nvarchar(max)) AS [RowCount], + CAST(@CurrentModificationCounter AS nvarchar(max)) AS ModificationCounter ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END @@ -2239,13 +2269,13 @@ BEGIN SET @CurrentCommandType = 'UPDATE_STATISTICS' SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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 OR SERVERPROPERTY('EngineEdition') IN (5, 8)) BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) + SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max)) END IF @CurrentStatisticsSample = 100 @@ -2257,7 +2287,7 @@ BEGIN IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar) + ' PERCENT' + SELECT 'SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT' END IF @CurrentNoRecompute = 1 @@ -2395,10 +2425,15 @@ BEGIN SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL - SET @CurrentReplicaID = NULL + SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL + SET @CurrentDistributedAvailabilityGroupID = NULL + SET @CurrentDistributedAvailabilityGroup = NULL + SET @CurrentDistributedAvailabilityGroupReplicaID = NULL + SET @CurrentDistributedAvailabilityGroupRole = NULL + SET @CurrentDatabaseMirroringRole = NULL SET @CurrentCommand = NULL @@ -2412,7 +2447,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- Logging: - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar(max),SYSDATETIME(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 33d3b3cd..c89307e4 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: 2026-05-25 19:57:22 +Version: 2026-05-28 01:22:34 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-25 19:57:22 //-- + --// Version: 2026-05-28 01:22:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -175,12 +175,6 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- - IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE [name] = DB_NAME()) >= 90 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The database ' + QUOTENAME(DB_NAME()) + ' 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, [State]) @@ -296,7 +290,7 @@ BEGIN SET @StartTime = SYSDATETIME() - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Database context: ' + QUOTENAME(@DatabaseContext) @@ -339,7 +333,7 @@ BEGIN SET @Error = ERROR_NUMBER() SET @ErrorMessageOriginal = ERROR_MESSAGE() - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205, 1222, 5245) THEN @LockMessageSeverity ELSE ERROR_SEVERITY() END RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT @@ -364,10 +358,10 @@ BEGIN 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(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) + SET @EndMessage = 'Duration: ' + CASE WHEN (DATEDIFF(SECOND,@StartTime,@EndTime) / (24 * 3600)) > 0 THEN CAST((DATEDIFF(SECOND,@StartTime,@EndTime) / (24 * 3600)) AS nvarchar(max)) + '.' ELSE '' END + CONVERT(nvarchar(max),DATEADD(SECOND,DATEDIFF(SECOND,@StartTime,@EndTime),'1900-01-01'),108) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,@EndTime,120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar(max),@EndTime,120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT @@ -484,7 +478,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-25 19:57:22 //-- + --// Version: 2026-05-28 01:22:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -550,13 +544,17 @@ BEGIN DECLARE @CurrentDate datetime2 DECLARE @CurrentDateUTC datetime2 DECLARE @CurrentCleanupDate datetime2 - DECLARE @CurrentReplicaID uniqueidentifier + DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState nvarchar(max) DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) + DECLARE @CurrentDistributedAvailabilityGroupID uniqueidentifier + DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) + DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier + DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) DECLARE @CurrentIsPreferredBackupReplica bit DECLARE @CurrentDatabaseMirroringRole nvarchar(max) DECLARE @CurrentLogShippingRole nvarchar(max) @@ -684,7 +682,7 @@ BEGIN 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 += ', @CleanupTime = ' + ISNULL(CAST(@CleanupTime AS nvarchar(max)),'NULL') SET @Parameters += ', @CleanupMode = ' + ISNULL('''' + REPLACE(@CleanupMode,'''','''''') + '''','NULL') SET @Parameters += ', @Compress = ' + ISNULL('''' + REPLACE(@Compress,'''','''''') + '''','NULL') SET @Parameters += ', @CompressionAlgorithm = ' + ISNULL('''' + REPLACE(@CompressionAlgorithm,'''','''''') + '''','NULL') @@ -693,17 +691,17 @@ BEGIN 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 += ', @MinBackupSizeForMultipleFiles = ' + ISNULL(CAST(@MinBackupSizeForMultipleFiles AS nvarchar),'NULL') - SET @Parameters += ', @MaxFileSize = ' + ISNULL(CAST(@MaxFileSize AS nvarchar),'NULL') - SET @Parameters += ', @CompressionLevelNumeric = ' + ISNULL(CAST(@CompressionLevelNumeric AS nvarchar),'NULL') + SET @Parameters += ', @BlockSize = ' + ISNULL(CAST(@BlockSize AS nvarchar(max)),'NULL') + SET @Parameters += ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar(max)),'NULL') + SET @Parameters += ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar(max)),'NULL') + SET @Parameters += ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar(max)),'NULL') + SET @Parameters += ', @MinBackupSizeForMultipleFiles = ' + ISNULL(CAST(@MinBackupSizeForMultipleFiles AS nvarchar(max)),'NULL') + SET @Parameters += ', @MaxFileSize = ' + ISNULL(CAST(@MaxFileSize AS nvarchar(max)),'NULL') + SET @Parameters += ', @CompressionLevelNumeric = ' + ISNULL(CAST(@CompressionLevelNumeric AS nvarchar(max)),'NULL') SET @Parameters += ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL') SET @Parameters += ', @BackupSetName = ' + ISNULL('''' + REPLACE(@BackupSetName,'''','''''') + '''','NULL') - SET @Parameters += ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar),'NULL') - SET @Parameters += ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar),'NULL') + SET @Parameters += ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar(max)),'NULL') + SET @Parameters += ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar(max)),'NULL') SET @Parameters += ', @Encrypt = ' + ISNULL('''' + REPLACE(@Encrypt,'''','''''') + '''','NULL') SET @Parameters += ', @EncryptionAlgorithm = ' + ISNULL('''' + REPLACE(@EncryptionAlgorithm,'''','''''') + '''','NULL') SET @Parameters += ', @ServerCertificate = ' + ISNULL('''' + REPLACE(@ServerCertificate,'''','''''') + '''','NULL') @@ -715,16 +713,16 @@ BEGIN 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 += ', @MirrorCleanupTime = ' + ISNULL(CAST(@MirrorCleanupTime AS nvarchar(max)),'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 += ', @MinDatabaseSizeForDifferentialBackup = ' + ISNULL('''' + REPLACE(@MinDatabaseSizeForDifferentialBackup,'''','''''') + '''','NULL') - SET @Parameters += ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar),'NULL') - SET @Parameters += ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar),'NULL') + SET @Parameters += ', @ModificationLevel = ' + ISNULL(CAST(@ModificationLevel AS nvarchar(max)),'NULL') + SET @Parameters += ', @MinDatabaseSizeForDifferentialBackup = ' + ISNULL(CAST(@MinDatabaseSizeForDifferentialBackup AS nvarchar(max)),'NULL') + SET @Parameters += ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar(max)),'NULL') + SET @Parameters += ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar(max)),'NULL') SET @Parameters += ', @DataDomainBoostHost = ' + ISNULL('''' + REPLACE(@DataDomainBoostHost,'''','''''') + '''','NULL') SET @Parameters += ', @DataDomainBoostUser = ' + ISNULL('''' + REPLACE(@DataDomainBoostUser,'''','''''') + '''','NULL') SET @Parameters += ', @DataDomainBoostDevicePath = ' + ISNULL('''' + REPLACE(@DataDomainBoostDevicePath,'''','''''') + '''','NULL') @@ -745,16 +743,16 @@ BEGIN SET @Parameters += ', @ExcludeLogShippedFromLogBackup = ' + ISNULL('''' + REPLACE(@ExcludeLogShippedFromLogBackup,'''','''''') + '''','NULL') SET @Parameters += ', @DirectoryCheck = ' + ISNULL('''' + REPLACE(@DirectoryCheck,'''','''''') + '''','NULL') SET @Parameters += ', @BackupOptions = ' + ISNULL('''' + REPLACE(@BackupOptions,'''','''''') + '''','NULL') - SET @Parameters += ', @Stats = ' + ISNULL(CAST(@Stats AS nvarchar),'NULL') - SET @Parameters += ', @ExpireDate = ' + ISNULL('''' + CONVERT(nvarchar, @ExpireDate, 21) + '''','NULL') - SET @Parameters += ', @RetainDays = ' + ISNULL(CAST(@RetainDays AS nvarchar),'NULL') + SET @Parameters += ', @Stats = ' + ISNULL(CAST(@Stats AS nvarchar(max)),'NULL') + SET @Parameters += ', @ExpireDate = ' + ISNULL('''' + CONVERT(nvarchar(max), @ExpireDate, 21) + '''','NULL') + SET @Parameters += ', @RetainDays = ' + ISNULL(CAST(@RetainDays AS nvarchar(max)),'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') SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) @@ -790,12 +788,6 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- - IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE [name] = DB_NAME()) >= 90 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The database ' + QUOTENAME(DB_NAME()) + ' 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, [State]) @@ -1176,8 +1168,8 @@ BEGIN SET @MirrorDirectory = REPLACE(@MirrorDirectory, CHAR(10), '') SET @MirrorDirectory = REPLACE(@MirrorDirectory, CHAR(13), '') - WHILE CHARINDEX(', ',@MirrorDirectory) > 0 SET @MirrorDirectory = REPLACE(@MirrorDirectory,', ',',') - WHILE CHARINDEX(' ,',@MirrorDirectory) > 0 SET @MirrorDirectory = REPLACE(@MirrorDirectory,' ,',',') + WHILE CHARINDEX(@StringDelimiter + ' ', @MirrorDirectory) > 0 SET @MirrorDirectory = REPLACE(@MirrorDirectory, @StringDelimiter + ' ', @StringDelimiter) + WHILE CHARINDEX(' ' + @StringDelimiter, @MirrorDirectory) > 0 SET @MirrorDirectory = REPLACE(@MirrorDirectory, ' ' + @StringDelimiter, @StringDelimiter) SET @MirrorDirectory = LTRIM(RTRIM(@MirrorDirectory)); @@ -3054,7 +3046,7 @@ BEGIN BEGIN ROLLBACK TRANSACTION END - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() @@ -3123,7 +3115,7 @@ BEGIN SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' BEGIN - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar(max),SYSDATETIME(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) @@ -3167,23 +3159,23 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @CurrentReplicaID = databases.replica_id + SELECT @CurrentAvailabilityGroupReplicaID = 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 @CurrentAvailabilityGroupID = group_id FROM sys.availability_replicas - WHERE replica_id = @CurrentReplicaID + WHERE replica_id = @CurrentAvailabilityGroupReplicaID SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states - WHERE replica_id = @CurrentReplicaID + WHERE replica_id = @CurrentAvailabilityGroupReplicaID SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc FROM sys.dm_hadr_database_replica_states - WHERE replica_id = @CurrentReplicaID + WHERE replica_id = @CurrentAvailabilityGroupReplicaID AND database_id = DB_ID(@CurrentDatabaseName) SELECT @CurrentAvailabilityGroup = [name], @@ -3197,6 +3189,22 @@ BEGIN SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) END + IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SELECT @CurrentDistributedAvailabilityGroupID = availability_groups.group_id, + @CurrentDistributedAvailabilityGroup = availability_groups.[name], + @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id + FROM sys.availability_groups availability_groups + INNER JOIN sys.availability_replicas availability_replicas ON availability_groups.group_id = availability_replicas.group_id + INNER JOIN sys.availability_groups availability_groups_local ON availability_replicas.replica_server_name = availability_groups_local.[name] + WHERE availability_groups.is_distributed = 1 + AND availability_groups_local.group_id = @CurrentAvailabilityGroupID + + SELECT @CurrentDistributedAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc + FROM sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states + WHERE dm_hadr_availability_replica_states.replica_id = @CurrentDistributedAvailabilityGroupReplicaID + END + SELECT @CurrentDifferentialBaseLSN = differential_base_lsn FROM sys.master_files WHERE database_id = DB_ID(@CurrentDatabaseName) @@ -3212,8 +3220,8 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentInStandby = 1) 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 OR @MinDatabaseSizeForDifferentialBackup IS NOT NULL) + AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) + AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) BEGIN SET @CurrentCommand = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' @@ -3341,6 +3349,21 @@ BEGIN END END + IF @CurrentDistributedAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Distributed availability group: ' + ISNULL(@CurrentDistributedAvailabilityGroup,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Distributed availability group role: ' + ISNULL(@CurrentDistributedAvailabilityGroupRole,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Replica role in distributed availability group: ' + CASE WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Global primary' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Forwarder' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in secondary availability group' + WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in primary availability group' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + IF @CurrentDatabaseMirroringRole IS NOT NULL BEGIN SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole @@ -3353,7 +3376,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Differential base LSN: ' + ISNULL(CAST(@CurrentDifferentialBaseLSN AS nvarchar),'N/A') + SET @DatabaseMessage = 'Differential base LSN: ' + ISNULL(CAST(@CurrentDifferentialBaseLSN AS nvarchar(max)),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentBackupType = 'DIFF' OR @CurrentDifferentialBaseIsSnapshot IS NOT NULL @@ -3362,15 +3385,15 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar),'N/A') + SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar(max)),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentBackupType IN('DIFF','FULL') BEGIN - SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar) + ' (' + CAST(@CurrentAllocatedExtentPageCount * 1. * 8 / 1024 AS nvarchar) + ' MB)','N/A') + SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar(max)) + ' (' + CAST(@CurrentAllocatedExtentPageCount * 1. * 8 / 1024 AS nvarchar(max)) + ' MB)','N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - SET @DatabaseMessage = 'Modified extent page count: ' + ISNULL(CAST(@CurrentModifiedExtentPageCount AS nvarchar) + ' (' + CAST(@CurrentModifiedExtentPageCount * 1. * 8 / 1024 AS nvarchar) + ' MB)','N/A') + SET @DatabaseMessage = 'Modified extent page count: ' + ISNULL(CAST(@CurrentModifiedExtentPageCount AS nvarchar(max)) + ' (' + CAST(@CurrentModifiedExtentPageCount * 1. * 8 / 1024 AS nvarchar(max)) + ' MB)','N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END @@ -3379,7 +3402,7 @@ 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 - SET @DatabaseMessage = 'Log size since last log backup (MB): ' + ISNULL(CAST(@CurrentLogSizeSinceLastLogBackup AS nvarchar),'N/A') + SET @DatabaseMessage = 'Log size since last log backup (MB): ' + ISNULL(CAST(@CurrentLogSizeSinceLastLogBackup AS nvarchar(max)),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END @@ -3394,6 +3417,7 @@ BEGIN AND NOT (@CurrentBackupType IN('DIFF','LOG') AND (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') + AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole = 'SECONDARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) 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') @@ -3598,18 +3622,18 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{CopyOnly}','COPY_ONLY') SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ISNULL(@Description,''),'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupSetName}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ISNULL(@BackupSetName,''),'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Year}',CAST(DATEPART(YEAR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Year}',CAST(DATEPART(YEAR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max))) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Weekday}',DATENAME(WEEKDAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),3)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) 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))) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),3)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),6)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4))) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3))) END IF @DirectoryStructureCase IS NOT NULL @@ -3762,20 +3786,20 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{CopyOnly}','COPY_ONLY') SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ISNULL(@Description,''),'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{BackupSetName}',LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(ISNULL(@BackupSetName,''),'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')))) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Year}',CAST(DATEPART(YEAR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Year}',CAST(DATEPART(YEAR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max))) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Weekday}',DATENAME(WEEKDAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),2)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),3)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar),6)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),3)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),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))) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4))) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3))) SELECT @CurrentMaxFilePathLength = CASE WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) @@ -3813,7 +3837,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) END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles >= 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) END) IF @CurrentDirectoryPath = 'NUL' BEGIN @@ -3850,7 +3874,7 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) AND Mirror = 1 - 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(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -3880,7 +3904,7 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs 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(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -3906,11 +3930,11 @@ BEGIN SELECT @CurrentDirectoryPath = DirectoryPath FROM @CurrentURLs - WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + 1 - AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) + WHERE @CurrentFileNumber >= (DirectoryNumber - 1) * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 1) + 1 + AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 1) AND Mirror = 1 - 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(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -3959,7 +3983,7 @@ BEGIN 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)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_create_subdir N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''' IF @ReturnCode <> 0 OR @ReturnCode IS NULL 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 @@ -4050,7 +4074,7 @@ BEGIN 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)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' @@ -4059,7 +4083,7 @@ BEGIN 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)' + 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(max)) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -4068,7 +4092,7 @@ BEGIN 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)' + 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(max)) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' @@ -4077,7 +4101,7 @@ BEGIN SET @CurrentCommandType = 'xp_ss_delete' - 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)' + 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(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -4163,20 +4187,20 @@ BEGIN 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 @BlockSize IS NOT NULL SET @CurrentCommand += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar(max)) + IF @BufferCount IS NOT NULL SET @CurrentCommand += ', BUFFERCOUNT = ' + CAST(@BufferCount AS nvarchar(max)) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar(max)) IF @Description IS NOT NULL SET @CurrentCommand += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' IF @BackupSetName IS NOT NULL SET @CurrentCommand += ', NAME = N''' + REPLACE(@BackupSetName,'''','''''') + '''' - IF @Stats IS NOT NULL SET @CurrentCommand += ', STATS = ' + CAST(@Stats AS nvarchar) + IF @Stats IS NOT NULL SET @CurrentCommand += ', STATS = ' + CAST(@Stats AS nvarchar(max)) IF @BackupOptions IS NOT NULL SET @CurrentCommand += ', BACKUP_OPTIONS = N''' + REPLACE(@BackupOptions,'''','''''') + '''' 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,'''','''''') + '''' - IF @ExpireDate IS NOT NULL SET @CurrentCommand += ', EXPIREDATE = ''' + CONVERT(nvarchar, @ExpireDate, 21) + '''' - IF @RetainDays IS NOT NULL SET @CurrentCommand += ', RETAINDAYS = ' + CAST(@RetainDays AS nvarchar) + IF @ExpireDate IS NOT NULL SET @CurrentCommand += ', EXPIREDATE = ''' + CONVERT(nvarchar(max), @ExpireDate, 21) + '''' + IF @RetainDays IS NOT NULL SET @CurrentCommand += ', RETAINDAYS = ' + CAST(@RetainDays AS nvarchar(max)) END IF @BackupSoftware = 'LITESPEED' @@ -4212,21 +4236,21 @@ BEGIN 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) + IF @BlockSize IS NOT NULL SET @CurrentCommand += ', BLOCKSIZE = ' + CAST(@BlockSize AS nvarchar(max)) SET @CurrentCommand += '''' IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand += ', @read_write_filegroups = 1' - IF @CompressionLevelNumeric IS NOT NULL SET @CurrentCommand += ', @compressionlevel = ' + CAST(@CompressionLevelNumeric AS nvarchar) + IF @CompressionLevelNumeric IS NOT NULL SET @CurrentCommand += ', @compressionlevel = ' + CAST(@CompressionLevelNumeric AS nvarchar(max)) 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 @BufferCount IS NOT NULL SET @CurrentCommand += ', @buffercount = ' + CAST(@BufferCount AS nvarchar(max)) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand += ', @maxtransfersize = ' + CAST(@CurrentMaxTransferSize AS nvarchar(max)) + IF @Threads IS NOT NULL SET @CurrentCommand += ', @threads = ' + CAST(@Threads AS nvarchar(max)) 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 @Throttle IS NOT NULL SET @CurrentCommand += ', @throttle = ' + CAST(@Throttle AS nvarchar(max)) IF @Description IS NOT NULL SET @CurrentCommand += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' IF @ObjectLevelRecoveryMap = 'Y' SET @CurrentCommand += ', @olrmap = 1' - IF @ExpireDate IS NOT NULL SET @CurrentCommand += ', @expiration = ''' + CONVERT(nvarchar, @ExpireDate, 21) + '''' - IF @RetainDays IS NOT NULL SET @CurrentCommand += ', @retaindays = ' + CAST(@RetainDays AS nvarchar) + IF @ExpireDate IS NOT NULL SET @CurrentCommand += ', @expiration = ''' + CONVERT(nvarchar(max), @ExpireDate, 21) + '''' + IF @RetainDays IS NOT NULL SET @CurrentCommand += ', @retaindays = ' + CAST(@RetainDays AS nvarchar(max)) IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand += ', @cryptlevel = ' + CASE WHEN @EncryptionAlgorithm = 'RC2_40' THEN '0' @@ -4241,7 +4265,7 @@ BEGIN END IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error performing LiteSpeed backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing LiteSpeed backup.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -4278,9 +4302,9 @@ BEGIN IF @NoRecovery = 'Y' AND @CurrentBackupType = 'LOG' SET @CurrentCommand += ', NORECOVERY' IF @Init = 'Y' SET @CurrentCommand += ', INIT' IF @Format = 'Y' SET @CurrentCommand += ', FORMAT' - IF @CompressionLevelNumeric IS NOT NULL SET @CurrentCommand += ', COMPRESSION = ' + CAST(@CompressionLevelNumeric 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 @CompressionLevelNumeric IS NOT NULL SET @CurrentCommand += ', COMPRESSION = ' + CAST(@CompressionLevelNumeric AS nvarchar(max)) + IF @Threads IS NOT NULL SET @CurrentCommand += ', THREADCOUNT = ' + CAST(@Threads AS nvarchar(max)) + IF @CurrentMaxTransferSize IS NOT NULL SET @CurrentCommand += ', MAXTRANSFERSIZE = ' + CAST(@CurrentMaxTransferSize AS nvarchar(max)) IF @Description IS NOT NULL SET @CurrentCommand += ', DESCRIPTION = N''' + REPLACE(@Description,'''','''''') + '''' IF @EncryptionAlgorithm IS NOT NULL SET @CurrentCommand += ', KEYSIZE = ' + CASE @@ -4289,7 +4313,7 @@ BEGIN END 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)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand,'''','''''') + '"''' + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing SQLBackup backup.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' @@ -4322,8 +4346,8 @@ BEGIN 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 @CompressionLevelNumeric IS NOT NULL SET @CurrentCommand += ', @compressionlevel = ' + CAST(@CompressionLevelNumeric AS nvarchar) - IF @Threads IS NOT NULL SET @CurrentCommand += ', @threads = ' + CAST(@Threads AS nvarchar) + IF @CompressionLevelNumeric IS NOT NULL SET @CurrentCommand += ', @compressionlevel = ' + CAST(@CompressionLevelNumeric AS nvarchar(max)) + IF @Threads IS NOT NULL SET @CurrentCommand += ', @threads = ' + CAST(@Threads AS nvarchar(max)) IF @Init = 'Y' SET @CurrentCommand += ', @overwrite = 1' IF @Description IS NOT NULL SET @CurrentCommand += ', @desc = N''' + REPLACE(@Description,'''','''''') + '''' @@ -4333,7 +4357,7 @@ BEGIN END + '''' IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptedbackuppassword = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' @@ -4344,7 +4368,7 @@ BEGIN SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.emc_run_backup ''' - SET @CurrentCommand += ' -c ' + CASE WHEN @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar) END + SET @CurrentCommand += ' -c ' + CASE WHEN @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)) END SET @CurrentCommand += ' -l ' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'full' @@ -4354,15 +4378,15 @@ BEGIN IF @NoRecovery = 'Y' SET @CurrentCommand += ' -H' - 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 @CleanupTime IS NOT NULL SET @CurrentCommand += ' -y +' + CAST(@CleanupTime/24 + CASE WHEN @CleanupTime%24 > 0 THEN 1 ELSE 0 END AS nvarchar(max)) + 'd' IF @Checksum = 'Y' SET @CurrentCommand += ' -k' - SET @CurrentCommand += ' -S ' + CAST(@CurrentNumberOfFiles AS nvarchar) + SET @CurrentCommand += ' -S ' + CAST(@CurrentNumberOfFiles AS nvarchar(max)) IF @Description IS NOT NULL SET @CurrentCommand += ' -b "' + REPLACE(@Description,'''','''''') + '"' - IF @BufferCount IS NOT NULL SET @CurrentCommand += ' -O "BUFFERCOUNT=' + CAST(@BufferCount AS nvarchar) + '"' + IF @BufferCount IS NOT NULL SET @CurrentCommand += ' -O "BUFFERCOUNT=' + CAST(@BufferCount AS nvarchar(max)) + '"' IF @ReadWriteFileGroups = 'Y' AND @CurrentDatabaseName <> 'master' SET @CurrentCommand += ' -O "READ_WRITE_FILEGROUPS"' @@ -4376,12 +4400,12 @@ BEGIN IF @BackupSetName IS NOT NULL SET @CurrentCommand += ' -N "' + REPLACE(@BackupSetName,'''','''''') + '"' IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand += ' "MSSQL' - IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand += ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar) + IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand += ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max)) SET @CurrentCommand += ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' SET @CurrentCommand += '''' - SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' END EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -4423,7 +4447,7 @@ BEGIN SET @CurrentCommand += ' WITH ' IF @Checksum = 'Y' SET @CurrentCommand += 'CHECKSUM' IF @Checksum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' - IF @Stats IS NOT NULL SET @CurrentCommand += ', STATS = ' + CAST(@Stats AS nvarchar) + IF @Stats IS NOT NULL SET @CurrentCommand += ', STATS = ' + CAST(@Stats AS nvarchar(max)) IF @BackupOptions IS NOT NULL SET @CurrentCommand += ', RESTORE_OPTIONS = N''' + REPLACE(@BackupOptions,'''','''''') + '''' IF @URL IS NOT NULL AND @Credential IS NOT NULL SET @CurrentCommand += ', CREDENTIAL = N''' + REPLACE(@Credential,'''','''''') + '''' END @@ -4447,7 +4471,7 @@ BEGIN SET @CurrentCommand += '''' IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' - SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying LiteSpeed backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error verifying LiteSpeed backup.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -4468,7 +4492,7 @@ BEGIN IF @Checksum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' 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 verifying SQLBackup backup.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand,'''','''''') + '"''' + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error verifying SQLBackup backup.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' @@ -4489,7 +4513,7 @@ BEGIN WITHIN GROUP (ORDER BY RowNumber ASC) FROM CurrentFiles - SET @CurrentCommand += ' IF @ReturnCode <> 0 RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' + SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' END EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -4572,7 +4596,7 @@ BEGIN 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)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + @CurrentFileExtension + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' @@ -4581,7 +4605,7 @@ BEGIN 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)' + 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(max)) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -4590,7 +4614,7 @@ BEGIN 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)' + 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(max)) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' @@ -4599,7 +4623,7 @@ BEGIN SET @CurrentCommandType = 'xp_ss_delete' - 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)' + 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(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute @@ -4679,7 +4703,7 @@ BEGIN SET @CurrentDate = NULL SET @CurrentDateUTC = NULL SET @CurrentCleanupDate = NULL - SET @CurrentReplicaID = NULL + SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL @@ -4687,6 +4711,10 @@ BEGIN SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL SET @CurrentIsPreferredBackupReplica = NULL + SET @CurrentDistributedAvailabilityGroupID = NULL + SET @CurrentDistributedAvailabilityGroup = NULL + SET @CurrentDistributedAvailabilityGroupReplicaID = NULL + SET @CurrentDistributedAvailabilityGroupRole = NULL SET @CurrentDatabaseMirroringRole = NULL SET @CurrentLogShippingRole = NULL SET @CurrentBackupOperationSupportedOnSecondaryReplicas = NULL @@ -4715,7 +4743,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- Logging: - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar(max),SYSDATETIME(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT @@ -4771,7 +4799,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-25 19:57:22 //-- + --// Version: 2026-05-28 01:22:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4805,13 +4833,17 @@ BEGIN DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) - DECLARE @CurrentReplicaID uniqueidentifier + DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) DECLARE @CurrentSecondaryRoleAllowConnections nvarchar(max) DECLARE @CurrentIsPreferredBackupReplica bit + DECLARE @CurrentDistributedAvailabilityGroupID uniqueidentifier + DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) + DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier + DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) DECLARE @CurrentDatabaseMirroringRole nvarchar(max) DECLARE @CurrentFGID int @@ -4939,20 +4971,20 @@ BEGIN 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 += ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar(max)),'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 += ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar(max)),'NULL') + SET @Parameters += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar(max)),'NULL') + SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar(max)),'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') SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) @@ -4988,12 +5020,6 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- - IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE [name] = DB_NAME()) >= 90 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The database ' + QUOTENAME(DB_NAME()) + ' 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, [State]) @@ -6001,7 +6027,7 @@ BEGIN BEGIN ROLLBACK TRANSACTION END - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() @@ -6068,7 +6094,7 @@ BEGIN SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' BEGIN - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar(max),SYSDATETIME(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) @@ -6102,7 +6128,7 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @CurrentReplicaID = databases.replica_id + SELECT @CurrentAvailabilityGroupReplicaID = 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 @@ -6110,11 +6136,11 @@ BEGIN SELECT @CurrentAvailabilityGroupID = group_id, @CurrentSecondaryRoleAllowConnections = secondary_role_allow_connections_desc FROM sys.availability_replicas - WHERE replica_id = @CurrentReplicaID + WHERE replica_id = @CurrentAvailabilityGroupReplicaID SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states - WHERE replica_id = @CurrentReplicaID + WHERE replica_id = @CurrentAvailabilityGroupReplicaID SELECT @CurrentAvailabilityGroup = [name], @CurrentAvailabilityGroupBackupPreference = UPPER(automated_backup_preference_desc) @@ -6127,6 +6153,22 @@ BEGIN SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) END + IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SELECT @CurrentDistributedAvailabilityGroupID = availability_groups.group_id, + @CurrentDistributedAvailabilityGroup = availability_groups.[name], + @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id + FROM sys.availability_groups availability_groups + INNER JOIN sys.availability_replicas availability_replicas ON availability_groups.group_id = availability_replicas.group_id + INNER JOIN sys.availability_groups availability_groups_local ON availability_replicas.replica_server_name = availability_groups_local.[name] + WHERE availability_groups.is_distributed = 1 + AND availability_groups_local.group_id = @CurrentAvailabilityGroupID + + SELECT @CurrentDistributedAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc + FROM sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states + WHERE dm_hadr_availability_replica_states.replica_id = @CurrentDistributedAvailabilityGroupReplicaID + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) @@ -6159,6 +6201,21 @@ BEGIN END END + IF @CurrentDistributedAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Distributed availability group: ' + ISNULL(@CurrentDistributedAvailabilityGroup,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Distributed availability group role: ' + ISNULL(@CurrentDistributedAvailabilityGroupRole,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Replica role in distributed availability group: ' + CASE WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Global primary' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Forwarder' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in secondary availability group' + WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in primary availability group' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + IF @CurrentDatabaseMirroringRole IS NOT NULL BEGIN SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole @@ -6184,7 +6241,7 @@ BEGIN SET @CurrentCommandType = 'DBCC_CHECKDB' SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'DBCC CHECKDB (' + QUOTENAME(@CurrentDatabaseName) IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' SET @CurrentCommand += ') WITH ALL_ERRORMSGS' @@ -6193,7 +6250,7 @@ BEGIN IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand += ', EXTENDED_LOGICAL_CHECKS' IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ', NO_INFOMSGS' IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar(max)) EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -6286,7 +6343,7 @@ BEGIN -- Does the filegroup exist? SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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 @@ -6295,7 +6352,7 @@ 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 + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @@ -6313,14 +6370,14 @@ BEGIN SET @CurrentCommandType = 'DBCC_CHECKFILEGROUP' SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' SET @CurrentCommand += ') WITH ALL_ERRORMSGS' IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ', NO_INFOMSGS' IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar(max)) EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR @@ -6354,7 +6411,7 @@ BEGIN SET @CurrentCommandType = 'DBCC_CHECKALLOC' SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'DBCC CHECKALLOC (' + QUOTENAME(@CurrentDatabaseName) SET @CurrentCommand += ') WITH ALL_ERRORMSGS' IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ', NO_INFOMSGS' @@ -6455,7 +6512,7 @@ BEGIN -- Does the object exist? SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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 @@ -6464,7 +6521,7 @@ 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 + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @@ -6482,7 +6539,7 @@ BEGIN SET @CurrentCommandType = 'DBCC_CHECKTABLE' SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'DBCC CHECKTABLE (N' + QUOTENAME(QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName),'''') IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' SET @CurrentCommand += ') WITH ALL_ERRORMSGS' @@ -6491,7 +6548,7 @@ BEGIN IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand += ', EXTENDED_LOGICAL_CHECKS' IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ', NO_INFOMSGS' IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' - IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar) + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar(max)) 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 @@ -6521,14 +6578,14 @@ BEGIN END -- Check catalog - IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') AND @CurrentAvailabilityGroupRole = 'PRIMARY' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentDatabaseContext = CASE WHEN SERVERPROPERTY('EngineEdition') = 5 THEN @CurrentDatabaseName ELSE 'master' END SET @CurrentCommandType = 'DBCC_CHECKCATALOG' SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) SET @CurrentCommand += ')' IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ' WITH NO_INFOMSGS' @@ -6578,13 +6635,17 @@ BEGIN SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL - SET @CurrentReplicaID = NULL + SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL SET @CurrentSecondaryRoleAllowConnections = NULL SET @CurrentIsPreferredBackupReplica = NULL + SET @CurrentDistributedAvailabilityGroupID = NULL + SET @CurrentDistributedAvailabilityGroup = NULL + SET @CurrentDistributedAvailabilityGroupReplicaID = NULL + SET @CurrentDistributedAvailabilityGroupRole = NULL SET @CurrentDatabaseMirroringRole = NULL SET @CurrentDatabaseContext = NULL @@ -6602,7 +6663,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- Logging: - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar(max),SYSDATETIME(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT @@ -6673,7 +6734,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-25 19:57:22 //-- + --// Version: 2026-05-28 01:22:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6714,10 +6775,14 @@ BEGIN DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) - DECLARE @CurrentReplicaID uniqueidentifier + DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) + DECLARE @CurrentDistributedAvailabilityGroupID uniqueidentifier + DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) + DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier + DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) DECLARE @CurrentDatabaseMirroringRole nvarchar(max) DECLARE @CurrentDatabaseContext nvarchar(max) @@ -6896,31 +6961,31 @@ BEGIN 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 += ', @FragmentationLevel1 = ' + ISNULL(CAST(@FragmentationLevel1 AS nvarchar(max)),'NULL') + SET @Parameters += ', @FragmentationLevel2 = ' + ISNULL(CAST(@FragmentationLevel2 AS nvarchar(max)),'NULL') + SET @Parameters += ', @MinNumberOfPages = ' + ISNULL(CAST(@MinNumberOfPages AS nvarchar(max)),'NULL') + SET @Parameters += ', @MaxNumberOfPages = ' + ISNULL(CAST(@MaxNumberOfPages AS nvarchar(max)),'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 += ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar(max)),'NULL') + SET @Parameters += ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar(max)),'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 += ', @StatisticsModificationLevel = ' + ISNULL(CAST(@StatisticsModificationLevel AS nvarchar(max)),'NULL') + SET @Parameters += ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar(max)),'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 += ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar(max)),'NULL') + SET @Parameters += ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar(max)),'NULL') + SET @Parameters += ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)),'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 += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar(max)),'NULL') + SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar(max)),'NULL') SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') @@ -6928,7 +6993,7 @@ BEGIN SET @Parameters += ', @LogToTable = ' + ISNULL('''' + REPLACE(@LogToTable,'''','''''') + '''','NULL') SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') - SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar,@StartTime,120) + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) @@ -6964,12 +7029,6 @@ BEGIN --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- - IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE [name] = DB_NAME()) >= 90 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The database ' + QUOTENAME(DB_NAME()) + ' 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, [State]) @@ -7982,7 +8041,7 @@ BEGIN BEGIN ROLLBACK TRANSACTION END - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar) + ', ' + ISNULL(ERROR_MESSAGE(),'') + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT SET @ReturnCode = ERROR_NUMBER() @@ -8049,7 +8108,7 @@ BEGIN SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' BEGIN - SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar(max),SYSDATETIME(),120) RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Database: ' + QUOTENAME(@CurrentDatabaseName) @@ -8083,24 +8142,40 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - SELECT @CurrentReplicaID = databases.replica_id + SELECT @CurrentAvailabilityGroupReplicaID = 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 @CurrentAvailabilityGroupID = group_id FROM sys.availability_replicas - WHERE replica_id = @CurrentReplicaID + WHERE replica_id = @CurrentAvailabilityGroupReplicaID SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states - WHERE replica_id = @CurrentReplicaID + WHERE replica_id = @CurrentAvailabilityGroupReplicaID SELECT @CurrentAvailabilityGroup = [name] FROM sys.availability_groups WHERE group_id = @CurrentAvailabilityGroupID END + IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SELECT @CurrentDistributedAvailabilityGroupID = availability_groups.group_id, + @CurrentDistributedAvailabilityGroup = availability_groups.[name], + @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id + FROM sys.availability_groups availability_groups + INNER JOIN sys.availability_replicas availability_replicas ON availability_groups.group_id = availability_replicas.group_id + INNER JOIN sys.availability_groups availability_groups_local ON availability_replicas.replica_server_name = availability_groups_local.[name] + WHERE availability_groups.is_distributed = 1 + AND availability_groups_local.group_id = @CurrentAvailabilityGroupID + + SELECT @CurrentDistributedAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc + FROM sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states + WHERE dm_hadr_availability_replica_states.replica_id = @CurrentDistributedAvailabilityGroupReplicaID + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) @@ -8118,6 +8193,21 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END + IF @CurrentDistributedAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Distributed availability group: ' + ISNULL(@CurrentDistributedAvailabilityGroup,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Distributed availability group role: ' + ISNULL(@CurrentDistributedAvailabilityGroupRole,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Replica role in distributed availability group: ' + CASE WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Global primary' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Forwarder' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in secondary availability group' + WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in primary availability group' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + IF @CurrentDatabaseMirroringRole IS NOT NULL BEGIN SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole @@ -8148,6 +8238,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentUserAccess = 'SINGLE_USER') AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) + AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) AND NOT (@AmazonRDS = 1 AND @CurrentDatabaseName = 'rdsadmin') AND NOT (@CurrentIsReadOnly = 1) AND (@CurrentExecuteAsUserExists = 1 OR @CurrentExecuteAsUserExists IS NULL) @@ -8461,7 +8552,7 @@ BEGIN BEGIN SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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' @@ -8476,7 +8567,7 @@ 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 + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @@ -8495,7 +8586,7 @@ BEGIN BEGIN SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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' @@ -8509,7 +8600,7 @@ 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 + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @@ -8528,7 +8619,7 @@ BEGIN BEGIN SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN @@ -8543,7 +8634,7 @@ BEGIN 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 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 + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @@ -8566,7 +8657,7 @@ BEGIN BEGIN SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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' @@ -8574,7 +8665,7 @@ BEGIN 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 + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @@ -8720,15 +8811,15 @@ BEGIN IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 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') + SET @CurrentComment += 'PageCount: ' + ISNULL(CAST(@CurrentPageCount AS nvarchar(max)),'N/A') + ', ' + SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar(max)),'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 + FROM (SELECT CAST(@CurrentPageCount AS nvarchar(max)) AS [PageCount], + CAST(@CurrentFragmentationLevel AS nvarchar(max)) AS Fragmentation ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END @@ -8739,12 +8830,12 @@ BEGIN SET @CurrentCommandType = 'ALTER_INDEX' SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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 @CurrentIsPartition = 1 AND @CurrentResumableIndexOperation = 0 SET @CurrentCommand += ' PARTITION = ' + CAST(@CurrentPartitionNumber AS nvarchar(max)) IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN @@ -8761,7 +8852,7 @@ BEGIN 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 + SELECT 'ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END END IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) AND @CurrentResumableIndexOperation = 0 @@ -8773,13 +8864,13 @@ BEGIN 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) + SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max)) 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) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'FILLFACTOR = ' + CAST(@FillFactor AS nvarchar) + SELECT 'FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max)) END 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 @@ -8839,15 +8930,15 @@ BEGIN 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 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar),'N/A') + ', ' - SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar),'N/A') + SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar(max)),'N/A') + ', ' + SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar(max)),'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 + FROM (SELECT CAST(@CurrentRowCount AS nvarchar(max)) AS [RowCount], + CAST(@CurrentModificationCounter AS nvarchar(max)) AS ModificationCounter ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END @@ -8858,13 +8949,13 @@ BEGIN SET @CurrentCommandType = 'UPDATE_STATISTICS' SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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 OR SERVERPROPERTY('EngineEdition') IN (5, 8)) BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar) + SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max)) END IF @CurrentStatisticsSample = 100 @@ -8876,7 +8967,7 @@ BEGIN IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar) + ' PERCENT' + SELECT 'SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT' END IF @CurrentNoRecompute = 1 @@ -9014,10 +9105,15 @@ BEGIN SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL - SET @CurrentReplicaID = NULL + SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL + SET @CurrentDistributedAvailabilityGroupID = NULL + SET @CurrentDistributedAvailabilityGroup = NULL + SET @CurrentDistributedAvailabilityGroupReplicaID = NULL + SET @CurrentDistributedAvailabilityGroupRole = NULL + SET @CurrentDatabaseMirroringRole = NULL SET @CurrentCommand = NULL @@ -9031,7 +9127,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- Logging: - SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar,SYSDATETIME(),120) + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar(max),SYSDATETIME(),120) RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT RAISERROR(@EmptyLine,10,1) WITH NOWAIT From d89e7accfc54a849e973436df31fcde4445073b2 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 28 May 2026 17:49:33 +0200 Subject: [PATCH 018/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 32 ++++++++---- DatabaseIntegrityCheck.sql | 32 ++++++++---- IndexOptimize.sql | 32 ++++++++---- MaintenanceSolution.sql | 100 +++++++++++++++++++++++++------------ 5 files changed, 135 insertions(+), 63 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 10a7a5c6..7d34d831 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: 2026-05-28 01:22:34 //-- + --// Version: 2026-05-28 17:39:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 24b8312d..b4b1f711 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 01:22:34 //-- + --// Version: 2026-05-28 17:39:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -276,13 +276,19 @@ BEGIN 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)) - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END - IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) - AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN - SET @ContainedAvailabilityGroupListenerConnection = 1 + IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) + BEGIN + SET @ContainedAvailabilityGroupListenerConnection = 1 + END END DECLARE @AmazonRDS bit = CASE WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END @@ -377,11 +383,17 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Platform: ' + @HostPlatform - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 719ffb38..8271ad3c 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 01:22:34 //-- + --// Version: 2026-05-28 17:39:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -187,13 +187,19 @@ BEGIN 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)) - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END - IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) - AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN - SET @ContainedAvailabilityGroupListenerConnection = 1 + IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) + BEGIN + SET @ContainedAvailabilityGroupListenerConnection = 1 + END END DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END @@ -237,11 +243,17 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Platform: ' + @HostPlatform - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT diff --git a/IndexOptimize.sql b/IndexOptimize.sql index b2729962..a7f836c5 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 01:22:34 //-- + --// Version: 2026-05-28 17:39:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -262,13 +262,19 @@ BEGIN 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)) - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END - IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) - AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN - SET @ContainedAvailabilityGroupListenerConnection = 1 + IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) + BEGIN + SET @ContainedAvailabilityGroupListenerConnection = 1 + END END DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END @@ -325,11 +331,17 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Platform: ' + @HostPlatform - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index c89307e4..3a24dd3c 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: 2026-05-28 01:22:34 +Version: 2026-05-28 17:39:32 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 01:22:34 //-- + --// Version: 2026-05-28 17:39:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -478,7 +478,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 01:22:34 //-- + --// Version: 2026-05-28 17:39:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -663,13 +663,19 @@ BEGIN 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)) - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END - IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) - AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN - SET @ContainedAvailabilityGroupListenerConnection = 1 + IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) + BEGIN + SET @ContainedAvailabilityGroupListenerConnection = 1 + END END DECLARE @AmazonRDS bit = CASE WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END @@ -764,11 +770,17 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Platform: ' + @HostPlatform - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -4799,7 +4811,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 01:22:34 //-- + --// Version: 2026-05-28 17:39:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4946,13 +4958,19 @@ BEGIN 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)) - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END - IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) - AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN - SET @ContainedAvailabilityGroupListenerConnection = 1 + IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) + BEGIN + SET @ContainedAvailabilityGroupListenerConnection = 1 + END END DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END @@ -4996,11 +5014,17 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Platform: ' + @HostPlatform - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -6734,7 +6758,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 01:22:34 //-- + --// Version: 2026-05-28 17:39:32 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6942,13 +6966,19 @@ BEGIN 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)) - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END - IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) - AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN - SET @ContainedAvailabilityGroupListenerConnection = 1 + IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) + BEGIN + SET @ContainedAvailabilityGroupListenerConnection = 1 + END END DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END @@ -7005,11 +7035,17 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Platform: ' + @HostPlatform - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') <> 5 + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT From 3d3ba5d7cff4b93ad8e0286f46f6e272e14b9840 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 28 May 2026 18:46:29 +0200 Subject: [PATCH 019/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 29 +++-------------- DatabaseIntegrityCheck.sql | 10 ++---- IndexOptimize.sql | 22 ++----------- MaintenanceSolution.sql | 65 +++++++------------------------------- 5 files changed, 21 insertions(+), 107 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 7d34d831..7ad6af97 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: 2026-05-28 17:39:32 //-- + --// Version: 2026-05-28 18:42:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index b4b1f711..8769aa2d 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -91,7 +91,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 17:39:32 //-- + --// Version: 2026-05-28 18:42:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1239,11 +1239,10 @@ BEGIN 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, -1785266663)))) + AND NOT (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - 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 + SELECT 'The value for the parameter @Compress is not supported. Backup compression is not supported in this edition of SQL Server.', 16, 2 END IF @Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevelNumeric IS NULL OR @CompressionLevelNumeric >= 1) @@ -1654,7 +1653,7 @@ BEGIN 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') IN(3, 8) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786, -1785266663))) + IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (SERVERPROPERTY('EngineEdition') IN(3, 8) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @Encrypt is not supported.', 16, 2 @@ -1833,12 +1832,6 @@ BEGIN 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]) @@ -1847,12 +1840,6 @@ BEGIN ---------------------------------------------------------------------------------------------------- - 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]) @@ -1907,12 +1894,6 @@ BEGIN 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]) @@ -3042,7 +3023,7 @@ BEGIN AND NOT (@CurrentBackupType IN('DIFF','LOG') AND (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') - AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole = 'SECONDARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) + AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) 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') diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 8271ad3c..db57594a 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 17:39:32 //-- + --// Version: 2026-05-28 18:42:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -538,7 +538,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 OR SERVERPROPERTY('IsHadrEnabled') = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 @@ -827,12 +827,6 @@ BEGIN 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 diff --git a/IndexOptimize.sql b/IndexOptimize.sql index a7f836c5..5f181838 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 17:39:32 //-- + --// Version: 2026-05-28 18:42:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -625,7 +625,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 OR SERVERPROPERTY('IsHadrEnabled') = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 @@ -1003,12 +1003,6 @@ BEGIN 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') @@ -1017,12 +1011,6 @@ BEGIN 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) @@ -1039,12 +1027,6 @@ BEGIN 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, [State]) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 3a24dd3c..97c199e5 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: 2026-05-28 17:39:32 +Version: 2026-05-28 18:42:36 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 17:39:32 //-- + --// Version: 2026-05-28 18:42:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -478,7 +478,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 17:39:32 //-- + --// Version: 2026-05-28 18:42:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1626,11 +1626,10 @@ BEGIN 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, -1785266663)))) + AND NOT (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - 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 + SELECT 'The value for the parameter @Compress is not supported. Backup compression is not supported in this edition of SQL Server.', 16, 2 END IF @Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevelNumeric IS NULL OR @CompressionLevelNumeric >= 1) @@ -2041,7 +2040,7 @@ BEGIN 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') IN(3, 8) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786, -1785266663))) + IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (SERVERPROPERTY('EngineEdition') IN(3, 8) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @Encrypt is not supported.', 16, 2 @@ -2220,12 +2219,6 @@ BEGIN 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]) @@ -2234,12 +2227,6 @@ BEGIN ---------------------------------------------------------------------------------------------------- - 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]) @@ -2294,12 +2281,6 @@ BEGIN 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]) @@ -3429,7 +3410,7 @@ BEGIN AND NOT (@CurrentBackupType IN('DIFF','LOG') AND (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') - AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole = 'SECONDARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) + AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) 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') @@ -4811,7 +4792,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 17:39:32 //-- + --// Version: 2026-05-28 18:42:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5309,7 +5290,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 OR SERVERPROPERTY('IsHadrEnabled') = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 @@ -5598,12 +5579,6 @@ BEGIN 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 @@ -6758,7 +6733,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 17:39:32 //-- + --// Version: 2026-05-28 18:42:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7329,7 +7304,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 OR SERVERPROPERTY('IsHadrEnabled') = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR SERVERPROPERTY('IsHadrEnabled') = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 @@ -7707,12 +7682,6 @@ BEGIN 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') @@ -7721,12 +7690,6 @@ BEGIN 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) @@ -7743,12 +7706,6 @@ BEGIN 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, [State]) From 2e38d407a8b381f4e9c28cc5551d800f1979b4f1 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 30 May 2026 10:50:18 +0200 Subject: [PATCH 020/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 94 +++++++++++------- DatabaseIntegrityCheck.sql | 19 +++- IndexOptimize.sql | 74 +++++++------- MaintenanceSolution.sql | 191 ++++++++++++++++++++++--------------- 5 files changed, 223 insertions(+), 157 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 7ad6af97..e22ae6ea 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: 2026-05-28 18:42:36 //-- + --// Version: 2026-05-30 10:34:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 8769aa2d..c9bd6f3d 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -50,14 +50,15 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @AvailabilityGroups nvarchar(max) = NULL, @Updateability nvarchar(max) = 'ALL', @AdaptiveCompression nvarchar(max) = NULL, -@ModificationLevel int = NULL, +@MinModificationLevel int = NULL, @MinDatabaseSizeForDifferentialBackup int = NULL, -@LogSizeSinceLastLogBackup int = NULL, -@TimeSinceLastLogBackup int = NULL, +@MinLogSizeSinceLastLogBackup int = NULL, +@MinTimeSinceLastLogBackup int = NULL, @DataDomainBoostHost nvarchar(max) = NULL, @DataDomainBoostUser nvarchar(max) = NULL, @DataDomainBoostDevicePath nvarchar(max) = NULL, @DataDomainBoostLockboxPath nvarchar(max) = NULL, +@DataDomainBoostNoOutputTable nvarchar(max) = 'N', @DirectoryStructure nvarchar(max) = '{ServerName}${InstanceName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}', @AvailabilityGroupDirectoryStructure nvarchar(max) = '{ClusterName}${AvailabilityGroupName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}', @DirectoryStructureCase nvarchar(max) = NULL, @@ -91,7 +92,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 18:42:36 //-- + --// Version: 2026-05-30 10:34:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -276,6 +277,11 @@ BEGIN 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 SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' + BEGIN + SET @Version = 16.010006 + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SELECT @HostPlatform = host_platform @@ -338,14 +344,15 @@ BEGIN 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(max)),'NULL') + SET @Parameters += ', @MinModificationLevel = ' + ISNULL(CAST(@MinModificationLevel AS nvarchar(max)),'NULL') SET @Parameters += ', @MinDatabaseSizeForDifferentialBackup = ' + ISNULL(CAST(@MinDatabaseSizeForDifferentialBackup AS nvarchar(max)),'NULL') - SET @Parameters += ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar(max)),'NULL') - SET @Parameters += ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar(max)),'NULL') + SET @Parameters += ', @MinLogSizeSinceLastLogBackup = ' + ISNULL(CAST(@MinLogSizeSinceLastLogBackup AS nvarchar(max)),'NULL') + SET @Parameters += ', @MinTimeSinceLastLogBackup = ' + ISNULL(CAST(@MinTimeSinceLastLogBackup AS nvarchar(max)),'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 += ', @DataDomainBoostNoOutputTable = ' + ISNULL('''' + REPLACE(@DataDomainBoostNoOutputTable,'''','''''') + '''','NULL') SET @Parameters += ', @DirectoryStructure = ' + ISNULL('''' + REPLACE(@DirectoryStructure,'''','''''') + '''','NULL') SET @Parameters += ', @AvailabilityGroupDirectoryStructure = ' + ISNULL('''' + REPLACE(@AvailabilityGroupDirectoryStructure,'''','''''') + '''','NULL') SET @Parameters += ', @DirectoryStructureCase = ' + ISNULL('''' + REPLACE(@DirectoryStructureCase,'''','''''') + '''','NULL') @@ -383,6 +390,12 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') = 8 + BEGIN + SET @StartMessage = 'Update type: ' + CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') @@ -737,7 +750,7 @@ BEGIN IF @Directory IS NULL AND @URL IS NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN - IF @Version >= 15 + IF @Version >= 15 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous') BEGIN SET @DefaultDirectory = CAST(SERVERPROPERTY('InstanceDefaultBackupPath') AS nvarchar(max)) END @@ -1124,7 +1137,7 @@ BEGIN --// Get default compression algorithm //-- ---------------------------------------------------------------------------------------------------- - IF @CompressionAlgorithm IS NULL AND @BackupSoftware IS NULL AND @Version >= 16 + IF @CompressionAlgorithm IS NULL AND @BackupSoftware IS NULL AND (@Version >= 16 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN SELECT @CompressionAlgorithm = CASE WHEN @BackupSoftware IS NULL AND EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression algorithm' AND value_in_use IN (0, 1)) THEN 'MS_XPRESS' WHEN @BackupSoftware IS NULL AND EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression algorithm' AND value_in_use = 2) THEN 'QAT_DEFLATE' @@ -1135,7 +1148,7 @@ BEGIN --// Get default compression level //-- ---------------------------------------------------------------------------------------------------- - IF @CompressionLevel IS NULL AND @BackupSoftware IS NULL AND @Version >= 17 + IF @CompressionLevel IS NULL AND @BackupSoftware IS NULL AND (@Version >= 17 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN SET @CompressionLevel = 'LOW' END @@ -1265,7 +1278,7 @@ BEGIN SELECT 'The value for the parameter @CompressionAlgorithm is not supported. The allowed values are MS_XPRESS, QAT_DEFLATE and ZSTD.', 16, 1 END - IF @CompressionAlgorithm IS NOT NULL AND NOT (@Version >= 16) + IF @CompressionAlgorithm IS NOT NULL AND NOT (@Version >= 16 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Specifying the compression algorithm is only supported in SQL Server 2022 and later.', 16, 2 @@ -1277,7 +1290,7 @@ BEGIN SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to QAT_DEFLATE is only supported in Standard and Enterprise Edition.', 16, 3 END - IF @CompressionAlgorithm = 'ZSTD' AND NOT (@Version >= 17) + IF @CompressionAlgorithm = 'ZSTD' AND NOT (@Version >= 17 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to ZSTD is only supported in SQL Server 2025 and later.', 16, 4 @@ -1303,7 +1316,7 @@ BEGIN SELECT 'The value for the parameter @CompressionLevel is not supported. The supported values are LOW, MEDIUM and HIGH.', 16, 2 END - IF @CompressionLevel IS NOT NULL AND NOT (@Version >= 17) + IF @CompressionLevel IS NOT NULL AND NOT (@Version >= 17 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @CompressionLevel is not supported. Setting the compression level is only supported in SQL Server 2025 and later.', 16, 3 @@ -1930,22 +1943,22 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @ModificationLevel <= 0 OR @ModificationLevel > 100 + IF @MinModificationLevel <= 0 OR @MinModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ModificationLevel is not supported.', 16, 2 + SELECT 'The value for the parameter @MinModificationLevel is not supported.', 16, 2 END - IF @ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N' + IF @MinModificationLevel IS NOT NULL AND @ChangeBackupType = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @ModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 3 + SELECT 'The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 3 END - IF @ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF' + IF @MinModificationLevel IS NOT NULL AND @BackupType <> 'DIFF' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @ModificationLevel can only be used for differential backups.', 16, 4 + SELECT 'The parameter @MinModificationLevel can only be used for differential backups.', 16, 4 END ---------------------------------------------------------------------------------------------------- @@ -1964,26 +1977,26 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' + IF @MinLogSizeSinceLastLogBackup 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 + SELECT 'The value for the parameter @MinLogSizeSinceLastLogBackup is not supported.', 16, 2 END ---------------------------------------------------------------------------------------------------- - IF @TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' + IF @MinTimeSinceLastLogBackup 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 + SELECT 'The value for the parameter @MinTimeSinceLastLogBackup is not supported.', 16, 2 END ---------------------------------------------------------------------------------------------------- - IF (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) + IF (@MinTimeSinceLastLogBackup IS NOT NULL AND @MinLogSizeSinceLastLogBackup IS NULL) OR (@MinTimeSinceLastLogBackup IS NULL AND @MinLogSizeSinceLastLogBackup IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameters @TimeSinceLastLogBackup and @LogSizeSinceLastLogBackup can only be used together.', 16, 1 + SELECT 'The parameters @MinTimeSinceLastLogBackup and @MinLogSizeSinceLastLogBackup can only be used together.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -2038,6 +2051,20 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @DataDomainBoostNoOutputTable NOT IN('Y','N') OR @DataDomainBoostNoOutputTable IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 1 + END + + IF @DataDomainBoostNoOutputTable = 'Y' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF @DirectoryStructure = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -2760,7 +2787,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) AND @Credential IS NULL THEN 65537 + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND ((@Version >= 13 AND @Version < 15.0404316) OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) AND @Credential IS NULL THEN 65537 END IF SERVERPROPERTY('IsHadrEnabled') = 1 @@ -2842,7 +2869,7 @@ BEGIN BEGIN SET @CurrentBackupType = 'DIFF' END - IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @ModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) + IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @MinModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) BEGIN SET @CurrentBackupType = 'FULL' END @@ -3027,7 +3054,7 @@ BEGIN 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)) + AND NOT (@CurrentBackupType = 'LOG' AND @MinLogSizeSinceLastLogBackup IS NOT NULL AND @MinTimeSinceLastLogBackup IS NOT NULL AND NOT(@CurrentLogSizeSinceLastLogBackup >= @MinLogSizeSinceLastLogBackup OR @CurrentLogSizeSinceLastLogBackup IS NULL OR DATEDIFF(SECOND,@CurrentLastLogBackup,SYSDATETIME()) >= @MinTimeSinceLastLogBackup OR @CurrentLastLogBackup IS NULL)) AND NOT (@CurrentBackupType = 'LOG' AND @Updateability = 'READ_ONLY' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') AND NOT (@CurrentBackupType = 'DIFF' AND @MinDatabaseSizeForDifferentialBackup IS NOT NULL AND (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) BEGIN -- Start of database backup check @@ -3772,10 +3799,7 @@ BEGIN IF @Checksum = 'Y' SET @CurrentCommand += 'CHECKSUM' IF @Checksum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' - IF @Version >= 10 - BEGIN - 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 + SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND (@CurrentMaxTransferSize >= 65537 OR (@Version >= 15.0404316 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))))) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END IF @Compress = 'Y' AND @CompressionAlgorithm IS NOT NULL BEGIN @@ -3972,7 +3996,11 @@ BEGIN SET @CurrentCommandType = 'emc_run_backup' - SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.emc_run_backup ''' + SET @CurrentCommand = '' + IF @DataDomainBoostNoOutputTable = 'Y' SET @CurrentCommand += 'DECLARE @DataDomainBoostOutput TABLE ([Message] nvarchar(MAX)); ' + SET @CurrentCommand += 'DECLARE @ReturnCode int; ' + IF @DataDomainBoostNoOutputTable = 'Y' SET @CurrentCommand += 'INSERT INTO @DataDomainBoostOutput ([Message]) ' + SET @CurrentCommand += 'EXECUTE @ReturnCode = dbo.emc_run_backup ''' SET @CurrentCommand += ' -c ' + CASE WHEN @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)) END diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index db57594a..908a91c7 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 18:42:36 //-- + --// Version: 2026-05-30 10:34:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -187,6 +187,11 @@ BEGIN 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 SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' + BEGIN + SET @Version = 16.010006 + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SELECT @HostPlatform = host_platform @@ -243,6 +248,12 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') = 8 + BEGIN + SET @StartMessage = 'Update type: ' + CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') @@ -883,7 +894,7 @@ BEGIN 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 OR SERVERPROPERTY('EngineEdition') = 8) + IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 14.0302916 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) 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 @@ -1675,7 +1686,7 @@ BEGIN 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' + 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) AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL) ORDER BY schemas.name ASC, objects.name ASC' INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, [Order], Selected, Completed) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand @@ -1760,7 +1771,7 @@ BEGIN -- Does the object exist? SET @CurrentCommand = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - 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' + 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) AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL) 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 = @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 diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 5f181838..49ea81a0 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 18:42:36 //-- + --// Version: 2026-05-30 10:34:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -262,6 +262,11 @@ BEGIN 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 SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' + BEGIN + SET @Version = 16.010006 + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SELECT @HostPlatform = host_platform @@ -331,6 +336,12 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') = 8 + BEGIN + SET @StartMessage = 'Update type: ' + CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') @@ -1198,7 +1209,7 @@ BEGIN --// 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 + SET @PartitionLevelStatistics = CASE WHEN @PartitionLevel = 'Y' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Update database order //-- @@ -1572,7 +1583,7 @@ BEGIN + ', objects.[object_id] AS ObjectID' + ', objects.[name] AS ObjectName' + ', RTRIM(objects.[type]) AS ObjectType' - + ', ' + CASE WHEN @Version >= 12 THEN 'ISNULL(tables.is_memory_optimized, 0)' ELSE '0' END + ' AS IsMemoryOptimized' + + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' + ', indexes.index_id AS IndexID' + ', indexes.[name] AS IndexName' + ', indexes.[type] AS IndexType' @@ -1600,12 +1611,12 @@ BEGIN + ' 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 OR SERVERPROPERTY('EngineEdition') IN (5, 8) 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' + CASE WHEN @PartitionLevel = 'Y' THEN ' AND (index_resumable_operations.partition_number = partitions.partition_number OR index_resumable_operations.partition_number IS NULL)' ELSE '' END + ') THEN 1 ELSE 0 END' ELSE '0' END + ' AS ResumableIndexOperation' + + ', 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' + CASE WHEN @PartitionLevel = 'Y' THEN ' AND (index_resumable_operations.partition_number = partitions.partition_number OR index_resumable_operations.partition_number IS NULL)' ELSE '' END + ') THEN 1 ELSE 0 END AS ResumableIndexOperation' + ', stats.stats_id AS StatisticsID' + ', stats.name AS StatisticsName' + ', stats.no_recompute AS NoRecompute' - + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE '0' END + ' AS IsIncremental' + + ', stats.is_incremental 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 @@ -1641,7 +1652,7 @@ BEGIN + ', objects.[object_id] AS ObjectID' + ', objects.[name] AS ObjectName' + ', RTRIM(objects.[type]) AS ObjectType' - + ', ' + CASE WHEN @Version >= 12 THEN 'ISNULL(tables.is_memory_optimized, 0)' ELSE '0' END + ' AS IsMemoryOptimized' + + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' + ', NULL AS IndexID, NULL AS IndexName' + ', NULL AS IndexType' + ', NULL AS AllowPageLocks' @@ -1659,7 +1670,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 '0' END + ' AS IsIncremental' + + ', stats.is_incremental AS IsIncremental' + ', NULL AS PartitionID' + ', ' + CASE WHEN @PartitionLevelStatistics = 1 THEN 'dm_db_incremental_stats_properties.partition_number' ELSE 'NULL' END + ' AS PartitionNumber' + ', NULL AS PartitionCount' @@ -1677,13 +1688,11 @@ BEGIN END SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] IN(''U'',''V'')' - + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR tables.is_memory_optimized IS NULL)' ELSE '' END + + ' AND (tables.is_memory_optimized = 0 OR tables.is_memory_optimized IS NULL)' + 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)' + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes2 WHERE indexes2.[object_id] = stats.[object_id] AND indexes2.type = 1 AND indexes2.is_disabled = 1)' - IF @Version >= 12 - BEGIN SET @CurrentCommand = @CurrentCommand + ' UNION ' SET @CurrentCommand = @CurrentCommand + 'SELECT schemas.[schema_id] AS SchemaID' @@ -1709,7 +1718,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 '0' END + ' AS IsIncremental' + + ', stats.is_incremental AS IsIncremental' + ', NULL AS PartitionID' + ', NULL AS PartitionNumber' + ', NULL AS PartitionCount' @@ -1725,7 +1734,6 @@ BEGIN + ' AND tables.is_memory_optimized = 1' + 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 END SET @CurrentCommand = @CurrentCommand + ') IndexesStatistics' @@ -1967,7 +1975,6 @@ BEGIN 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) - AND NOT (SERVERPROPERTY('EngineEdition') = 8 AND @CurrentDatabaseName IN ('master', 'model')) BEGIN SET @CurrentCommand = '' @@ -2022,18 +2029,12 @@ BEGIN IF SERVERPROPERTY('EngineEdition') IN (3, 5, 8) AND NOT (@CurrentOnReadOnlyFileGroup = 1) AND NOT (@CurrentIsMemoryOptimized = 1) - AND NOT (@CurrentIsPartition = 1 AND @Version < 12) AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1) AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsNewLOB = 1 AND @Version < 11) - AND NOT (@CurrentIndexType = 2 AND @CurrentIsNewLOB = 1 AND @Version < 11) AND NOT (@CurrentIndexType = 3) AND NOT (@CurrentIndexType = 4) - AND NOT (@CurrentIndexType = 5 AND @Version < 15) - AND NOT (@CurrentIndexType = 6 AND @Version < 14) - AND NOT (@CurrentIndexType = 1 AND @CurrentHasNonClusteredColumnstore = 1 AND @Version < 13) - AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @Version < 15) - AND NOT (@CurrentIndexType = 2 AND @CurrentHasNonClusteredColumnstore = 1 AND @Version < 13) + AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) + AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) BEGIN INSERT INTO @CurrentActionsAllowed ([Action]) VALUES ('INDEX_REBUILD_ONLINE') @@ -2083,7 +2084,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 ((@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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL) 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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL)) 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' @@ -2096,13 +2097,6 @@ BEGIN SET @CurrentStatisticsSample = @StatisticsSample SET @CurrentStatisticsResample = @StatisticsResample - -- Memory-optimized tables only supports FULLSCAN and RESAMPLE in SQL Server 2014 - 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' - END - -- Incremental statistics only supports RESAMPLE IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN @@ -2118,12 +2112,12 @@ BEGIN 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 >= 12 AND @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 11 AND @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasNonClusteredColumnstore: ' + CASE WHEN @CurrentHasNonClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasNonClusteredColumnstore = 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' AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 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 + ', ' - IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasNonClusteredColumnstore: ' + CASE WHEN @CurrentHasNonClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasNonClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Resumable = 'Y' SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Resumable = 'Y' AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Resumable = 'Y' SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 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(max)),'N/A') + ', ' SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar(max)),'N/A') @@ -2163,13 +2157,13 @@ BEGIN SELECT 'SORT_IN_TEMPDB = OFF' END - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) AND @CurrentResumableIndexOperation = 0 + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' 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(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END END - IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) AND @CurrentResumableIndexOperation = 0 + IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'ONLINE = OFF' @@ -2193,13 +2187,13 @@ BEGIN SELECT 'PAD_INDEX = ON' END - IF (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END END - IF (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 AND @TimeLimit IS NOT NULL + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'MAX_DURATION = ' + CAST(DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) AS nvarchar(max)) @@ -2266,7 +2260,7 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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 OR SERVERPROPERTY('EngineEdition') IN (5, 8)) + IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.030154 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max)) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 97c199e5..20782b00 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: 2026-05-28 18:42:36 +Version: 2026-05-30 10:34:53 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 18:42:36 //-- + --// Version: 2026-05-30 10:34:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -437,14 +437,15 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @AvailabilityGroups nvarchar(max) = NULL, @Updateability nvarchar(max) = 'ALL', @AdaptiveCompression nvarchar(max) = NULL, -@ModificationLevel int = NULL, +@MinModificationLevel int = NULL, @MinDatabaseSizeForDifferentialBackup int = NULL, -@LogSizeSinceLastLogBackup int = NULL, -@TimeSinceLastLogBackup int = NULL, +@MinLogSizeSinceLastLogBackup int = NULL, +@MinTimeSinceLastLogBackup int = NULL, @DataDomainBoostHost nvarchar(max) = NULL, @DataDomainBoostUser nvarchar(max) = NULL, @DataDomainBoostDevicePath nvarchar(max) = NULL, @DataDomainBoostLockboxPath nvarchar(max) = NULL, +@DataDomainBoostNoOutputTable nvarchar(max) = 'N', @DirectoryStructure nvarchar(max) = '{ServerName}${InstanceName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}', @AvailabilityGroupDirectoryStructure nvarchar(max) = '{ClusterName}${AvailabilityGroupName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}', @DirectoryStructureCase nvarchar(max) = NULL, @@ -478,7 +479,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 18:42:36 //-- + --// Version: 2026-05-30 10:34:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -663,6 +664,11 @@ BEGIN 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 SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' + BEGIN + SET @Version = 16.010006 + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SELECT @HostPlatform = host_platform @@ -725,14 +731,15 @@ BEGIN 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(max)),'NULL') + SET @Parameters += ', @MinModificationLevel = ' + ISNULL(CAST(@MinModificationLevel AS nvarchar(max)),'NULL') SET @Parameters += ', @MinDatabaseSizeForDifferentialBackup = ' + ISNULL(CAST(@MinDatabaseSizeForDifferentialBackup AS nvarchar(max)),'NULL') - SET @Parameters += ', @LogSizeSinceLastLogBackup = ' + ISNULL(CAST(@LogSizeSinceLastLogBackup AS nvarchar(max)),'NULL') - SET @Parameters += ', @TimeSinceLastLogBackup = ' + ISNULL(CAST(@TimeSinceLastLogBackup AS nvarchar(max)),'NULL') + SET @Parameters += ', @MinLogSizeSinceLastLogBackup = ' + ISNULL(CAST(@MinLogSizeSinceLastLogBackup AS nvarchar(max)),'NULL') + SET @Parameters += ', @MinTimeSinceLastLogBackup = ' + ISNULL(CAST(@MinTimeSinceLastLogBackup AS nvarchar(max)),'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 += ', @DataDomainBoostNoOutputTable = ' + ISNULL('''' + REPLACE(@DataDomainBoostNoOutputTable,'''','''''') + '''','NULL') SET @Parameters += ', @DirectoryStructure = ' + ISNULL('''' + REPLACE(@DirectoryStructure,'''','''''') + '''','NULL') SET @Parameters += ', @AvailabilityGroupDirectoryStructure = ' + ISNULL('''' + REPLACE(@AvailabilityGroupDirectoryStructure,'''','''''') + '''','NULL') SET @Parameters += ', @DirectoryStructureCase = ' + ISNULL('''' + REPLACE(@DirectoryStructureCase,'''','''''') + '''','NULL') @@ -770,6 +777,12 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') = 8 + BEGIN + SET @StartMessage = 'Update type: ' + CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') @@ -1124,7 +1137,7 @@ BEGIN IF @Directory IS NULL AND @URL IS NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN - IF @Version >= 15 + IF @Version >= 15 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous') BEGIN SET @DefaultDirectory = CAST(SERVERPROPERTY('InstanceDefaultBackupPath') AS nvarchar(max)) END @@ -1511,7 +1524,7 @@ BEGIN --// Get default compression algorithm //-- ---------------------------------------------------------------------------------------------------- - IF @CompressionAlgorithm IS NULL AND @BackupSoftware IS NULL AND @Version >= 16 + IF @CompressionAlgorithm IS NULL AND @BackupSoftware IS NULL AND (@Version >= 16 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN SELECT @CompressionAlgorithm = CASE WHEN @BackupSoftware IS NULL AND EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression algorithm' AND value_in_use IN (0, 1)) THEN 'MS_XPRESS' WHEN @BackupSoftware IS NULL AND EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression algorithm' AND value_in_use = 2) THEN 'QAT_DEFLATE' @@ -1522,7 +1535,7 @@ BEGIN --// Get default compression level //-- ---------------------------------------------------------------------------------------------------- - IF @CompressionLevel IS NULL AND @BackupSoftware IS NULL AND @Version >= 17 + IF @CompressionLevel IS NULL AND @BackupSoftware IS NULL AND (@Version >= 17 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN SET @CompressionLevel = 'LOW' END @@ -1652,7 +1665,7 @@ BEGIN SELECT 'The value for the parameter @CompressionAlgorithm is not supported. The allowed values are MS_XPRESS, QAT_DEFLATE and ZSTD.', 16, 1 END - IF @CompressionAlgorithm IS NOT NULL AND NOT (@Version >= 16) + IF @CompressionAlgorithm IS NOT NULL AND NOT (@Version >= 16 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Specifying the compression algorithm is only supported in SQL Server 2022 and later.', 16, 2 @@ -1664,7 +1677,7 @@ BEGIN SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to QAT_DEFLATE is only supported in Standard and Enterprise Edition.', 16, 3 END - IF @CompressionAlgorithm = 'ZSTD' AND NOT (@Version >= 17) + IF @CompressionAlgorithm = 'ZSTD' AND NOT (@Version >= 17 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to ZSTD is only supported in SQL Server 2025 and later.', 16, 4 @@ -1690,7 +1703,7 @@ BEGIN SELECT 'The value for the parameter @CompressionLevel is not supported. The supported values are LOW, MEDIUM and HIGH.', 16, 2 END - IF @CompressionLevel IS NOT NULL AND NOT (@Version >= 17) + IF @CompressionLevel IS NOT NULL AND NOT (@Version >= 17 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @CompressionLevel is not supported. Setting the compression level is only supported in SQL Server 2025 and later.', 16, 3 @@ -2317,22 +2330,22 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @ModificationLevel <= 0 OR @ModificationLevel > 100 + IF @MinModificationLevel <= 0 OR @MinModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ModificationLevel is not supported.', 16, 2 + SELECT 'The value for the parameter @MinModificationLevel is not supported.', 16, 2 END - IF @ModificationLevel IS NOT NULL AND @ChangeBackupType = 'N' + IF @MinModificationLevel IS NOT NULL AND @ChangeBackupType = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @ModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 3 + SELECT 'The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 3 END - IF @ModificationLevel IS NOT NULL AND @BackupType <> 'DIFF' + IF @MinModificationLevel IS NOT NULL AND @BackupType <> 'DIFF' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @ModificationLevel can only be used for differential backups.', 16, 4 + SELECT 'The parameter @MinModificationLevel can only be used for differential backups.', 16, 4 END ---------------------------------------------------------------------------------------------------- @@ -2351,26 +2364,26 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @LogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' + IF @MinLogSizeSinceLastLogBackup 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 + SELECT 'The value for the parameter @MinLogSizeSinceLastLogBackup is not supported.', 16, 2 END ---------------------------------------------------------------------------------------------------- - IF @TimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' + IF @MinTimeSinceLastLogBackup 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 + SELECT 'The value for the parameter @MinTimeSinceLastLogBackup is not supported.', 16, 2 END ---------------------------------------------------------------------------------------------------- - IF (@TimeSinceLastLogBackup IS NOT NULL AND @LogSizeSinceLastLogBackup IS NULL) OR (@TimeSinceLastLogBackup IS NULL AND @LogSizeSinceLastLogBackup IS NOT NULL) + IF (@MinTimeSinceLastLogBackup IS NOT NULL AND @MinLogSizeSinceLastLogBackup IS NULL) OR (@MinTimeSinceLastLogBackup IS NULL AND @MinLogSizeSinceLastLogBackup IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameters @TimeSinceLastLogBackup and @LogSizeSinceLastLogBackup can only be used together.', 16, 1 + SELECT 'The parameters @MinTimeSinceLastLogBackup and @MinLogSizeSinceLastLogBackup can only be used together.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -2425,6 +2438,20 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @DataDomainBoostNoOutputTable NOT IN('Y','N') OR @DataDomainBoostNoOutputTable IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 1 + END + + IF @DataDomainBoostNoOutputTable = 'Y' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF @DirectoryStructure = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -3147,7 +3174,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) AND @Credential IS NULL THEN 65537 + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND ((@Version >= 13 AND @Version < 15.0404316) OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) AND @Credential IS NULL THEN 65537 END IF SERVERPROPERTY('IsHadrEnabled') = 1 @@ -3229,7 +3256,7 @@ BEGIN BEGIN SET @CurrentBackupType = 'DIFF' END - IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @ModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) + IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @MinModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) BEGIN SET @CurrentBackupType = 'FULL' END @@ -3414,7 +3441,7 @@ BEGIN 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)) + AND NOT (@CurrentBackupType = 'LOG' AND @MinLogSizeSinceLastLogBackup IS NOT NULL AND @MinTimeSinceLastLogBackup IS NOT NULL AND NOT(@CurrentLogSizeSinceLastLogBackup >= @MinLogSizeSinceLastLogBackup OR @CurrentLogSizeSinceLastLogBackup IS NULL OR DATEDIFF(SECOND,@CurrentLastLogBackup,SYSDATETIME()) >= @MinTimeSinceLastLogBackup OR @CurrentLastLogBackup IS NULL)) AND NOT (@CurrentBackupType = 'LOG' AND @Updateability = 'READ_ONLY' AND @BackupSoftware = 'DATA_DOMAIN_BOOST') AND NOT (@CurrentBackupType = 'DIFF' AND @MinDatabaseSizeForDifferentialBackup IS NOT NULL AND (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) BEGIN -- Start of database backup check @@ -4159,10 +4186,7 @@ BEGIN IF @Checksum = 'Y' SET @CurrentCommand += 'CHECKSUM' IF @Checksum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' - IF @Version >= 10 - BEGIN - 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 + SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND (@CurrentMaxTransferSize >= 65537 OR (@Version >= 15.0404316 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))))) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END IF @Compress = 'Y' AND @CompressionAlgorithm IS NOT NULL BEGIN @@ -4359,7 +4383,11 @@ BEGIN SET @CurrentCommandType = 'emc_run_backup' - SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.emc_run_backup ''' + SET @CurrentCommand = '' + IF @DataDomainBoostNoOutputTable = 'Y' SET @CurrentCommand += 'DECLARE @DataDomainBoostOutput TABLE ([Message] nvarchar(MAX)); ' + SET @CurrentCommand += 'DECLARE @ReturnCode int; ' + IF @DataDomainBoostNoOutputTable = 'Y' SET @CurrentCommand += 'INSERT INTO @DataDomainBoostOutput ([Message]) ' + SET @CurrentCommand += 'EXECUTE @ReturnCode = dbo.emc_run_backup ''' SET @CurrentCommand += ' -c ' + CASE WHEN @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)) END @@ -4792,7 +4820,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 18:42:36 //-- + --// Version: 2026-05-30 10:34:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4939,6 +4967,11 @@ BEGIN 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 SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' + BEGIN + SET @Version = 16.010006 + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SELECT @HostPlatform = host_platform @@ -4995,6 +5028,12 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') = 8 + BEGIN + SET @StartMessage = 'Update type: ' + CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') @@ -5635,7 +5674,7 @@ BEGIN 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 OR SERVERPROPERTY('EngineEdition') = 8) + IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 14.0302916 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) 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 @@ -6427,7 +6466,7 @@ BEGIN 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' + 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) AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL) ORDER BY schemas.name ASC, objects.name ASC' INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, [Order], Selected, Completed) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand @@ -6512,7 +6551,7 @@ BEGIN -- Does the object exist? SET @CurrentCommand = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - 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' + 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) AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL) 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 = @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 @@ -6733,7 +6772,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-28 18:42:36 //-- + --// Version: 2026-05-30 10:34:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6941,6 +6980,11 @@ BEGIN 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 SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' + BEGIN + SET @Version = 16.010006 + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SELECT @HostPlatform = host_platform @@ -7010,6 +7054,12 @@ BEGIN SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + IF SERVERPROPERTY('EngineEdition') = 8 + BEGIN + SET @StartMessage = 'Update type: ' + CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + IF SERVERPROPERTY('EngineEdition') <> 5 BEGIN SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') @@ -7877,7 +7927,7 @@ BEGIN --// 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 + SET @PartitionLevelStatistics = CASE WHEN @PartitionLevel = 'Y' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Update database order //-- @@ -8251,7 +8301,7 @@ BEGIN + ', objects.[object_id] AS ObjectID' + ', objects.[name] AS ObjectName' + ', RTRIM(objects.[type]) AS ObjectType' - + ', ' + CASE WHEN @Version >= 12 THEN 'ISNULL(tables.is_memory_optimized, 0)' ELSE '0' END + ' AS IsMemoryOptimized' + + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' + ', indexes.index_id AS IndexID' + ', indexes.[name] AS IndexName' + ', indexes.[type] AS IndexType' @@ -8279,12 +8329,12 @@ BEGIN + ' 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 OR SERVERPROPERTY('EngineEdition') IN (5, 8) 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' + CASE WHEN @PartitionLevel = 'Y' THEN ' AND (index_resumable_operations.partition_number = partitions.partition_number OR index_resumable_operations.partition_number IS NULL)' ELSE '' END + ') THEN 1 ELSE 0 END' ELSE '0' END + ' AS ResumableIndexOperation' + + ', 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' + CASE WHEN @PartitionLevel = 'Y' THEN ' AND (index_resumable_operations.partition_number = partitions.partition_number OR index_resumable_operations.partition_number IS NULL)' ELSE '' END + ') THEN 1 ELSE 0 END AS ResumableIndexOperation' + ', stats.stats_id AS StatisticsID' + ', stats.name AS StatisticsName' + ', stats.no_recompute AS NoRecompute' - + ', ' + CASE WHEN @Version >= 12 THEN 'stats.is_incremental' ELSE '0' END + ' AS IsIncremental' + + ', stats.is_incremental 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 @@ -8320,7 +8370,7 @@ BEGIN + ', objects.[object_id] AS ObjectID' + ', objects.[name] AS ObjectName' + ', RTRIM(objects.[type]) AS ObjectType' - + ', ' + CASE WHEN @Version >= 12 THEN 'ISNULL(tables.is_memory_optimized, 0)' ELSE '0' END + ' AS IsMemoryOptimized' + + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' + ', NULL AS IndexID, NULL AS IndexName' + ', NULL AS IndexType' + ', NULL AS AllowPageLocks' @@ -8338,7 +8388,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 '0' END + ' AS IsIncremental' + + ', stats.is_incremental AS IsIncremental' + ', NULL AS PartitionID' + ', ' + CASE WHEN @PartitionLevelStatistics = 1 THEN 'dm_db_incremental_stats_properties.partition_number' ELSE 'NULL' END + ' AS PartitionNumber' + ', NULL AS PartitionCount' @@ -8356,13 +8406,11 @@ BEGIN END SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] IN(''U'',''V'')' - + CASE WHEN @Version >= 12 THEN ' AND (tables.is_memory_optimized = 0 OR tables.is_memory_optimized IS NULL)' ELSE '' END + + ' AND (tables.is_memory_optimized = 0 OR tables.is_memory_optimized IS NULL)' + 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)' + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes2 WHERE indexes2.[object_id] = stats.[object_id] AND indexes2.type = 1 AND indexes2.is_disabled = 1)' - IF @Version >= 12 - BEGIN SET @CurrentCommand = @CurrentCommand + ' UNION ' SET @CurrentCommand = @CurrentCommand + 'SELECT schemas.[schema_id] AS SchemaID' @@ -8388,7 +8436,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 '0' END + ' AS IsIncremental' + + ', stats.is_incremental AS IsIncremental' + ', NULL AS PartitionID' + ', NULL AS PartitionNumber' + ', NULL AS PartitionCount' @@ -8404,7 +8452,6 @@ BEGIN + ' AND tables.is_memory_optimized = 1' + 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 END SET @CurrentCommand = @CurrentCommand + ') IndexesStatistics' @@ -8646,7 +8693,6 @@ BEGIN 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) - AND NOT (SERVERPROPERTY('EngineEdition') = 8 AND @CurrentDatabaseName IN ('master', 'model')) BEGIN SET @CurrentCommand = '' @@ -8701,18 +8747,12 @@ BEGIN IF SERVERPROPERTY('EngineEdition') IN (3, 5, 8) AND NOT (@CurrentOnReadOnlyFileGroup = 1) AND NOT (@CurrentIsMemoryOptimized = 1) - AND NOT (@CurrentIsPartition = 1 AND @Version < 12) AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1) AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsNewLOB = 1 AND @Version < 11) - AND NOT (@CurrentIndexType = 2 AND @CurrentIsNewLOB = 1 AND @Version < 11) AND NOT (@CurrentIndexType = 3) AND NOT (@CurrentIndexType = 4) - AND NOT (@CurrentIndexType = 5 AND @Version < 15) - AND NOT (@CurrentIndexType = 6 AND @Version < 14) - AND NOT (@CurrentIndexType = 1 AND @CurrentHasNonClusteredColumnstore = 1 AND @Version < 13) - AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @Version < 15) - AND NOT (@CurrentIndexType = 2 AND @CurrentHasNonClusteredColumnstore = 1 AND @Version < 13) + AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) + AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) BEGIN INSERT INTO @CurrentActionsAllowed ([Action]) VALUES ('INDEX_REBUILD_ONLINE') @@ -8762,7 +8802,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 ((@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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL) 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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL)) 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' @@ -8775,13 +8815,6 @@ BEGIN SET @CurrentStatisticsSample = @StatisticsSample SET @CurrentStatisticsResample = @StatisticsResample - -- Memory-optimized tables only supports FULLSCAN and RESAMPLE in SQL Server 2014 - 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' - END - -- Incremental statistics only supports RESAMPLE IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN @@ -8797,12 +8830,12 @@ BEGIN 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 >= 12 AND @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Version >= 11 AND @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasNonClusteredColumnstore: ' + CASE WHEN @CurrentHasNonClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasNonClusteredColumnstore = 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' AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 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 + ', ' - IF @Version >= 14 AND @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasNonClusteredColumnstore: ' + CASE WHEN @CurrentHasNonClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasNonClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Resumable = 'Y' SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Resumable = 'Y' AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Resumable = 'Y' SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 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(max)),'N/A') + ', ' SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar(max)),'N/A') @@ -8842,13 +8875,13 @@ BEGIN SELECT 'SORT_IN_TEMPDB = OFF' END - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) AND @CurrentResumableIndexOperation = 0 + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' 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(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END END - IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND (@CurrentIsPartition = 0 OR @Version >= 12) AND @CurrentResumableIndexOperation = 0 + IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'ONLINE = OFF' @@ -8872,13 +8905,13 @@ BEGIN SELECT 'PAD_INDEX = ON' END - IF (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END END - IF (@Version >= 14 OR SERVERPROPERTY('EngineEdition') IN (5,8)) AND @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 AND @TimeLimit IS NOT NULL + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'MAX_DURATION = ' + CAST(DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) AS nvarchar(max)) @@ -8945,7 +8978,7 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' 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 OR SERVERPROPERTY('EngineEdition') IN (5, 8)) + IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.030154 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max)) From 6db31aadc580e10f71c2a1f1d75c79f9ab09688d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 30 May 2026 11:14:19 +0200 Subject: [PATCH 021/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 15 +++++++++------ 5 files changed, 13 insertions(+), 10 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index e22ae6ea..afdbfe7f 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: 2026-05-30 10:34:53 //-- + --// Version: 2026-05-30 11:07:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index c9bd6f3d..51a217f8 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -92,7 +92,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 10:34:53 //-- + --// Version: 2026-05-30 11:07:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 908a91c7..aa866eb3 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 10:34:53 //-- + --// Version: 2026-05-30 11:07:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 49ea81a0..f4d33102 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 10:34:53 //-- + --// Version: 2026-05-30 11:07:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 20782b00..d64927f6 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: 2026-05-30 10:34:53 +Version: 2026-05-30 11:07:55 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 10:34:53 //-- + --// Version: 2026-05-30 11:07:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -479,7 +479,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 10:34:53 //-- + --// Version: 2026-05-30 11:07:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4820,7 +4820,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 10:34:53 //-- + --// Version: 2026-05-30 11:07:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6772,7 +6772,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 10:34:53 //-- + --// Version: 2026-05-30 11:07:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -9457,7 +9457,7 @@ DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THE IF @AmazonRDS = 0 BEGIN - DECLARE JobCursor CURSOR FAST_FORWARD FOR SELECT job_id, step_id, command FROM msdb.dbo.sysjobsteps WHERE command LIKE '%DatabaseBackup%@CheckSum%' COLLATE SQL_Latin1_General_CP1_CS_AS + DECLARE JobCursor CURSOR LOCAL FAST_FORWARD FOR SELECT job_id, step_id, command FROM msdb.dbo.sysjobsteps WHERE command LIKE '%DatabaseBackup%@CheckSum%' COLLATE SQL_Latin1_General_CP1_CS_AS OR command LIKE '%DatabaseBackup%@ModificationLevel%' OR command LIKE '%DatabaseBackup%@LogSizeSinceLastLogBackup%' OR command LIKE '%DatabaseBackup%@TimeSinceLastLogBackup%' OPEN JobCursor @@ -9466,6 +9466,9 @@ BEGIN WHILE @@FETCH_STATUS = 0 BEGIN SET @command = REPLACE(@command, '@CheckSum', '@Checksum') + SET @command = REPLACE(@command, '@ModificationLevel', '@MinModificationLevel') + SET @command = REPLACE(@command, '@LogSizeSinceLastLogBackup', '@MinLogSizeSinceLastLogBackup') + SET @command = REPLACE(@command, '@TimeSinceLastLogBackup', '@MinTimeSinceLastLogBackup') EXECUTE msdb.dbo.sp_update_jobstep @job_id = @job_id, @step_id = @step_id, @command = @command From 23e80c86785ff26cb662d9d82d33356278e4bf03 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 30 May 2026 19:59:30 +0200 Subject: [PATCH 022/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 16 +++++++++++++--- MaintenanceSolution.sql | 24 +++++++++++++++++------- 5 files changed, 33 insertions(+), 13 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index afdbfe7f..ca78c4a7 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: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 19:58:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 51a217f8..4efeeca3 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -92,7 +92,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 19:58:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index aa866eb3..48c0fcb0 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 19:58:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index f4d33102..d9ccbb39 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 19:58:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -145,6 +145,7 @@ BEGIN DECLARE @CurrentIsFileStream bit DECLARE @CurrentHasClusteredColumnstore bit DECLARE @CurrentHasNonClusteredColumnstore bit + DECLARE @CurrentIsColumnstoreOrdered bit DECLARE @CurrentIsComputed bit DECLARE @CurrentIsClusteredIndexComputed bit DECLARE @CurrentIsTimestamp bit @@ -202,6 +203,7 @@ BEGIN IsFileStream bit, HasClusteredColumnstore bit, HasNonClusteredColumnstore bit, + IsColumnstoreOrdered bit, IsComputed bit, IsClusteredIndexComputed bit, IsTimestamp bit, @@ -1573,7 +1575,7 @@ BEGIN IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + ' FROM (' IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') @@ -1601,6 +1603,8 @@ BEGIN + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 6) THEN 1 ELSE 0 END AS HasNonClusteredColumnstore' + + ', ' + CASE WHEN (@Version >= 16 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns INNER JOIN sys.indexes indexes2 ON index_columns.[object_id] = indexes2.[object_id] AND index_columns.index_id = indexes2.index_id WHERE indexes2.[object_id] = indexes.[object_id] AND indexes2.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' + + ', 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 OR index_columns.is_included_column = 1) 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.indexes indexes2 ON index_columns.object_id = indexes2.object_id AND index_columns.index_id = indexes2.index_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND indexes2.[type] = 1 AND index_columns.object_id = indexes.object_id) THEN 1 ELSE 0 END AS IsClusteredIndexComputed' @@ -1662,6 +1666,7 @@ BEGIN + ', NULL AS IsFileStream' + ', NULL AS HasClusteredColumnstore' + ', NULL AS HasNonClusteredColumnstore' + + ', NULL AS IsColumnstoreOrdered' + ', NULL AS IsComputed' + ', NULL AS IsClusteredIndexComputed' + ', NULL AS IsTimestamp' @@ -1710,6 +1715,7 @@ BEGIN + ', NULL AS IsFileStream' + ', NULL AS HasClusteredColumnstore' + ', NULL AS HasNonClusteredColumnstore' + + ', NULL AS IsColumnstoreOrdered' + ', NULL AS IsComputed' + ', NULL AS IsClusteredIndexComputed' + ', NULL AS IsTimestamp' @@ -1738,7 +1744,7 @@ BEGIN SET @CurrentCommand = @CurrentCommand + ') IndexesStatistics' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -1844,6 +1850,7 @@ BEGIN @CurrentIsFileStream = IsFileStream, @CurrentHasClusteredColumnstore = HasClusteredColumnstore, @CurrentHasNonClusteredColumnstore = HasNonClusteredColumnstore, + @CurrentIsColumnstoreOrdered = IsColumnstoreOrdered, @CurrentIsComputed = IsComputed, @CurrentIsClusteredIndexComputed = IsClusteredIndexComputed, @CurrentIsTimestamp = IsTimestamp, @@ -2035,6 +2042,7 @@ BEGIN AND NOT (@CurrentIndexType = 4) AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND NOT (@Version >= 17 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) BEGIN INSERT INTO @CurrentActionsAllowed ([Action]) VALUES ('INDEX_REBUILD_ONLINE') @@ -2114,6 +2122,7 @@ BEGIN SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasNonClusteredColumnstore: ' + CASE WHEN @CurrentHasNonClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasNonClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Resumable = 'Y' SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Resumable = 'Y' AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Resumable = 'Y' SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' @@ -2347,6 +2356,7 @@ BEGIN SET @CurrentIsFileStream = NULL SET @CurrentHasClusteredColumnstore = NULL SET @CurrentHasNonClusteredColumnstore = NULL + SET @CurrentIsColumnstoreOrdered = NULL SET @CurrentIsComputed = NULL SET @CurrentIsClusteredIndexComputed = NULL SET @CurrentIsTimestamp = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index d64927f6..d8d8870c 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: 2026-05-30 11:07:55 +Version: 2026-05-30 19:58:39 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 19:58:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -479,7 +479,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 19:58:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4820,7 +4820,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 19:58:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6772,7 +6772,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 19:58:39 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6863,6 +6863,7 @@ BEGIN DECLARE @CurrentIsFileStream bit DECLARE @CurrentHasClusteredColumnstore bit DECLARE @CurrentHasNonClusteredColumnstore bit + DECLARE @CurrentIsColumnstoreOrdered bit DECLARE @CurrentIsComputed bit DECLARE @CurrentIsClusteredIndexComputed bit DECLARE @CurrentIsTimestamp bit @@ -6920,6 +6921,7 @@ BEGIN IsFileStream bit, HasClusteredColumnstore bit, HasNonClusteredColumnstore bit, + IsColumnstoreOrdered bit, IsComputed bit, IsClusteredIndexComputed bit, IsTimestamp bit, @@ -8291,7 +8293,7 @@ BEGIN IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + ' FROM (' IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') @@ -8319,6 +8321,8 @@ BEGIN + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 6) THEN 1 ELSE 0 END AS HasNonClusteredColumnstore' + + ', ' + CASE WHEN (@Version >= 16 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns INNER JOIN sys.indexes indexes2 ON index_columns.[object_id] = indexes2.[object_id] AND index_columns.index_id = indexes2.index_id WHERE indexes2.[object_id] = indexes.[object_id] AND indexes2.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' + + ', 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 OR index_columns.is_included_column = 1) 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.indexes indexes2 ON index_columns.object_id = indexes2.object_id AND index_columns.index_id = indexes2.index_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND indexes2.[type] = 1 AND index_columns.object_id = indexes.object_id) THEN 1 ELSE 0 END AS IsClusteredIndexComputed' @@ -8380,6 +8384,7 @@ BEGIN + ', NULL AS IsFileStream' + ', NULL AS HasClusteredColumnstore' + ', NULL AS HasNonClusteredColumnstore' + + ', NULL AS IsColumnstoreOrdered' + ', NULL AS IsComputed' + ', NULL AS IsClusteredIndexComputed' + ', NULL AS IsTimestamp' @@ -8428,6 +8433,7 @@ BEGIN + ', NULL AS IsFileStream' + ', NULL AS HasClusteredColumnstore' + ', NULL AS HasNonClusteredColumnstore' + + ', NULL AS IsColumnstoreOrdered' + ', NULL AS IsComputed' + ', NULL AS IsClusteredIndexComputed' + ', NULL AS IsTimestamp' @@ -8456,7 +8462,7 @@ BEGIN SET @CurrentCommand = @CurrentCommand + ') IndexesStatistics' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -8562,6 +8568,7 @@ BEGIN @CurrentIsFileStream = IsFileStream, @CurrentHasClusteredColumnstore = HasClusteredColumnstore, @CurrentHasNonClusteredColumnstore = HasNonClusteredColumnstore, + @CurrentIsColumnstoreOrdered = IsColumnstoreOrdered, @CurrentIsComputed = IsComputed, @CurrentIsClusteredIndexComputed = IsClusteredIndexComputed, @CurrentIsTimestamp = IsTimestamp, @@ -8753,6 +8760,7 @@ BEGIN AND NOT (@CurrentIndexType = 4) AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND NOT (@Version >= 17 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) BEGIN INSERT INTO @CurrentActionsAllowed ([Action]) VALUES ('INDEX_REBUILD_ONLINE') @@ -8832,6 +8840,7 @@ BEGIN SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasNonClusteredColumnstore: ' + CASE WHEN @CurrentHasNonClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasNonClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Resumable = 'Y' SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Resumable = 'Y' AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Resumable = 'Y' SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' @@ -9065,6 +9074,7 @@ BEGIN SET @CurrentIsFileStream = NULL SET @CurrentHasClusteredColumnstore = NULL SET @CurrentHasNonClusteredColumnstore = NULL + SET @CurrentIsColumnstoreOrdered = NULL SET @CurrentIsComputed = NULL SET @CurrentIsClusteredIndexComputed = NULL SET @CurrentIsTimestamp = NULL From a3f2ec82349c960b01247d3e959f692b5216598a Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 30 May 2026 20:04:23 +0200 Subject: [PATCH 023/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 16 +++++++++++++--- MaintenanceSolution.sql | 24 +++++++++++++++++------- 5 files changed, 33 insertions(+), 13 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index afdbfe7f..6c80bfc6 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: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 51a217f8..4cf248a5 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -92,7 +92,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index aa866eb3..79b9b0c0 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index f4d33102..35949863 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -145,6 +145,7 @@ BEGIN DECLARE @CurrentIsFileStream bit DECLARE @CurrentHasClusteredColumnstore bit DECLARE @CurrentHasNonClusteredColumnstore bit + DECLARE @CurrentIsColumnstoreOrdered bit DECLARE @CurrentIsComputed bit DECLARE @CurrentIsClusteredIndexComputed bit DECLARE @CurrentIsTimestamp bit @@ -202,6 +203,7 @@ BEGIN IsFileStream bit, HasClusteredColumnstore bit, HasNonClusteredColumnstore bit, + IsColumnstoreOrdered bit, IsComputed bit, IsClusteredIndexComputed bit, IsTimestamp bit, @@ -1573,7 +1575,7 @@ BEGIN IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + ' FROM (' IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') @@ -1601,6 +1603,8 @@ BEGIN + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 6) THEN 1 ELSE 0 END AS HasNonClusteredColumnstore' + + ', ' + CASE WHEN (@Version >= 16 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' + + ', 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 OR index_columns.is_included_column = 1) 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.indexes indexes2 ON index_columns.object_id = indexes2.object_id AND index_columns.index_id = indexes2.index_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND indexes2.[type] = 1 AND index_columns.object_id = indexes.object_id) THEN 1 ELSE 0 END AS IsClusteredIndexComputed' @@ -1662,6 +1666,7 @@ BEGIN + ', NULL AS IsFileStream' + ', NULL AS HasClusteredColumnstore' + ', NULL AS HasNonClusteredColumnstore' + + ', NULL AS IsColumnstoreOrdered' + ', NULL AS IsComputed' + ', NULL AS IsClusteredIndexComputed' + ', NULL AS IsTimestamp' @@ -1710,6 +1715,7 @@ BEGIN + ', NULL AS IsFileStream' + ', NULL AS HasClusteredColumnstore' + ', NULL AS HasNonClusteredColumnstore' + + ', NULL AS IsColumnstoreOrdered' + ', NULL AS IsComputed' + ', NULL AS IsClusteredIndexComputed' + ', NULL AS IsTimestamp' @@ -1738,7 +1744,7 @@ BEGIN SET @CurrentCommand = @CurrentCommand + ') IndexesStatistics' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -1844,6 +1850,7 @@ BEGIN @CurrentIsFileStream = IsFileStream, @CurrentHasClusteredColumnstore = HasClusteredColumnstore, @CurrentHasNonClusteredColumnstore = HasNonClusteredColumnstore, + @CurrentIsColumnstoreOrdered = IsColumnstoreOrdered, @CurrentIsComputed = IsComputed, @CurrentIsClusteredIndexComputed = IsClusteredIndexComputed, @CurrentIsTimestamp = IsTimestamp, @@ -2035,6 +2042,7 @@ BEGIN AND NOT (@CurrentIndexType = 4) AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND NOT (@Version >= 17 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) BEGIN INSERT INTO @CurrentActionsAllowed ([Action]) VALUES ('INDEX_REBUILD_ONLINE') @@ -2114,6 +2122,7 @@ BEGIN SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasNonClusteredColumnstore: ' + CASE WHEN @CurrentHasNonClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasNonClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Resumable = 'Y' SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Resumable = 'Y' AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Resumable = 'Y' SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' @@ -2347,6 +2356,7 @@ BEGIN SET @CurrentIsFileStream = NULL SET @CurrentHasClusteredColumnstore = NULL SET @CurrentHasNonClusteredColumnstore = NULL + SET @CurrentIsColumnstoreOrdered = NULL SET @CurrentIsComputed = NULL SET @CurrentIsClusteredIndexComputed = NULL SET @CurrentIsTimestamp = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index d64927f6..2f6eea49 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: 2026-05-30 11:07:55 +Version: 2026-05-30 20:03:41 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -479,7 +479,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4820,7 +4820,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6772,7 +6772,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 11:07:55 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6863,6 +6863,7 @@ BEGIN DECLARE @CurrentIsFileStream bit DECLARE @CurrentHasClusteredColumnstore bit DECLARE @CurrentHasNonClusteredColumnstore bit + DECLARE @CurrentIsColumnstoreOrdered bit DECLARE @CurrentIsComputed bit DECLARE @CurrentIsClusteredIndexComputed bit DECLARE @CurrentIsTimestamp bit @@ -6920,6 +6921,7 @@ BEGIN IsFileStream bit, HasClusteredColumnstore bit, HasNonClusteredColumnstore bit, + IsColumnstoreOrdered bit, IsComputed bit, IsClusteredIndexComputed bit, IsTimestamp bit, @@ -8291,7 +8293,7 @@ BEGIN IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, NoRecompute, IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed' + ' FROM (' IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') @@ -8319,6 +8321,8 @@ BEGIN + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 6) THEN 1 ELSE 0 END AS HasNonClusteredColumnstore' + + ', ' + CASE WHEN (@Version >= 16 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' + + ', 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 OR index_columns.is_included_column = 1) 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.indexes indexes2 ON index_columns.object_id = indexes2.object_id AND index_columns.index_id = indexes2.index_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND indexes2.[type] = 1 AND index_columns.object_id = indexes.object_id) THEN 1 ELSE 0 END AS IsClusteredIndexComputed' @@ -8380,6 +8384,7 @@ BEGIN + ', NULL AS IsFileStream' + ', NULL AS HasClusteredColumnstore' + ', NULL AS HasNonClusteredColumnstore' + + ', NULL AS IsColumnstoreOrdered' + ', NULL AS IsComputed' + ', NULL AS IsClusteredIndexComputed' + ', NULL AS IsTimestamp' @@ -8428,6 +8433,7 @@ BEGIN + ', NULL AS IsFileStream' + ', NULL AS HasClusteredColumnstore' + ', NULL AS HasNonClusteredColumnstore' + + ', NULL AS IsColumnstoreOrdered' + ', NULL AS IsComputed' + ', NULL AS IsClusteredIndexComputed' + ', NULL AS IsTimestamp' @@ -8456,7 +8462,7 @@ BEGIN SET @CurrentCommand = @CurrentCommand + ') IndexesStatistics' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -8562,6 +8568,7 @@ BEGIN @CurrentIsFileStream = IsFileStream, @CurrentHasClusteredColumnstore = HasClusteredColumnstore, @CurrentHasNonClusteredColumnstore = HasNonClusteredColumnstore, + @CurrentIsColumnstoreOrdered = IsColumnstoreOrdered, @CurrentIsComputed = IsComputed, @CurrentIsClusteredIndexComputed = IsClusteredIndexComputed, @CurrentIsTimestamp = IsTimestamp, @@ -8753,6 +8760,7 @@ BEGIN AND NOT (@CurrentIndexType = 4) AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND NOT (@Version >= 17 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) BEGIN INSERT INTO @CurrentActionsAllowed ([Action]) VALUES ('INDEX_REBUILD_ONLINE') @@ -8832,6 +8840,7 @@ BEGIN SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasNonClusteredColumnstore: ' + CASE WHEN @CurrentHasNonClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasNonClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Resumable = 'Y' SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Resumable = 'Y' AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Resumable = 'Y' SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' @@ -9065,6 +9074,7 @@ BEGIN SET @CurrentIsFileStream = NULL SET @CurrentHasClusteredColumnstore = NULL SET @CurrentHasNonClusteredColumnstore = NULL + SET @CurrentIsColumnstoreOrdered = NULL SET @CurrentIsComputed = NULL SET @CurrentIsClusteredIndexComputed = NULL SET @CurrentIsTimestamp = NULL From 2777c500179e07d34808ea72ade2dd9addb28752 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 30 May 2026 20:05:03 +0200 Subject: [PATCH 024/177] 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 ca78c4a7..6c80bfc6 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: 2026-05-30 19:58:39 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 4efeeca3..4cf248a5 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -92,7 +92,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 19:58:39 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 48c0fcb0..79b9b0c0 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 19:58:39 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index d9ccbb39..35949863 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 19:58:39 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1603,7 +1603,7 @@ BEGIN + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 6) THEN 1 ELSE 0 END AS HasNonClusteredColumnstore' - + ', ' + CASE WHEN (@Version >= 16 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns INNER JOIN sys.indexes indexes2 ON index_columns.[object_id] = indexes2.[object_id] AND index_columns.index_id = indexes2.index_id WHERE indexes2.[object_id] = indexes.[object_id] AND indexes2.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' + + ', ' + CASE WHEN (@Version >= 16 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' + ', 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 OR index_columns.is_included_column = 1) 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' diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index d8d8870c..2f6eea49 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: 2026-05-30 19:58:39 +Version: 2026-05-30 20:03:41 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 19:58:39 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -479,7 +479,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 19:58:39 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4820,7 +4820,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 19:58:39 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6772,7 +6772,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 19:58:39 //-- + --// Version: 2026-05-30 20:03:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8321,7 +8321,7 @@ BEGIN + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 6) THEN 1 ELSE 0 END AS HasNonClusteredColumnstore' - + ', ' + CASE WHEN (@Version >= 16 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns INNER JOIN sys.indexes indexes2 ON index_columns.[object_id] = indexes2.[object_id] AND index_columns.index_id = indexes2.index_id WHERE indexes2.[object_id] = indexes.[object_id] AND indexes2.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' + + ', ' + CASE WHEN (@Version >= 16 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' + ', 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 OR index_columns.is_included_column = 1) 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' From 6f52ba2ba6ad048da8ac128dd9fc27535dbd0127 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 30 May 2026 22:58:52 +0200 Subject: [PATCH 025/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 13 ++++++++++++- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 21 ++++++++++++++++----- 5 files changed, 31 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 6c80bfc6..26ad1d29 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: 2026-05-30 20:03:41 //-- + --// Version: 2026-05-30 22:05:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 4cf248a5..9dfb736e 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -78,6 +78,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @Stats int = NULL, @ExpireDate datetime = NULL, @RetainDays int = NULL, +@AllowNonCopyOnlyBackupsOnForwarder nvarchar(max) = 'N', @StringDelimiter nvarchar(max) = ',', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @@ -92,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 20:03:41 //-- + --// Version: 2026-05-30 22:05:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -372,6 +373,7 @@ BEGIN SET @Parameters += ', @Stats = ' + ISNULL(CAST(@Stats AS nvarchar(max)),'NULL') SET @Parameters += ', @ExpireDate = ' + ISNULL('''' + CONVERT(nvarchar(max), @ExpireDate, 21) + '''','NULL') SET @Parameters += ', @RetainDays = ' + ISNULL(CAST(@RetainDays AS nvarchar(max)),'NULL') + SET @Parameters += ', @AllowNonCopyOnlyBackupsOnForwarder = ' + ISNULL('''' + REPLACE(@AllowNonCopyOnlyBackupsOnForwarder,'''','''''') + '''','NULL') SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') @@ -2363,6 +2365,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @AllowNonCopyOnlyBackupsOnForwarder NOT IN('Y','N') OR @AllowNonCopyOnlyBackupsOnForwarder IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AllowNonCopyOnlyBackupsOnForwarder is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -3051,6 +3061,7 @@ BEGIN AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) + AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND @AllowNonCopyOnlyBackupsOnForwarder = 'N' AND NOT (@CurrentBackupType = 'FULL' AND @CopyOnly = 'Y')) 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') diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 79b9b0c0..5b839e2c 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 20:03:41 //-- + --// Version: 2026-05-30 22:05:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 35949863..09de034d 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 20:03:41 //-- + --// Version: 2026-05-30 22:05:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 2f6eea49..bd31026c 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: 2026-05-30 20:03:41 +Version: 2026-05-30 22:05:44 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 20:03:41 //-- + --// Version: 2026-05-30 22:05:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -465,6 +465,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @Stats int = NULL, @ExpireDate datetime = NULL, @RetainDays int = NULL, +@AllowNonCopyOnlyBackupsOnForwarder nvarchar(max) = 'N', @StringDelimiter nvarchar(max) = ',', @DatabaseOrder nvarchar(max) = NULL, @DatabasesInParallel nvarchar(max) = 'N', @@ -479,7 +480,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 20:03:41 //-- + --// Version: 2026-05-30 22:05:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -759,6 +760,7 @@ BEGIN SET @Parameters += ', @Stats = ' + ISNULL(CAST(@Stats AS nvarchar(max)),'NULL') SET @Parameters += ', @ExpireDate = ' + ISNULL('''' + CONVERT(nvarchar(max), @ExpireDate, 21) + '''','NULL') SET @Parameters += ', @RetainDays = ' + ISNULL(CAST(@RetainDays AS nvarchar(max)),'NULL') + SET @Parameters += ', @AllowNonCopyOnlyBackupsOnForwarder = ' + ISNULL('''' + REPLACE(@AllowNonCopyOnlyBackupsOnForwarder,'''','''''') + '''','NULL') SET @Parameters += ', @StringDelimiter = ' + ISNULL('''' + REPLACE(@StringDelimiter,'''','''''') + '''','NULL') SET @Parameters += ', @DatabaseOrder = ' + ISNULL('''' + REPLACE(@DatabaseOrder,'''','''''') + '''','NULL') SET @Parameters += ', @DatabasesInParallel = ' + ISNULL('''' + REPLACE(@DatabasesInParallel,'''','''''') + '''','NULL') @@ -2750,6 +2752,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @AllowNonCopyOnlyBackupsOnForwarder NOT IN('Y','N') OR @AllowNonCopyOnlyBackupsOnForwarder IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @AllowNonCopyOnlyBackupsOnForwarder is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -3438,6 +3448,7 @@ BEGIN AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) + AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND @AllowNonCopyOnlyBackupsOnForwarder = 'N' AND NOT (@CurrentBackupType = 'FULL' AND @CopyOnly = 'Y')) 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') @@ -4820,7 +4831,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 20:03:41 //-- + --// Version: 2026-05-30 22:05:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6772,7 +6783,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 20:03:41 //-- + --// Version: 2026-05-30 22:05:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 9ee83cc4b49fe4a996c51e01bd0a6fc3c64ac10c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 31 May 2026 13:47:53 +0200 Subject: [PATCH 026/177] 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 26ad1d29..d3d5de16 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: 2026-05-30 22:05:44 //-- + --// Version: 2026-05-31 13:47:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 9dfb736e..d47fba17 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 22:05:44 //-- + --// Version: 2026-05-31 13:47:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -151,7 +151,7 @@ BEGIN DECLARE @CurrentDatabaseNameFS nvarchar(max) DECLARE @CurrentDirectoryStructure nvarchar(max) DECLARE @CurrentDatabaseFileName nvarchar(max) - DECLARE @CurrentMaxFilePathLength nvarchar(max) + DECLARE @CurrentMaxFilePathLength int DECLARE @CurrentFileName nvarchar(max) DECLARE @CurrentDirectoryID int DECLARE @CurrentDirectoryPath nvarchar(4000) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 5b839e2c..4f5c94f1 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 22:05:44 //-- + --// Version: 2026-05-31 13:47:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 09de034d..30443aca 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 22:05:44 //-- + --// Version: 2026-05-31 13:47:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index bd31026c..258f07fa 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: 2026-05-30 22:05:44 +Version: 2026-05-31 13:47:17 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 22:05:44 //-- + --// Version: 2026-05-31 13:47:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -480,7 +480,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 22:05:44 //-- + --// Version: 2026-05-31 13:47:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -538,7 +538,7 @@ BEGIN DECLARE @CurrentDatabaseNameFS nvarchar(max) DECLARE @CurrentDirectoryStructure nvarchar(max) DECLARE @CurrentDatabaseFileName nvarchar(max) - DECLARE @CurrentMaxFilePathLength nvarchar(max) + DECLARE @CurrentMaxFilePathLength int DECLARE @CurrentFileName nvarchar(max) DECLARE @CurrentDirectoryID int DECLARE @CurrentDirectoryPath nvarchar(4000) @@ -4831,7 +4831,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 22:05:44 //-- + --// Version: 2026-05-31 13:47:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6783,7 +6783,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-30 22:05:44 //-- + --// Version: 2026-05-31 13:47:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 4577eacc6dc3656cd092f861e103b0b0db8e703a Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 31 May 2026 18:33:02 +0200 Subject: [PATCH 027/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 11 ++++------- DatabaseIntegrityCheck.sql | 7 ++----- IndexOptimize.sql | 11 ++++------- MaintenanceSolution.sql | 33 ++++++++++++--------------------- 5 files changed, 23 insertions(+), 41 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index d3d5de16..461ed8ee 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: 2026-05-31 13:47:17 //-- + --// Version: 2026-05-31 16:59:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index d47fba17..7c88051e 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-31 13:47:17 //-- + --// Version: 2026-05-31 16:59:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -166,7 +166,6 @@ BEGIN DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState nvarchar(max) DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) - DECLARE @CurrentDistributedAvailabilityGroupID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) @@ -2834,8 +2833,7 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN - SELECT @CurrentDistributedAvailabilityGroupID = availability_groups.group_id, - @CurrentDistributedAvailabilityGroup = availability_groups.[name], + SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id FROM sys.availability_groups availability_groups INNER JOIN sys.availability_replicas availability_replicas ON availability_groups.group_id = availability_replicas.group_id @@ -3270,7 +3268,7 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Weekday}',DATENAME(WEEKDAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Weekday}',FORMAT(CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END,'dddd','en-US')) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) @@ -3434,7 +3432,7 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Weekday}',DATENAME(WEEKDAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Weekday}',FORMAT(CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END,'dddd','en-US')) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) @@ -4356,7 +4354,6 @@ BEGIN SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL SET @CurrentIsPreferredBackupReplica = NULL - SET @CurrentDistributedAvailabilityGroupID = NULL SET @CurrentDistributedAvailabilityGroup = NULL SET @CurrentDistributedAvailabilityGroupReplicaID = NULL SET @CurrentDistributedAvailabilityGroupRole = NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 4f5c94f1..6869a934 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-31 13:47:17 //-- + --// Version: 2026-05-31 16:59:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -81,7 +81,6 @@ BEGIN DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) DECLARE @CurrentSecondaryRoleAllowConnections nvarchar(max) DECLARE @CurrentIsPreferredBackupReplica bit - DECLARE @CurrentDistributedAvailabilityGroupID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) @@ -1413,8 +1412,7 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN - SELECT @CurrentDistributedAvailabilityGroupID = availability_groups.group_id, - @CurrentDistributedAvailabilityGroup = availability_groups.[name], + SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id FROM sys.availability_groups availability_groups INNER JOIN sys.availability_replicas availability_replicas ON availability_groups.group_id = availability_replicas.group_id @@ -1900,7 +1898,6 @@ BEGIN SET @CurrentAvailabilityGroupBackupPreference = NULL SET @CurrentSecondaryRoleAllowConnections = NULL SET @CurrentIsPreferredBackupReplica = NULL - SET @CurrentDistributedAvailabilityGroupID = NULL SET @CurrentDistributedAvailabilityGroup = NULL SET @CurrentDistributedAvailabilityGroupReplicaID = NULL SET @CurrentDistributedAvailabilityGroupRole = NULL diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 30443aca..37ffb447 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-31 13:47:17 //-- + --// Version: 2026-05-31 16:59:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -99,7 +99,6 @@ BEGIN DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) - DECLARE @CurrentDistributedAvailabilityGroupID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) @@ -1489,8 +1488,7 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN - SELECT @CurrentDistributedAvailabilityGroupID = availability_groups.group_id, - @CurrentDistributedAvailabilityGroup = availability_groups.[name], + SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id FROM sys.availability_groups availability_groups INNER JOIN sys.availability_replicas availability_replicas ON availability_groups.group_id = availability_replicas.group_id @@ -2226,7 +2224,7 @@ BEGIN FROM @CurrentAlterIndexWithClauseArguments END - 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 + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 @@ -2307,7 +2305,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, @ExecuteAsUser = @ExecuteAsUser, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 @@ -2427,7 +2425,6 @@ BEGIN SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL - SET @CurrentDistributedAvailabilityGroupID = NULL SET @CurrentDistributedAvailabilityGroup = NULL SET @CurrentDistributedAvailabilityGroupReplicaID = NULL SET @CurrentDistributedAvailabilityGroupRole = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 258f07fa..3877ccd3 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: 2026-05-31 13:47:17 +Version: 2026-05-31 16:59:43 You can contact me by e-mail at ola@hallengren.com. @@ -137,7 +137,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-31 13:47:17 //-- + --// Version: 2026-05-31 16:59:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -480,7 +480,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-31 13:47:17 //-- + --// Version: 2026-05-31 16:59:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -553,7 +553,6 @@ BEGIN DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState nvarchar(max) DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) - DECLARE @CurrentDistributedAvailabilityGroupID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) @@ -3221,8 +3220,7 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN - SELECT @CurrentDistributedAvailabilityGroupID = availability_groups.group_id, - @CurrentDistributedAvailabilityGroup = availability_groups.[name], + SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id FROM sys.availability_groups availability_groups INNER JOIN sys.availability_replicas availability_replicas ON availability_groups.group_id = availability_replicas.group_id @@ -3657,7 +3655,7 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Weekday}',DATENAME(WEEKDAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END)) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Weekday}',FORMAT(CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END,'dddd','en-US')) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) @@ -3821,7 +3819,7 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Month}',RIGHT('0' + CAST(DATEPART(MONTH,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Day}',RIGHT('0' + CAST(DATEPART(DAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Week}',RIGHT('0' + CAST(DATEPART(WEEK,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Weekday}',DATENAME(WEEKDAY,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END)) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Weekday}',FORMAT(CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END,'dddd','en-US')) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Hour}',RIGHT('0' + CAST(DATEPART(HOUR,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Minute}',RIGHT('0' + CAST(DATEPART(MINUTE,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) @@ -4743,7 +4741,6 @@ BEGIN SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL SET @CurrentIsPreferredBackupReplica = NULL - SET @CurrentDistributedAvailabilityGroupID = NULL SET @CurrentDistributedAvailabilityGroup = NULL SET @CurrentDistributedAvailabilityGroupReplicaID = NULL SET @CurrentDistributedAvailabilityGroupRole = NULL @@ -4831,7 +4828,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-31 13:47:17 //-- + --// Version: 2026-05-31 16:59:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4872,7 +4869,6 @@ BEGIN DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) DECLARE @CurrentSecondaryRoleAllowConnections nvarchar(max) DECLARE @CurrentIsPreferredBackupReplica bit - DECLARE @CurrentDistributedAvailabilityGroupID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) @@ -6204,8 +6200,7 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN - SELECT @CurrentDistributedAvailabilityGroupID = availability_groups.group_id, - @CurrentDistributedAvailabilityGroup = availability_groups.[name], + SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id FROM sys.availability_groups availability_groups INNER JOIN sys.availability_replicas availability_replicas ON availability_groups.group_id = availability_replicas.group_id @@ -6691,7 +6686,6 @@ BEGIN SET @CurrentAvailabilityGroupBackupPreference = NULL SET @CurrentSecondaryRoleAllowConnections = NULL SET @CurrentIsPreferredBackupReplica = NULL - SET @CurrentDistributedAvailabilityGroupID = NULL SET @CurrentDistributedAvailabilityGroup = NULL SET @CurrentDistributedAvailabilityGroupReplicaID = NULL SET @CurrentDistributedAvailabilityGroupRole = NULL @@ -6783,7 +6777,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-31 13:47:17 //-- + --// Version: 2026-05-31 16:59:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6828,7 +6822,6 @@ BEGIN DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) - DECLARE @CurrentDistributedAvailabilityGroupID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) @@ -8218,8 +8211,7 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN - SELECT @CurrentDistributedAvailabilityGroupID = availability_groups.group_id, - @CurrentDistributedAvailabilityGroup = availability_groups.[name], + SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id FROM sys.availability_groups availability_groups INNER JOIN sys.availability_replicas availability_replicas ON availability_groups.group_id = availability_replicas.group_id @@ -8955,7 +8947,7 @@ BEGIN FROM @CurrentAlterIndexWithClauseArguments END - 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 + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 @@ -9036,7 +9028,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, @ExecuteAsUser = @ExecuteAsUser, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 @@ -9156,7 +9148,6 @@ BEGIN SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL - SET @CurrentDistributedAvailabilityGroupID = NULL SET @CurrentDistributedAvailabilityGroup = NULL SET @CurrentDistributedAvailabilityGroupReplicaID = NULL SET @CurrentDistributedAvailabilityGroupRole = NULL From 12847834953326b504966b443205031b6cf6e08f Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 31 May 2026 19:15:11 +0200 Subject: [PATCH 028/177] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 83d5ceeb..497a862c 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 2008, SQL Server 2008 R2, SQL Server 2012, SQL Server 2014, SQL Server 2016, SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, Azure SQL Database, and Azure SQL Managed Instance +Supported versions: SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, Azure SQL Database, and Azure SQL Managed Instance ## Documentation From 0575371c1d31549bd47d6105e217e1ea6c296578 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 6 Jun 2026 09:50:41 +0200 Subject: [PATCH 029/177] Add files via upload --- CommandExecute.sql | 24 +++++++++++++-- DatabaseBackup.sql | 32 +++++++++++--------- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 62 ++++++++++++++++++++++++++------------ 5 files changed, 83 insertions(+), 39 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 461ed8ee..88339541 100644 --- a/CommandExecute.sql +++ b/CommandExecute.sql @@ -22,6 +22,8 @@ ALTER PROCEDURE [dbo].[CommandExecute] @IndexType int = NULL, @StatisticsName nvarchar(max) = NULL, @PartitionNumber int = NULL, +@EncryptionKey nvarchar(max) = NULL, +@EncryptionKeyPlaceholder nvarchar(max) = NULL, @ExtendedInfo xml = NULL, @LockMessageSeverity int = 16, @ExecuteAsUser nvarchar(max) = NULL, @@ -36,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: 2026-05-31 16:59:43 //-- + --// Version: 2026-06-06 10:32:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -70,6 +72,8 @@ BEGIN DECLARE @RevertCommand nvarchar(max) + DECLARE @CommandMasked nvarchar(max) + ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- @@ -120,6 +124,12 @@ BEGIN SELECT 'The value for the parameter @Mode is not supported.', 16, 1 END + IF (@EncryptionKey IS NULL AND @EncryptionKeyPlaceholder IS NOT NULL) OR (@EncryptionKey IS NOT NULL AND @EncryptionKeyPlaceholder IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameters @EncryptionKey and @EncryptionKeyPlaceholder must be specified together.', 16, 1 + END + IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -183,6 +193,14 @@ BEGIN SET @RevertCommand = 'REVERT' END + ---------------------------------------------------------------------------------------------------- + --// Mask encryption key //-- + ---------------------------------------------------------------------------------------------------- + + SET @CommandMasked = CASE WHEN @EncryptionKeyPlaceholder IS NULL THEN @Command ELSE REPLACE(@Command,@EncryptionKeyPlaceholder,'********') END + + SET @Command = CASE WHEN @EncryptionKeyPlaceholder IS NULL THEN @Command ELSE REPLACE(@Command,@EncryptionKeyPlaceholder,REPLACE(ISNULL(@EncryptionKey,''),'''','''''')) END + ---------------------------------------------------------------------------------------------------- --// Log initial information //-- ---------------------------------------------------------------------------------------------------- @@ -195,7 +213,7 @@ BEGIN SET @StartMessage = 'Database context: ' + QUOTENAME(@DatabaseContext) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Command: ' + @Command + SET @StartMessage = 'Command: ' + @CommandMasked RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT IF @Comment IS NOT NULL @@ -207,7 +225,7 @@ BEGIN IF @LogToTable = 'Y' BEGIN INSERT INTO dbo.CommandLog (DatabaseName, SchemaName, ObjectName, ObjectType, IndexName, IndexType, StatisticsName, PartitionNumber, ExtendedInfo, CommandType, Command, StartTime) - VALUES (@DatabaseName, @SchemaName, @ObjectName, @ObjectType, @IndexName, @IndexType, @StatisticsName, @PartitionNumber, @ExtendedInfo, @CommandType, @Command, @StartTime) + VALUES (@DatabaseName, @SchemaName, @ObjectName, @ObjectType, @IndexName, @IndexType, @StatisticsName, @PartitionNumber, @ExtendedInfo, @CommandType, @CommandMasked, @StartTime) END SET @ID = SCOPE_IDENTITY() diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 7c88051e..2439ab7e 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-31 16:59:43 //-- + --// Version: 2026-06-06 10:32:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -270,6 +270,10 @@ BEGIN CleanupDate datetime2, Mirror bit) + DECLARE @EncryptionKeyMasked nvarchar(max) = CASE WHEN @EncryptionKey IS NULL THEN NULL ELSE '********' END + + DECLARE @EncryptionKeyPlaceholder nvarchar(max) = CASE WHEN @EncryptionKey IS NULL THEN NULL ELSE CAST(NEWID() AS nvarchar(max)) END + DECLARE @Error int = 0 DECLARE @ReturnCode int = 0 @@ -331,7 +335,7 @@ BEGIN 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 += ', @EncryptionKey = ' + ISNULL('''' + @EncryptionKeyMasked + '''','NULL') SET @Parameters += ', @ReadWriteFileGroups = ' + ISNULL('''' + REPLACE(@ReadWriteFileGroups,'''','''''') + '''','NULL') SET @Parameters += ', @OverrideBackupPreference = ' + ISNULL('''' + REPLACE(@OverrideBackupPreference,'''','''''') + '''','NULL') SET @Parameters += ', @NoRecovery = ' + ISNULL('''' + REPLACE(@NoRecovery,'''','''''') + '''','NULL') @@ -445,7 +449,7 @@ BEGIN 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%') + 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 '%@EncryptionKeyPlaceholder%') BEGIN 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 @@ -3734,7 +3738,7 @@ BEGIN 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(max)) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL 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(max)) + 'h'', ' + ISNULL('''' + @EncryptionKeyPlaceholder + '''','NULL') + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' @@ -3746,7 +3750,7 @@ BEGIN 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(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @EncryptionKey = @EncryptionKey, @EncryptionKeyPlaceholder = @EncryptionKeyPlaceholder, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput = @Error IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput @@ -3903,7 +3907,7 @@ BEGIN WHEN @EncryptionAlgorithm = 'AES_256' THEN '8' END - IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptionkey = N''' + @EncryptionKeyPlaceholder + '''' SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing LiteSpeed backup.'', 16, 1)' END @@ -3951,7 +3955,7 @@ BEGIN WHEN @EncryptionAlgorithm = 'AES_256' THEN '256' END - IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', PASSWORD = N''' + @EncryptionKeyPlaceholder + '''' SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand,'''','''''') + '"''' + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing SQLBackup backup.'', 16, 1)' END @@ -3995,7 +3999,7 @@ BEGIN WHEN @EncryptionAlgorithm = 'AES_256' THEN 'AES256' END + '''' - IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptedbackuppassword = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptedbackuppassword = N''' + @EncryptionKeyPlaceholder + '''' SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' END @@ -4051,7 +4055,7 @@ BEGIN SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' END - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @EncryptionKey = @EncryptionKey, @EncryptionKeyPlaceholder = @EncryptionKeyPlaceholder, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput = @Error IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput @@ -4112,7 +4116,7 @@ BEGIN 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,'''','''''') + '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptionkey = N''' + @EncryptionKeyPlaceholder + '''' SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error verifying LiteSpeed backup.'', 16, 1)' END @@ -4133,7 +4137,7 @@ BEGIN 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,'''','''''') + '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', PASSWORD = N''' + @EncryptionKeyPlaceholder + '''' SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand,'''','''''') + '"''' + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error verifying SQLBackup backup.'', 16, 1)' END @@ -4159,7 +4163,7 @@ BEGIN SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' END - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @EncryptionKey = @EncryptionKey, @EncryptionKeyPlaceholder = @EncryptionKeyPlaceholder, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput = @Error IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput @@ -4257,7 +4261,7 @@ BEGIN 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(max)) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL 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(max)) + 'h'', ' + ISNULL('''' + @EncryptionKeyPlaceholder + '''','NULL') + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' @@ -4269,7 +4273,7 @@ BEGIN 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(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @EncryptionKey = @EncryptionKey, @EncryptionKeyPlaceholder = @EncryptionKeyPlaceholder, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput = @Error IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 6869a934..79779c46 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-31 16:59:43 //-- + --// Version: 2026-06-06 10:32:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 37ffb447..e0560507 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-31 16:59:43 //-- + --// Version: 2026-06-06 10:32:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 3877ccd3..155f2756 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: 2026-05-31 16:59:43 +Version: 2026-06-06 10:32:46 You can contact me by e-mail at ola@hallengren.com. @@ -123,6 +123,8 @@ ALTER PROCEDURE [dbo].[CommandExecute] @IndexType int = NULL, @StatisticsName nvarchar(max) = NULL, @PartitionNumber int = NULL, +@EncryptionKey nvarchar(max) = NULL, +@EncryptionKeyPlaceholder nvarchar(max) = NULL, @ExtendedInfo xml = NULL, @LockMessageSeverity int = 16, @ExecuteAsUser nvarchar(max) = NULL, @@ -137,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-31 16:59:43 //-- + --// Version: 2026-06-06 10:32:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -171,6 +173,8 @@ BEGIN DECLARE @RevertCommand nvarchar(max) + DECLARE @CommandMasked nvarchar(max) + ---------------------------------------------------------------------------------------------------- --// Check core requirements //-- ---------------------------------------------------------------------------------------------------- @@ -221,6 +225,12 @@ BEGIN SELECT 'The value for the parameter @Mode is not supported.', 16, 1 END + IF (@EncryptionKey IS NULL AND @EncryptionKeyPlaceholder IS NOT NULL) OR (@EncryptionKey IS NOT NULL AND @EncryptionKeyPlaceholder IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameters @EncryptionKey and @EncryptionKeyPlaceholder must be specified together.', 16, 1 + END + IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -284,6 +294,14 @@ BEGIN SET @RevertCommand = 'REVERT' END + ---------------------------------------------------------------------------------------------------- + --// Mask encryption key //-- + ---------------------------------------------------------------------------------------------------- + + SET @CommandMasked = CASE WHEN @EncryptionKeyPlaceholder IS NULL THEN @Command ELSE REPLACE(@Command,@EncryptionKeyPlaceholder,'********') END + + SET @Command = CASE WHEN @EncryptionKeyPlaceholder IS NULL THEN @Command ELSE REPLACE(@Command,@EncryptionKeyPlaceholder,REPLACE(ISNULL(@EncryptionKey,''),'''','''''')) END + ---------------------------------------------------------------------------------------------------- --// Log initial information //-- ---------------------------------------------------------------------------------------------------- @@ -296,7 +314,7 @@ BEGIN SET @StartMessage = 'Database context: ' + QUOTENAME(@DatabaseContext) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Command: ' + @Command + SET @StartMessage = 'Command: ' + @CommandMasked RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT IF @Comment IS NOT NULL @@ -308,7 +326,7 @@ BEGIN IF @LogToTable = 'Y' BEGIN INSERT INTO dbo.CommandLog (DatabaseName, SchemaName, ObjectName, ObjectType, IndexName, IndexType, StatisticsName, PartitionNumber, ExtendedInfo, CommandType, Command, StartTime) - VALUES (@DatabaseName, @SchemaName, @ObjectName, @ObjectType, @IndexName, @IndexType, @StatisticsName, @PartitionNumber, @ExtendedInfo, @CommandType, @Command, @StartTime) + VALUES (@DatabaseName, @SchemaName, @ObjectName, @ObjectType, @IndexName, @IndexType, @StatisticsName, @PartitionNumber, @ExtendedInfo, @CommandType, @CommandMasked, @StartTime) END SET @ID = SCOPE_IDENTITY() @@ -480,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-31 16:59:43 //-- + --// Version: 2026-06-06 10:32:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -657,6 +675,10 @@ BEGIN CleanupDate datetime2, Mirror bit) + DECLARE @EncryptionKeyMasked nvarchar(max) = CASE WHEN @EncryptionKey IS NULL THEN NULL ELSE '********' END + + DECLARE @EncryptionKeyPlaceholder nvarchar(max) = CASE WHEN @EncryptionKey IS NULL THEN NULL ELSE CAST(NEWID() AS nvarchar(max)) END + DECLARE @Error int = 0 DECLARE @ReturnCode int = 0 @@ -718,7 +740,7 @@ BEGIN 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 += ', @EncryptionKey = ' + ISNULL('''' + @EncryptionKeyMasked + '''','NULL') SET @Parameters += ', @ReadWriteFileGroups = ' + ISNULL('''' + REPLACE(@ReadWriteFileGroups,'''','''''') + '''','NULL') SET @Parameters += ', @OverrideBackupPreference = ' + ISNULL('''' + REPLACE(@OverrideBackupPreference,'''','''''') + '''','NULL') SET @Parameters += ', @NoRecovery = ' + ISNULL('''' + REPLACE(@NoRecovery,'''','''''') + '''','NULL') @@ -832,7 +854,7 @@ BEGIN 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%') + 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 '%@EncryptionKeyPlaceholder%') BEGIN 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 @@ -4121,7 +4143,7 @@ BEGIN 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(max)) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL 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(max)) + 'h'', ' + ISNULL('''' + @EncryptionKeyPlaceholder + '''','NULL') + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' @@ -4133,7 +4155,7 @@ BEGIN 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(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @EncryptionKey = @EncryptionKey, @EncryptionKeyPlaceholder = @EncryptionKeyPlaceholder, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput = @Error IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput @@ -4290,7 +4312,7 @@ BEGIN WHEN @EncryptionAlgorithm = 'AES_256' THEN '8' END - IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptionkey = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptionkey = N''' + @EncryptionKeyPlaceholder + '''' SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing LiteSpeed backup.'', 16, 1)' END @@ -4338,7 +4360,7 @@ BEGIN WHEN @EncryptionAlgorithm = 'AES_256' THEN '256' END - IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', PASSWORD = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', PASSWORD = N''' + @EncryptionKeyPlaceholder + '''' SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand,'''','''''') + '"''' + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing SQLBackup backup.'', 16, 1)' END @@ -4382,7 +4404,7 @@ BEGIN WHEN @EncryptionAlgorithm = 'AES_256' THEN 'AES256' END + '''' - IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptedbackuppassword = N''' + REPLACE(@EncryptionKey,'''','''''') + '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptedbackuppassword = N''' + @EncryptionKeyPlaceholder + '''' SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing SQLsafe backup.'', 16, 1)' END @@ -4438,7 +4460,7 @@ BEGIN SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error performing Data Domain Boost backup.'', 16, 1)' END - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @EncryptionKey = @EncryptionKey, @EncryptionKeyPlaceholder = @EncryptionKeyPlaceholder, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput = @Error IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput @@ -4499,7 +4521,7 @@ BEGIN 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,'''','''''') + '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', @encryptionkey = N''' + @EncryptionKeyPlaceholder + '''' SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error verifying LiteSpeed backup.'', 16, 1)' END @@ -4520,7 +4542,7 @@ BEGIN 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,'''','''''') + '''' + IF @EncryptionKey IS NOT NULL SET @CurrentCommand += ', PASSWORD = N''' + @EncryptionKeyPlaceholder + '''' SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.sqlbackup N''-SQL "' + REPLACE(@CurrentCommand,'''','''''') + '"''' + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error verifying SQLBackup backup.'', 16, 1)' END @@ -4546,7 +4568,7 @@ BEGIN SET @CurrentCommand += ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error verifying SQLsafe backup.'', 16, 1)' END - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @EncryptionKey = @EncryptionKey, @EncryptionKeyPlaceholder = @EncryptionKeyPlaceholder, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput = @Error IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput @@ -4644,7 +4666,7 @@ BEGIN 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(max)) + 'h'', ' + ISNULL('''' + REPLACE(@EncryptionKey,'''','''''') + '''','NULL') + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL 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(max)) + 'h'', ' + ISNULL('''' + @EncryptionKeyPlaceholder + '''','NULL') + ' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLBackup backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLSAFE' @@ -4656,7 +4678,7 @@ BEGIN 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(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @LogToTable = @LogToTable, @Execute = @Execute + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @EncryptionKey = @EncryptionKey, @EncryptionKeyPlaceholder = @EncryptionKeyPlaceholder, @LogToTable = @LogToTable, @Execute = @Execute SET @Error = @@ERROR IF @Error <> 0 SET @CurrentCommandOutput = @Error IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput @@ -4828,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-31 16:59:43 //-- + --// Version: 2026-06-06 10:32:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6777,7 +6799,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-05-31 16:59:43 //-- + --// Version: 2026-06-06 10:32:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 72fcf80d1eb5557ad76a4a93d9f7ace70e25fa02 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 6 Jun 2026 11:35:23 +0200 Subject: [PATCH 030/177] 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 88339541..4ccf8fa6 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-06 10:32:46 //-- + --// Version: 2026-06-06 12:34:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 2439ab7e..655a8884 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 10:32:46 //-- + --// Version: 2026-06-06 12:34:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2800,7 +2800,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) OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) AND @Credential IS NULL THEN 65537 + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version < 15.0404316 AND NOT (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) AND @Credential IS NULL THEN 65537 END IF SERVERPROPERTY('IsHadrEnabled') = 1 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 79779c46..98c128e6 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 10:32:46 //-- + --// Version: 2026-06-06 12:34:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index e0560507..4c1d3427 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 10:32:46 //-- + --// Version: 2026-06-06 12:34:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 155f2756..58b14489 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: 2026-06-06 10:32:46 +Version: 2026-06-06 12:34:43 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 10:32:46 //-- + --// Version: 2026-06-06 12:34:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 10:32:46 //-- + --// Version: 2026-06-06 12:34:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3205,7 +3205,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) OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) AND @Credential IS NULL THEN 65537 + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version < 15.0404316 AND NOT (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) AND @Credential IS NULL THEN 65537 END IF SERVERPROPERTY('IsHadrEnabled') = 1 @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 10:32:46 //-- + --// Version: 2026-06-06 12:34:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6799,7 +6799,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 10:32:46 //-- + --// Version: 2026-06-06 12:34:43 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From dbbd6ff9247b15c0e1d2141fe74122fad832101f Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 6 Jun 2026 20:28:35 +0200 Subject: [PATCH 031/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 39 +++++++++++++++++++++++++++++-- MaintenanceSolution.sql | 47 +++++++++++++++++++++++++++++++++----- 5 files changed, 81 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 4ccf8fa6..0cfb4933 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-06 12:34:43 //-- + --// Version: 2026-06-06 21:24:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 655a8884..46bc3b44 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 12:34:43 //-- + --// Version: 2026-06-06 21:24:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 98c128e6..e34fba4a 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 12:34:43 //-- + --// Version: 2026-06-06 21:24:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 4c1d3427..20a231d9 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 12:34:43 //-- + --// Version: 2026-06-06 21:24:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -152,6 +152,7 @@ BEGIN DECLARE @CurrentHasFilter bit DECLARE @CurrentNoRecompute bit DECLARE @CurrentIsIncremental bit + DECLARE @CurrentObjectRowCount bigint DECLARE @CurrentRowCount bigint DECLARE @CurrentModificationCounter bigint DECLARE @CurrentOnReadOnlyFileGroup bit @@ -1637,6 +1638,7 @@ BEGIN END SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] IN(''U'',''V'')' + + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' + 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' @@ -1692,6 +1694,7 @@ BEGIN SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] IN(''U'',''V'')' + ' AND (tables.is_memory_optimized = 0 OR tables.is_memory_optimized IS NULL)' + + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' + 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)' + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes2 WHERE indexes2.[object_id] = stats.[object_id] AND indexes2.type = 1 AND indexes2.is_disabled = 1)' @@ -1941,6 +1944,37 @@ BEGIN END CATCH END + -- What is the object row count? + IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL + BEGIN + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 + BEGIN + SET @CurrentCommand += 'SELECT @ParamObjectRowCount = row_count FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id (SELECT MIN(index_id) FROM sys.indexes WHERE [object_id] = @ParamObjectID) AND partition_number = @ParamPartitionNumber' + END + ELSE + BEGIN + SET @CurrentCommand += 'SELECT @ParamObjectRowCount = SUM(row_count) FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id = (SELECT MIN(index_id) FROM sys.indexes WHERE [object_id] = @ParamObjectID)' + END + + BEGIN TRY + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamPartitionNumber int, @ParamObjectRowCount bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamObjectRowCount = @CurrentObjectRowCount OUTPUT + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The row count 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 + SET @ReturnCode = ERROR_NUMBER() + END + GOTO NoAction + END CATCH + 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 BEGIN @@ -2090,7 +2124,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 ((@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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL)) + 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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL AND @CurrentObjectRowCount > 0)) 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' @@ -2362,6 +2396,7 @@ BEGIN SET @CurrentHasFilter = NULL SET @CurrentNoRecompute = NULL SET @CurrentIsIncremental = NULL + SET @CurrentObjectRowCount = NULL SET @CurrentRowCount = NULL SET @CurrentModificationCounter = NULL SET @CurrentOnReadOnlyFileGroup = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 58b14489..fa0da61e 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: 2026-06-06 12:34:43 +Version: 2026-06-06 21:24:44 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 12:34:43 //-- + --// Version: 2026-06-06 21:24:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 12:34:43 //-- + --// Version: 2026-06-06 21:24:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 12:34:43 //-- + --// Version: 2026-06-06 21:24:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6799,7 +6799,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 12:34:43 //-- + --// Version: 2026-06-06 21:24:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6897,6 +6897,7 @@ BEGIN DECLARE @CurrentHasFilter bit DECLARE @CurrentNoRecompute bit DECLARE @CurrentIsIncremental bit + DECLARE @CurrentObjectRowCount bigint DECLARE @CurrentRowCount bigint DECLARE @CurrentModificationCounter bigint DECLARE @CurrentOnReadOnlyFileGroup bit @@ -8382,6 +8383,7 @@ BEGIN END SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] IN(''U'',''V'')' + + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' + 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' @@ -8437,6 +8439,7 @@ BEGIN SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] IN(''U'',''V'')' + ' AND (tables.is_memory_optimized = 0 OR tables.is_memory_optimized IS NULL)' + + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' + 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)' + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes2 WHERE indexes2.[object_id] = stats.[object_id] AND indexes2.type = 1 AND indexes2.is_disabled = 1)' @@ -8686,6 +8689,37 @@ BEGIN END CATCH END + -- What is the object row count? + IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL + BEGIN + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 + BEGIN + SET @CurrentCommand += 'SELECT @ParamObjectRowCount = row_count FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id (SELECT MIN(index_id) FROM sys.indexes WHERE [object_id] = @ParamObjectID) AND partition_number = @ParamPartitionNumber' + END + ELSE + BEGIN + SET @CurrentCommand += 'SELECT @ParamObjectRowCount = SUM(row_count) FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id = (SELECT MIN(index_id) FROM sys.indexes WHERE [object_id] = @ParamObjectID)' + END + + BEGIN TRY + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamPartitionNumber int, @ParamObjectRowCount bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamObjectRowCount = @CurrentObjectRowCount OUTPUT + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The row count 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 + SET @ReturnCode = ERROR_NUMBER() + END + GOTO NoAction + END CATCH + 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 BEGIN @@ -8835,7 +8869,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 ((@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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL)) + 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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL AND @CurrentObjectRowCount > 0)) 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' @@ -9107,6 +9141,7 @@ BEGIN SET @CurrentHasFilter = NULL SET @CurrentNoRecompute = NULL SET @CurrentIsIncremental = NULL + SET @CurrentObjectRowCount = NULL SET @CurrentRowCount = NULL SET @CurrentModificationCounter = NULL SET @CurrentOnReadOnlyFileGroup = NULL From 80970f1aed656d548fe9a659331272b0c5c31a8b Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 6 Jun 2026 20:36:22 +0200 Subject: [PATCH 032/177] 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 0cfb4933..fbc98388 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-06 21:24:44 //-- + --// Version: 2026-06-06 21:35:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 46bc3b44..76a588aa 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 21:24:44 //-- + --// Version: 2026-06-06 21:35:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index e34fba4a..31f77f09 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 21:24:44 //-- + --// Version: 2026-06-06 21:35:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 20a231d9..56a1cd72 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -54,7 +54,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 21:24:44 //-- + --// Version: 2026-06-06 21:35:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1952,7 +1952,7 @@ BEGIN IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN - SET @CurrentCommand += 'SELECT @ParamObjectRowCount = row_count FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id (SELECT MIN(index_id) FROM sys.indexes WHERE [object_id] = @ParamObjectID) AND partition_number = @ParamPartitionNumber' + SET @CurrentCommand += 'SELECT @ParamObjectRowCount = row_count FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id = (SELECT MIN(index_id) FROM sys.indexes WHERE [object_id] = @ParamObjectID) AND partition_number = @ParamPartitionNumber' END ELSE BEGIN diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index fa0da61e..126b3162 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: 2026-06-06 21:24:44 +Version: 2026-06-06 21:35:24 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 21:24:44 //-- + --// Version: 2026-06-06 21:35:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 21:24:44 //-- + --// Version: 2026-06-06 21:35:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 21:24:44 //-- + --// Version: 2026-06-06 21:35:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6799,7 +6799,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 21:24:44 //-- + --// Version: 2026-06-06 21:35:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8697,7 +8697,7 @@ BEGIN IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN - SET @CurrentCommand += 'SELECT @ParamObjectRowCount = row_count FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id (SELECT MIN(index_id) FROM sys.indexes WHERE [object_id] = @ParamObjectID) AND partition_number = @ParamPartitionNumber' + SET @CurrentCommand += 'SELECT @ParamObjectRowCount = row_count FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id = (SELECT MIN(index_id) FROM sys.indexes WHERE [object_id] = @ParamObjectID) AND partition_number = @ParamPartitionNumber' END ELSE BEGIN From 1d270390fdd36783472b8a2db034b50a47ec163b Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 7 Jun 2026 12:22:13 +0200 Subject: [PATCH 033/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 36 ++++++++++++++++++++++++++++++- MaintenanceSolution.sql | 44 +++++++++++++++++++++++++++++++++----- 5 files changed, 77 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index fbc98388..06d18c52 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-06 21:35:24 //-- + --// Version: 2026-06-07 12:21:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 76a588aa..510fd30d 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 21:35:24 //-- + --// Version: 2026-06-07 12:21:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 31f77f09..62a3e1d9 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 21:35:24 //-- + --// Version: 2026-06-07 12:21:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 56a1cd72..c06adf2e 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -28,6 +28,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @StatisticsModificationLevel int = NULL, @StatisticsSample int = NULL, @StatisticsResample nvarchar(max) = 'N', +@StatisticsPersistSamplePercent nvarchar(max) = 'N', @PartitionLevel nvarchar(max) = 'Y', @MSShippedObjects nvarchar(max) = 'N', @Indexes nvarchar(max) = NULL, @@ -54,7 +55,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 21:35:24 //-- + --// Version: 2026-06-07 12:21:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -308,6 +309,7 @@ BEGIN SET @Parameters += ', @StatisticsModificationLevel = ' + ISNULL(CAST(@StatisticsModificationLevel AS nvarchar(max)),'NULL') SET @Parameters += ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar(max)),'NULL') SET @Parameters += ', @StatisticsResample = ' + ISNULL('''' + REPLACE(@StatisticsResample,'''','''''') + '''','NULL') + SET @Parameters += ', @StatisticsPersistSamplePercent = ' + ISNULL('''' + REPLACE(@StatisticsPersistSamplePercent,'''','''''') + '''','NULL') SET @Parameters += ', @PartitionLevel = ' + ISNULL('''' + REPLACE(@PartitionLevel,'''','''''') + '''','NULL') SET @Parameters += ', @MSShippedObjects = ' + ISNULL('''' + REPLACE(@MSShippedObjects,'''','''''') + '''','NULL') SET @Parameters += ', @Indexes = ' + ISNULL('''' + REPLACE(@Indexes,'''','''''') + '''','NULL') @@ -964,6 +966,32 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @StatisticsPersistSamplePercent NOT IN('Y','N') OR @StatisticsPersistSamplePercent IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StatisticsPersistSamplePercent is not supported.', 16, 1 + END + + IF @StatisticsPersistSamplePercent = 'Y' AND @StatisticsSample IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameter @StatisticsPersistSamplePercent can only be used together with @StatisticsSample.', 16, 2 + END + + IF @StatisticsPersistSamplePercent = 'Y' AND @StatisticsResample = 'Y' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameters @StatisticsPersistSamplePercent and @StatisticsResample cannot be used together.', 16, 3 + END + + IF @StatisticsPersistSamplePercent = 'Y' AND NOT (@Version > 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 4 + END + + ---------------------------------------------------------------------------------------------------- + IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -2331,6 +2359,12 @@ BEGIN SELECT 'RESAMPLE' END + IF @StatisticsPersistSamplePercent = 'Y' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'PERSIST_SAMPLE_PERCENT = ON' + END + IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) BEGIN SELECT @CurrentCommand += ' WITH ' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 126b3162..9c2679aa 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: 2026-06-06 21:35:24 +Version: 2026-06-07 12:21:05 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 21:35:24 //-- + --// Version: 2026-06-07 12:21:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 21:35:24 //-- + --// Version: 2026-06-07 12:21:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 21:35:24 //-- + --// Version: 2026-06-07 12:21:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6773,6 +6773,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @StatisticsModificationLevel int = NULL, @StatisticsSample int = NULL, @StatisticsResample nvarchar(max) = 'N', +@StatisticsPersistSamplePercent nvarchar(max) = 'N', @PartitionLevel nvarchar(max) = 'Y', @MSShippedObjects nvarchar(max) = 'N', @Indexes nvarchar(max) = NULL, @@ -6799,7 +6800,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-06 21:35:24 //-- + --// Version: 2026-06-07 12:21:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7053,6 +7054,7 @@ BEGIN SET @Parameters += ', @StatisticsModificationLevel = ' + ISNULL(CAST(@StatisticsModificationLevel AS nvarchar(max)),'NULL') SET @Parameters += ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar(max)),'NULL') SET @Parameters += ', @StatisticsResample = ' + ISNULL('''' + REPLACE(@StatisticsResample,'''','''''') + '''','NULL') + SET @Parameters += ', @StatisticsPersistSamplePercent = ' + ISNULL('''' + REPLACE(@StatisticsPersistSamplePercent,'''','''''') + '''','NULL') SET @Parameters += ', @PartitionLevel = ' + ISNULL('''' + REPLACE(@PartitionLevel,'''','''''') + '''','NULL') SET @Parameters += ', @MSShippedObjects = ' + ISNULL('''' + REPLACE(@MSShippedObjects,'''','''''') + '''','NULL') SET @Parameters += ', @Indexes = ' + ISNULL('''' + REPLACE(@Indexes,'''','''''') + '''','NULL') @@ -7709,6 +7711,32 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @StatisticsPersistSamplePercent NOT IN('Y','N') OR @StatisticsPersistSamplePercent IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StatisticsPersistSamplePercent is not supported.', 16, 1 + END + + IF @StatisticsPersistSamplePercent = 'Y' AND @StatisticsSample IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameter @StatisticsPersistSamplePercent can only be used together with @StatisticsSample.', 16, 2 + END + + IF @StatisticsPersistSamplePercent = 'Y' AND @StatisticsResample = 'Y' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameters @StatisticsPersistSamplePercent and @StatisticsResample cannot be used together.', 16, 3 + END + + IF @StatisticsPersistSamplePercent = 'Y' AND NOT (@Version > 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 4 + END + + ---------------------------------------------------------------------------------------------------- + IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -9076,6 +9104,12 @@ BEGIN SELECT 'RESAMPLE' END + IF @StatisticsPersistSamplePercent = 'Y' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'PERSIST_SAMPLE_PERCENT = ON' + END + IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) BEGIN SELECT @CurrentCommand += ' WITH ' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) From b2d3bc838e2f6634201b1b80a539afc98790e102 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 7 Jun 2026 12:55:27 +0200 Subject: [PATCH 034/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 22 +++++++++++++--------- MaintenanceSolution.sql | 30 +++++++++++++++++------------- 5 files changed, 33 insertions(+), 25 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 06d18c52..2fd2b61f 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-07 12:21:05 //-- + --// Version: 2026-06-07 12:54:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 510fd30d..8fc08caa 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 12:21:05 //-- + --// Version: 2026-06-07 12:54:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 62a3e1d9..86d8877b 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 12:21:05 //-- + --// Version: 2026-06-07 12:54:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index c06adf2e..5b9f8f7c 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -55,7 +55,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 12:21:05 //-- + --// Version: 2026-06-07 12:54:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -166,6 +166,7 @@ BEGIN DECLARE @CurrentUpdateStatistics nvarchar(max) DECLARE @CurrentStatisticsSample int DECLARE @CurrentStatisticsResample nvarchar(max) + DECLARE @CurrentStatisticsPersistSamplePercent nvarchar(max) DECLARE @CurrentDelay datetime DECLARE @tmpDatabases TABLE (ID int IDENTITY, @@ -984,10 +985,10 @@ BEGIN SELECT 'The parameters @StatisticsPersistSamplePercent and @StatisticsResample cannot be used together.', 16, 3 END - IF @StatisticsPersistSamplePercent = 'Y' AND NOT (@Version > 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @StatisticsPersistSamplePercent = 'Y' AND NOT (@Version >= 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 4 + SELECT 'The value for the parameter @StatisticsPersistSamplePercent is not supported.', 16, 4 END ---------------------------------------------------------------------------------------------------- @@ -2164,12 +2165,14 @@ BEGIN SET @CurrentStatisticsSample = @StatisticsSample SET @CurrentStatisticsResample = @StatisticsResample + SET @CurrentStatisticsPersistSamplePercent = @StatisticsPersistSamplePercent -- Incremental statistics only supports RESAMPLE IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN SET @CurrentStatisticsSample = NULL SET @CurrentStatisticsResample = 'Y' + SET @CurrentStatisticsPersistSamplePercent = 'N' END -- Create index comment @@ -2347,22 +2350,22 @@ BEGIN SELECT 'SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT' END - IF @CurrentNoRecompute = 1 + IF @CurrentStatisticsPersistSamplePercent = 'Y' BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'NORECOMPUTE' + SELECT 'PERSIST_SAMPLE_PERCENT = ON' END - IF @CurrentStatisticsResample = 'Y' + IF @CurrentNoRecompute = 1 BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'RESAMPLE' + SELECT 'NORECOMPUTE' END - IF @StatisticsPersistSamplePercent = 'Y' + IF @CurrentStatisticsResample = 'Y' BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'PERSIST_SAMPLE_PERCENT = ON' + SELECT 'RESAMPLE' END IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) @@ -2443,6 +2446,7 @@ BEGIN SET @CurrentUpdateStatistics = NULL SET @CurrentStatisticsSample = NULL SET @CurrentStatisticsResample = NULL + SET @CurrentStatisticsPersistSamplePercent = NULL DELETE FROM @CurrentActionsAllowed DELETE FROM @CurrentAlterIndexWithClauseArguments diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 9c2679aa..33d5baa1 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: 2026-06-07 12:21:05 +Version: 2026-06-07 12:54:54 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 12:21:05 //-- + --// Version: 2026-06-07 12:54:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 12:21:05 //-- + --// Version: 2026-06-07 12:54:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 12:21:05 //-- + --// Version: 2026-06-07 12:54:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6800,7 +6800,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 12:21:05 //-- + --// Version: 2026-06-07 12:54:54 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6911,6 +6911,7 @@ BEGIN DECLARE @CurrentUpdateStatistics nvarchar(max) DECLARE @CurrentStatisticsSample int DECLARE @CurrentStatisticsResample nvarchar(max) + DECLARE @CurrentStatisticsPersistSamplePercent nvarchar(max) DECLARE @CurrentDelay datetime DECLARE @tmpDatabases TABLE (ID int IDENTITY, @@ -7729,10 +7730,10 @@ BEGIN SELECT 'The parameters @StatisticsPersistSamplePercent and @StatisticsResample cannot be used together.', 16, 3 END - IF @StatisticsPersistSamplePercent = 'Y' AND NOT (@Version > 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @StatisticsPersistSamplePercent = 'Y' AND NOT (@Version >= 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 4 + SELECT 'The value for the parameter @StatisticsPersistSamplePercent is not supported.', 16, 4 END ---------------------------------------------------------------------------------------------------- @@ -8909,12 +8910,14 @@ BEGIN SET @CurrentStatisticsSample = @StatisticsSample SET @CurrentStatisticsResample = @StatisticsResample + SET @CurrentStatisticsPersistSamplePercent = @StatisticsPersistSamplePercent -- Incremental statistics only supports RESAMPLE IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN SET @CurrentStatisticsSample = NULL SET @CurrentStatisticsResample = 'Y' + SET @CurrentStatisticsPersistSamplePercent = 'N' END -- Create index comment @@ -9092,22 +9095,22 @@ BEGIN SELECT 'SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT' END - IF @CurrentNoRecompute = 1 + IF @CurrentStatisticsPersistSamplePercent = 'Y' BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'NORECOMPUTE' + SELECT 'PERSIST_SAMPLE_PERCENT = ON' END - IF @CurrentStatisticsResample = 'Y' + IF @CurrentNoRecompute = 1 BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'RESAMPLE' + SELECT 'NORECOMPUTE' END - IF @StatisticsPersistSamplePercent = 'Y' + IF @CurrentStatisticsResample = 'Y' BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'PERSIST_SAMPLE_PERCENT = ON' + SELECT 'RESAMPLE' END IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) @@ -9188,6 +9191,7 @@ BEGIN SET @CurrentUpdateStatistics = NULL SET @CurrentStatisticsSample = NULL SET @CurrentStatisticsResample = NULL + SET @CurrentStatisticsPersistSamplePercent = NULL DELETE FROM @CurrentActionsAllowed DELETE FROM @CurrentAlterIndexWithClauseArguments From 97dea61166916febb2aba044d14394eb5caacb8f Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 7 Jun 2026 13:00:56 +0200 Subject: [PATCH 035/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 10 +++++----- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 2fd2b61f..66cf2aa3 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-07 12:54:54 //-- + --// Version: 2026-06-07 13:00:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 8fc08caa..a2cf969a 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 12:54:54 //-- + --// Version: 2026-06-07 13:00:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 86d8877b..b7d8128f 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 12:54:54 //-- + --// Version: 2026-06-07 13:00:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 5b9f8f7c..4ad4116b 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -55,7 +55,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 12:54:54 //-- + --// Version: 2026-06-07 13:00:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 33d5baa1..da235e4a 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: 2026-06-07 12:54:54 +Version: 2026-06-07 13:00:12 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 12:54:54 //-- + --// Version: 2026-06-07 13:00:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 12:54:54 //-- + --// Version: 2026-06-07 13:00:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 12:54:54 //-- + --// Version: 2026-06-07 13:00:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6800,7 +6800,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 12:54:54 //-- + --// Version: 2026-06-07 13:00:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 46f347418b8ca22145a1ff144ead6517105dced9 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 7 Jun 2026 13:39:56 +0200 Subject: [PATCH 036/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 44 ++++++++++++++++---------------- MaintenanceSolution.sql | 52 +++++++++++++++++++------------------- 5 files changed, 51 insertions(+), 51 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 66cf2aa3..ed5cfb5b 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-07 13:00:12 //-- + --// Version: 2026-06-07 13:39:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index a2cf969a..f047a5d9 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:00:12 //-- + --// Version: 2026-06-07 13:39:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index b7d8128f..ce35818c 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:00:12 //-- + --// Version: 2026-06-07 13:39:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 4ad4116b..a557ffb3 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -27,8 +27,8 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @OnlyModifiedStatistics nvarchar(max) = 'N', @StatisticsModificationLevel int = NULL, @StatisticsSample int = NULL, +@StatisticsPersistSample nvarchar(max) = 'N', @StatisticsResample nvarchar(max) = 'N', -@StatisticsPersistSamplePercent nvarchar(max) = 'N', @PartitionLevel nvarchar(max) = 'Y', @MSShippedObjects nvarchar(max) = 'N', @Indexes nvarchar(max) = NULL, @@ -55,7 +55,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:00:12 //-- + --// Version: 2026-06-07 13:39:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -165,8 +165,8 @@ BEGIN DECLARE @CurrentMaxDOP int DECLARE @CurrentUpdateStatistics nvarchar(max) DECLARE @CurrentStatisticsSample int + DECLARE @CurrentStatisticsPersistSample nvarchar(max) DECLARE @CurrentStatisticsResample nvarchar(max) - DECLARE @CurrentStatisticsPersistSamplePercent nvarchar(max) DECLARE @CurrentDelay datetime DECLARE @tmpDatabases TABLE (ID int IDENTITY, @@ -309,8 +309,8 @@ BEGIN SET @Parameters += ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') SET @Parameters += ', @StatisticsModificationLevel = ' + ISNULL(CAST(@StatisticsModificationLevel AS nvarchar(max)),'NULL') SET @Parameters += ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar(max)),'NULL') + SET @Parameters += ', @StatisticsPersistSample = ' + ISNULL('''' + REPLACE(@StatisticsPersistSample,'''','''''') + '''','NULL') SET @Parameters += ', @StatisticsResample = ' + ISNULL('''' + REPLACE(@StatisticsResample,'''','''''') + '''','NULL') - SET @Parameters += ', @StatisticsPersistSamplePercent = ' + ISNULL('''' + REPLACE(@StatisticsPersistSamplePercent,'''','''''') + '''','NULL') SET @Parameters += ', @PartitionLevel = ' + ISNULL('''' + REPLACE(@PartitionLevel,'''','''''') + '''','NULL') SET @Parameters += ', @MSShippedObjects = ' + ISNULL('''' + REPLACE(@MSShippedObjects,'''','''''') + '''','NULL') SET @Parameters += ', @Indexes = ' + ISNULL('''' + REPLACE(@Indexes,'''','''''') + '''','NULL') @@ -953,42 +953,42 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL + IF @StatisticsPersistSample NOT IN('Y','N') OR @StatisticsPersistSample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 1 + SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 1 END - IF @StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL + IF @StatisticsPersistSample = 'Y' AND @StatisticsSample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 2 + SELECT 'The parameter @StatisticsPersistSample can only be used together with @StatisticsSample.', 16, 2 END - ---------------------------------------------------------------------------------------------------- - - IF @StatisticsPersistSamplePercent NOT IN('Y','N') OR @StatisticsPersistSamplePercent IS NULL + IF @StatisticsPersistSample = 'Y' AND @StatisticsResample = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsPersistSamplePercent is not supported.', 16, 1 + SELECT 'The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3 END - IF @StatisticsPersistSamplePercent = 'Y' AND @StatisticsSample IS NULL + IF @StatisticsPersistSample = 'Y' AND NOT (@Version >= 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @StatisticsPersistSamplePercent can only be used together with @StatisticsSample.', 16, 2 + SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 4 END - IF @StatisticsPersistSamplePercent = 'Y' AND @StatisticsResample = 'Y' + ---------------------------------------------------------------------------------------------------- + + IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameters @StatisticsPersistSamplePercent and @StatisticsResample cannot be used together.', 16, 3 + SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 1 END - IF @StatisticsPersistSamplePercent = 'Y' AND NOT (@Version >= 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsPersistSamplePercent is not supported.', 16, 4 + SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 2 END ---------------------------------------------------------------------------------------------------- @@ -2165,14 +2165,14 @@ BEGIN SET @CurrentStatisticsSample = @StatisticsSample SET @CurrentStatisticsResample = @StatisticsResample - SET @CurrentStatisticsPersistSamplePercent = @StatisticsPersistSamplePercent + SET @CurrentStatisticsPersistSample = @StatisticsPersistSample -- Incremental statistics only supports RESAMPLE IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN SET @CurrentStatisticsSample = NULL + SET @CurrentStatisticsPersistSample = 'N' SET @CurrentStatisticsResample = 'Y' - SET @CurrentStatisticsPersistSamplePercent = 'N' END -- Create index comment @@ -2350,7 +2350,7 @@ BEGIN SELECT 'SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT' END - IF @CurrentStatisticsPersistSamplePercent = 'Y' + IF @CurrentStatisticsPersistSample = 'Y' BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) SELECT 'PERSIST_SAMPLE_PERCENT = ON' @@ -2445,8 +2445,8 @@ BEGIN SET @CurrentMaxDOP = NULL SET @CurrentUpdateStatistics = NULL SET @CurrentStatisticsSample = NULL + SET @CurrentStatisticsPersistSample = NULL SET @CurrentStatisticsResample = NULL - SET @CurrentStatisticsPersistSamplePercent = NULL DELETE FROM @CurrentActionsAllowed DELETE FROM @CurrentAlterIndexWithClauseArguments diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index da235e4a..774bd724 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: 2026-06-07 13:00:12 +Version: 2026-06-07 13:39:21 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:00:12 //-- + --// Version: 2026-06-07 13:39:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:00:12 //-- + --// Version: 2026-06-07 13:39:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:00:12 //-- + --// Version: 2026-06-07 13:39:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6772,8 +6772,8 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @OnlyModifiedStatistics nvarchar(max) = 'N', @StatisticsModificationLevel int = NULL, @StatisticsSample int = NULL, +@StatisticsPersistSample nvarchar(max) = 'N', @StatisticsResample nvarchar(max) = 'N', -@StatisticsPersistSamplePercent nvarchar(max) = 'N', @PartitionLevel nvarchar(max) = 'Y', @MSShippedObjects nvarchar(max) = 'N', @Indexes nvarchar(max) = NULL, @@ -6800,7 +6800,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:00:12 //-- + --// Version: 2026-06-07 13:39:21 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6910,8 +6910,8 @@ BEGIN DECLARE @CurrentMaxDOP int DECLARE @CurrentUpdateStatistics nvarchar(max) DECLARE @CurrentStatisticsSample int + DECLARE @CurrentStatisticsPersistSample nvarchar(max) DECLARE @CurrentStatisticsResample nvarchar(max) - DECLARE @CurrentStatisticsPersistSamplePercent nvarchar(max) DECLARE @CurrentDelay datetime DECLARE @tmpDatabases TABLE (ID int IDENTITY, @@ -7054,8 +7054,8 @@ BEGIN SET @Parameters += ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') SET @Parameters += ', @StatisticsModificationLevel = ' + ISNULL(CAST(@StatisticsModificationLevel AS nvarchar(max)),'NULL') SET @Parameters += ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar(max)),'NULL') + SET @Parameters += ', @StatisticsPersistSample = ' + ISNULL('''' + REPLACE(@StatisticsPersistSample,'''','''''') + '''','NULL') SET @Parameters += ', @StatisticsResample = ' + ISNULL('''' + REPLACE(@StatisticsResample,'''','''''') + '''','NULL') - SET @Parameters += ', @StatisticsPersistSamplePercent = ' + ISNULL('''' + REPLACE(@StatisticsPersistSamplePercent,'''','''''') + '''','NULL') SET @Parameters += ', @PartitionLevel = ' + ISNULL('''' + REPLACE(@PartitionLevel,'''','''''') + '''','NULL') SET @Parameters += ', @MSShippedObjects = ' + ISNULL('''' + REPLACE(@MSShippedObjects,'''','''''') + '''','NULL') SET @Parameters += ', @Indexes = ' + ISNULL('''' + REPLACE(@Indexes,'''','''''') + '''','NULL') @@ -7698,42 +7698,42 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL + IF @StatisticsPersistSample NOT IN('Y','N') OR @StatisticsPersistSample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 1 + SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 1 END - IF @StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL + IF @StatisticsPersistSample = 'Y' AND @StatisticsSample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 2 + SELECT 'The parameter @StatisticsPersistSample can only be used together with @StatisticsSample.', 16, 2 END - ---------------------------------------------------------------------------------------------------- - - IF @StatisticsPersistSamplePercent NOT IN('Y','N') OR @StatisticsPersistSamplePercent IS NULL + IF @StatisticsPersistSample = 'Y' AND @StatisticsResample = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsPersistSamplePercent is not supported.', 16, 1 + SELECT 'The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3 END - IF @StatisticsPersistSamplePercent = 'Y' AND @StatisticsSample IS NULL + IF @StatisticsPersistSample = 'Y' AND NOT (@Version >= 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @StatisticsPersistSamplePercent can only be used together with @StatisticsSample.', 16, 2 + SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 4 END - IF @StatisticsPersistSamplePercent = 'Y' AND @StatisticsResample = 'Y' + ---------------------------------------------------------------------------------------------------- + + IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameters @StatisticsPersistSamplePercent and @StatisticsResample cannot be used together.', 16, 3 + SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 1 END - IF @StatisticsPersistSamplePercent = 'Y' AND NOT (@Version >= 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsPersistSamplePercent is not supported.', 16, 4 + SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 2 END ---------------------------------------------------------------------------------------------------- @@ -8910,14 +8910,14 @@ BEGIN SET @CurrentStatisticsSample = @StatisticsSample SET @CurrentStatisticsResample = @StatisticsResample - SET @CurrentStatisticsPersistSamplePercent = @StatisticsPersistSamplePercent + SET @CurrentStatisticsPersistSample = @StatisticsPersistSample -- Incremental statistics only supports RESAMPLE IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN SET @CurrentStatisticsSample = NULL + SET @CurrentStatisticsPersistSample = 'N' SET @CurrentStatisticsResample = 'Y' - SET @CurrentStatisticsPersistSamplePercent = 'N' END -- Create index comment @@ -9095,7 +9095,7 @@ BEGIN SELECT 'SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT' END - IF @CurrentStatisticsPersistSamplePercent = 'Y' + IF @CurrentStatisticsPersistSample = 'Y' BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) SELECT 'PERSIST_SAMPLE_PERCENT = ON' @@ -9190,8 +9190,8 @@ BEGIN SET @CurrentMaxDOP = NULL SET @CurrentUpdateStatistics = NULL SET @CurrentStatisticsSample = NULL + SET @CurrentStatisticsPersistSample = NULL SET @CurrentStatisticsResample = NULL - SET @CurrentStatisticsPersistSamplePercent = NULL DELETE FROM @CurrentActionsAllowed DELETE FROM @CurrentAlterIndexWithClauseArguments From a558446cb68652ca799477d75b8d2256a75ba8c6 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 7 Jun 2026 13:46:41 +0200 Subject: [PATCH 037/177] 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 ed5cfb5b..78a7cf2e 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-07 13:39:21 //-- + --// Version: 2026-06-07 13:46:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index f047a5d9..091b47a8 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:39:21 //-- + --// Version: 2026-06-07 13:46:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index ce35818c..a5e0d887 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:39:21 //-- + --// Version: 2026-06-07 13:46:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index a557ffb3..ff565e3c 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -55,7 +55,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:39:21 //-- + --// Version: 2026-06-07 13:46:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2164,8 +2164,8 @@ BEGIN END SET @CurrentStatisticsSample = @StatisticsSample - SET @CurrentStatisticsResample = @StatisticsResample SET @CurrentStatisticsPersistSample = @StatisticsPersistSample + SET @CurrentStatisticsResample = @StatisticsResample -- Incremental statistics only supports RESAMPLE IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 774bd724..e46c218d 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: 2026-06-07 13:39:21 +Version: 2026-06-07 13:46:05 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:39:21 //-- + --// Version: 2026-06-07 13:46:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:39:21 //-- + --// Version: 2026-06-07 13:46:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:39:21 //-- + --// Version: 2026-06-07 13:46:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6800,7 +6800,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:39:21 //-- + --// Version: 2026-06-07 13:46:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8909,8 +8909,8 @@ BEGIN END SET @CurrentStatisticsSample = @StatisticsSample - SET @CurrentStatisticsResample = @StatisticsResample SET @CurrentStatisticsPersistSample = @StatisticsPersistSample + SET @CurrentStatisticsResample = @StatisticsResample -- Incremental statistics only supports RESAMPLE IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 From c5eeddb54b853d136cfc72ecf17604641f35f7db Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 7 Jun 2026 17:32:16 +0200 Subject: [PATCH 038/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 10 ++++++++-- MaintenanceSolution.sql | 18 ++++++++++++------ 5 files changed, 23 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 78a7cf2e..264783d0 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-07 13:46:05 //-- + --// Version: 2026-06-07 17:31:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 091b47a8..149904c9 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:46:05 //-- + --// Version: 2026-06-07 17:31:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index a5e0d887..24004b35 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:46:05 //-- + --// Version: 2026-06-07 17:31:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index ff565e3c..dd73feee 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -55,7 +55,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:46:05 //-- + --// Version: 2026-06-07 17:31:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2235,6 +2235,12 @@ BEGIN SELECT 'ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END END + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 1 AND @WaitAtLowPriorityMaxDuration IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + ')' + END + IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) @@ -2265,7 +2271,7 @@ BEGIN SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 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 @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 AND @TimeLimit IS NOT NULL + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'MAX_DURATION = ' + CAST(DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) AS nvarchar(max)) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index e46c218d..bc528416 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: 2026-06-07 13:46:05 +Version: 2026-06-07 17:31:20 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:46:05 //-- + --// Version: 2026-06-07 17:31:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:46:05 //-- + --// Version: 2026-06-07 17:31:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:46:05 //-- + --// Version: 2026-06-07 17:31:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6800,7 +6800,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 13:46:05 //-- + --// Version: 2026-06-07 17:31:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8980,6 +8980,12 @@ BEGIN SELECT 'ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END END + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 1 AND @WaitAtLowPriorityMaxDuration IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + ')' + END + IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) @@ -9010,7 +9016,7 @@ BEGIN SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 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 @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 AND @TimeLimit IS NOT NULL + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'MAX_DURATION = ' + CAST(DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) AS nvarchar(max)) From bf219f99eb439eb57b26b66402f5e3a034fd7713 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 7 Jun 2026 19:12:55 +0200 Subject: [PATCH 039/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 22 ++++++++++++++-------- MaintenanceSolution.sql | 30 ++++++++++++++++++------------ 5 files changed, 35 insertions(+), 23 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 264783d0..441d10b9 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-07 17:31:20 //-- + --// Version: 2026-06-07 19:11:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 149904c9..e715daf0 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 17:31:20 //-- + --// Version: 2026-06-07 19:11:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 24004b35..54aa8917 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 17:31:20 //-- + --// Version: 2026-06-07 19:11:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index dd73feee..47c43a3f 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -27,7 +27,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @OnlyModifiedStatistics nvarchar(max) = 'N', @StatisticsModificationLevel int = NULL, @StatisticsSample int = NULL, -@StatisticsPersistSample nvarchar(max) = 'N', +@StatisticsPersistSample nvarchar(max) = NULL, @StatisticsResample nvarchar(max) = 'N', @PartitionLevel nvarchar(max) = 'Y', @MSShippedObjects nvarchar(max) = 'N', @@ -55,7 +55,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 17:31:20 //-- + --// Version: 2026-06-07 19:11:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -953,25 +953,25 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @StatisticsPersistSample NOT IN('Y','N') OR @StatisticsPersistSample IS NULL + IF @StatisticsPersistSample NOT IN('Y','N') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 1 END - IF @StatisticsPersistSample = 'Y' AND @StatisticsSample IS NULL + IF @StatisticsPersistSample IS NOT NULL AND @StatisticsSample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The parameter @StatisticsPersistSample can only be used together with @StatisticsSample.', 16, 2 END - IF @StatisticsPersistSample = 'Y' AND @StatisticsResample = 'Y' + IF @StatisticsPersistSample IS NOT NULL AND @StatisticsResample = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3 END - IF @StatisticsPersistSample = 'Y' AND NOT (@Version >= 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 4 @@ -2171,7 +2171,7 @@ BEGIN IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN SET @CurrentStatisticsSample = NULL - SET @CurrentStatisticsPersistSample = 'N' + SET @CurrentStatisticsPersistSample = NULL SET @CurrentStatisticsResample = 'Y' END @@ -2274,7 +2274,7 @@ BEGIN IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'MAX_DURATION = ' + CAST(DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) AS nvarchar(max)) + SELECT 'MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max)) END IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' @@ -2362,6 +2362,12 @@ BEGIN SELECT 'PERSIST_SAMPLE_PERCENT = ON' END + IF @CurrentStatisticsPersistSample = 'N' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'PERSIST_SAMPLE_PERCENT = OFF' + END + IF @CurrentNoRecompute = 1 BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index bc528416..3c104557 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: 2026-06-07 17:31:20 +Version: 2026-06-07 19:11:50 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 17:31:20 //-- + --// Version: 2026-06-07 19:11:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 17:31:20 //-- + --// Version: 2026-06-07 19:11:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 17:31:20 //-- + --// Version: 2026-06-07 19:11:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6772,7 +6772,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @OnlyModifiedStatistics nvarchar(max) = 'N', @StatisticsModificationLevel int = NULL, @StatisticsSample int = NULL, -@StatisticsPersistSample nvarchar(max) = 'N', +@StatisticsPersistSample nvarchar(max) = NULL, @StatisticsResample nvarchar(max) = 'N', @PartitionLevel nvarchar(max) = 'Y', @MSShippedObjects nvarchar(max) = 'N', @@ -6800,7 +6800,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 17:31:20 //-- + --// Version: 2026-06-07 19:11:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7698,25 +7698,25 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @StatisticsPersistSample NOT IN('Y','N') OR @StatisticsPersistSample IS NULL + IF @StatisticsPersistSample NOT IN('Y','N') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 1 END - IF @StatisticsPersistSample = 'Y' AND @StatisticsSample IS NULL + IF @StatisticsPersistSample IS NOT NULL AND @StatisticsSample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The parameter @StatisticsPersistSample can only be used together with @StatisticsSample.', 16, 2 END - IF @StatisticsPersistSample = 'Y' AND @StatisticsResample = 'Y' + IF @StatisticsPersistSample IS NOT NULL AND @StatisticsResample = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3 END - IF @StatisticsPersistSample = 'Y' AND NOT (@Version >= 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 4 @@ -8916,7 +8916,7 @@ BEGIN IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 BEGIN SET @CurrentStatisticsSample = NULL - SET @CurrentStatisticsPersistSample = 'N' + SET @CurrentStatisticsPersistSample = NULL SET @CurrentStatisticsResample = 'Y' END @@ -9019,7 +9019,7 @@ BEGIN IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'MAX_DURATION = ' + CAST(DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) AS nvarchar(max)) + SELECT 'MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max)) END IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' @@ -9107,6 +9107,12 @@ BEGIN SELECT 'PERSIST_SAMPLE_PERCENT = ON' END + IF @CurrentStatisticsPersistSample = 'N' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + SELECT 'PERSIST_SAMPLE_PERCENT = OFF' + END + IF @CurrentNoRecompute = 1 BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) From 359fbbe94bb2bb25f100c493532543ada951207d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 7 Jun 2026 23:09:52 +0200 Subject: [PATCH 040/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 10 +++++----- DatabaseIntegrityCheck.sql | 8 ++++---- IndexOptimize.sql | 10 +++++----- MaintenanceSolution.sql | 34 +++++++++++++++++----------------- 5 files changed, 32 insertions(+), 32 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 441d10b9..d3d62f81 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-07 19:11:50 //-- + --// Version: 2026-06-07 23:07:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index e715daf0..2182c0aa 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 19:11:50 //-- + --// Version: 2026-06-07 23:07:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -279,11 +279,11 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) - 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)) + DECLARE @Version numeric(18,10) = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4) + '.' + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),2) AS numeric(18,10)) IF SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' BEGIN - SET @Version = 16.010006 + SET @Version = 16.01000 END IF SERVERPROPERTY('EngineEdition') <> 5 @@ -2800,7 +2800,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 < 15.0404316 AND NOT (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) AND @Credential IS NULL THEN 65537 + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version < 15.04043 AND NOT (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) AND @Credential IS NULL THEN 65537 END IF SERVERPROPERTY('IsHadrEnabled') = 1 @@ -3812,7 +3812,7 @@ BEGIN IF @Checksum = 'Y' SET @CurrentCommand += 'CHECKSUM' IF @Checksum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' - SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND (@CurrentMaxTransferSize >= 65537 OR (@Version >= 15.0404316 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))))) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END + SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND (@CurrentMaxTransferSize >= 65537 OR (@Version >= 15.04043 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))))) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END IF @Compress = 'Y' AND @CompressionAlgorithm IS NOT NULL BEGIN diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 54aa8917..a0429239 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 19:11:50 //-- + --// Version: 2026-06-07 23:07:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -184,11 +184,11 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) - 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)) + DECLARE @Version numeric(18,10) = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4) + '.' + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),2) AS numeric(18,10)) IF SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' BEGIN - SET @Version = 16.010006 + SET @Version = 16.01000 END IF SERVERPROPERTY('EngineEdition') <> 5 @@ -893,7 +893,7 @@ BEGIN 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 >= 14.0302916 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 14.03029 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) 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 diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 47c43a3f..14d039b6 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -55,7 +55,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 19:11:50 //-- + --// Version: 2026-06-07 23:07:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -264,11 +264,11 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) - 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)) + DECLARE @Version numeric(18,10) = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4) + '.' + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),2) AS numeric(18,10)) IF SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' BEGIN - SET @Version = 16.010006 + SET @Version = 16.01000 END IF SERVERPROPERTY('EngineEdition') <> 5 @@ -971,7 +971,7 @@ BEGIN SELECT 'The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3 END - IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.03006 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 4 @@ -2338,7 +2338,7 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) - IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.030154 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max)) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 3c104557..72cab624 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: 2026-06-07 19:11:50 +Version: 2026-06-07 23:07:00 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 19:11:50 //-- + --// Version: 2026-06-07 23:07:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 19:11:50 //-- + --// Version: 2026-06-07 23:07:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -684,11 +684,11 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) - 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)) + DECLARE @Version numeric(18,10) = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4) + '.' + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),2) AS numeric(18,10)) IF SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' BEGIN - SET @Version = 16.010006 + SET @Version = 16.01000 END IF SERVERPROPERTY('EngineEdition') <> 5 @@ -3205,7 +3205,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 < 15.0404316 AND NOT (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) AND @Credential IS NULL THEN 65537 + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version < 15.04043 AND NOT (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) AND @Credential IS NULL THEN 65537 END IF SERVERPROPERTY('IsHadrEnabled') = 1 @@ -4217,7 +4217,7 @@ BEGIN IF @Checksum = 'Y' SET @CurrentCommand += 'CHECKSUM' IF @Checksum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' - SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND (@CurrentMaxTransferSize >= 65537 OR (@Version >= 15.0404316 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))))) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END + SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND (@CurrentMaxTransferSize >= 65537 OR (@Version >= 15.04043 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))))) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END IF @Compress = 'Y' AND @CompressionAlgorithm IS NOT NULL BEGIN @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 19:11:50 //-- + --// Version: 2026-06-07 23:07:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4994,11 +4994,11 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) - 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)) + DECLARE @Version numeric(18,10) = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4) + '.' + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),2) AS numeric(18,10)) IF SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' BEGIN - SET @Version = 16.010006 + SET @Version = 16.01000 END IF SERVERPROPERTY('EngineEdition') <> 5 @@ -5703,7 +5703,7 @@ BEGIN 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 >= 14.0302916 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 14.03029 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) 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 @@ -6800,7 +6800,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 19:11:50 //-- + --// Version: 2026-06-07 23:07:00 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7009,11 +7009,11 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) - 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)) + DECLARE @Version numeric(18,10) = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4) + '.' + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),2) AS numeric(18,10)) IF SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' BEGIN - SET @Version = 16.010006 + SET @Version = 16.01000 END IF SERVERPROPERTY('EngineEdition') <> 5 @@ -7716,7 +7716,7 @@ BEGIN SELECT 'The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3 END - IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.0300616 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.03006 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 4 @@ -9083,7 +9083,7 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) - IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.030154 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max)) @@ -9341,7 +9341,7 @@ BEGIN DECLARE @CurrentJobStepDatabaseName nvarchar(max) DECLARE @CurrentOutputFileName nvarchar(max) - 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)) + DECLARE @Version numeric(18,10) = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4) + '.' + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),2) AS numeric(18,10)) DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END From 2d3055201fef7ecccba2c262a6e04eb6b19c41f5 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 8 Jun 2026 08:34:50 +0200 Subject: [PATCH 041/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 18 +++++++++++++++++- MaintenanceSolution.sql | 26 +++++++++++++++++++++----- 5 files changed, 41 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index d3d62f81..30df0f80 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-07 23:07:00 //-- + --// Version: 2026-06-08 08:34:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 2182c0aa..9fbbedd9 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 23:07:00 //-- + --// Version: 2026-06-08 08:34:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index a0429239..2eb97d3e 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 23:07:00 //-- + --// Version: 2026-06-08 08:34:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 14d039b6..34a45593 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -22,6 +22,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @MaxDOP int = NULL, @FillFactor int = NULL, @PadIndex nvarchar(max) = NULL, +@DataCompression nvarchar(max) = NULL, @LOBCompaction nvarchar(max) = 'Y', @UpdateStatistics nvarchar(max) = NULL, @OnlyModifiedStatistics nvarchar(max) = 'N', @@ -55,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 23:07:00 //-- + --// Version: 2026-06-08 08:34:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -304,6 +305,7 @@ BEGIN SET @Parameters += ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar(max)),'NULL') SET @Parameters += ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar(max)),'NULL') SET @Parameters += ', @PadIndex = ' + ISNULL('''' + REPLACE(@PadIndex,'''','''''') + '''','NULL') + SET @Parameters += ', @DataCompression = ' + ISNULL('''' + REPLACE(@DataCompression,'''','''''') + '''','NULL') SET @Parameters += ', @LOBCompaction = ' + ISNULL('''' + REPLACE(@LOBCompaction,'''','''''') + '''','NULL') SET @Parameters += ', @UpdateStatistics = ' + ISNULL('''' + REPLACE(@UpdateStatistics,'''','''''') + '''','NULL') SET @Parameters += ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') @@ -905,6 +907,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @DataCompression NOT IN('NONE', 'PAGE', 'ROW') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataCompression is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -2265,6 +2275,12 @@ BEGIN SELECT 'PAD_INDEX = ON' END + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'DATA_COMPRESSION = ' + @DataCompression + END + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 72cab624..18d04305 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: 2026-06-07 23:07:00 +Version: 2026-06-08 08:34:02 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 23:07:00 //-- + --// Version: 2026-06-08 08:34:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 23:07:00 //-- + --// Version: 2026-06-08 08:34:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 23:07:00 //-- + --// Version: 2026-06-08 08:34:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6767,6 +6767,7 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @MaxDOP int = NULL, @FillFactor int = NULL, @PadIndex nvarchar(max) = NULL, +@DataCompression nvarchar(max) = NULL, @LOBCompaction nvarchar(max) = 'Y', @UpdateStatistics nvarchar(max) = NULL, @OnlyModifiedStatistics nvarchar(max) = 'N', @@ -6800,7 +6801,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-07 23:07:00 //-- + --// Version: 2026-06-08 08:34:02 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7049,6 +7050,7 @@ BEGIN SET @Parameters += ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar(max)),'NULL') SET @Parameters += ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar(max)),'NULL') SET @Parameters += ', @PadIndex = ' + ISNULL('''' + REPLACE(@PadIndex,'''','''''') + '''','NULL') + SET @Parameters += ', @DataCompression = ' + ISNULL('''' + REPLACE(@DataCompression,'''','''''') + '''','NULL') SET @Parameters += ', @LOBCompaction = ' + ISNULL('''' + REPLACE(@LOBCompaction,'''','''''') + '''','NULL') SET @Parameters += ', @UpdateStatistics = ' + ISNULL('''' + REPLACE(@UpdateStatistics,'''','''''') + '''','NULL') SET @Parameters += ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') @@ -7650,6 +7652,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @DataCompression NOT IN('NONE', 'PAGE', 'ROW') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataCompression is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -9010,6 +9020,12 @@ BEGIN SELECT 'PAD_INDEX = ON' END + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + SELECT 'DATA_COMPRESSION = ' + @DataCompression + END + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) From 301230dc363d097b289a2484c106fe83ba120cdb Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 8 Jun 2026 08:57:37 +0200 Subject: [PATCH 042/177] 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 30df0f80..865540cb 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-08 08:34:02 //-- + --// Version: 2026-06-08 08:57:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 9fbbedd9..89c49dce 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 08:34:02 //-- + --// Version: 2026-06-08 08:57:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 2eb97d3e..d55840e3 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 08:34:02 //-- + --// Version: 2026-06-08 08:57:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 34a45593..5a13dd67 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 08:34:02 //-- + --// Version: 2026-06-08 08:57:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2269,10 +2269,10 @@ BEGIN SELECT 'FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max)) END - 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 + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'PAD_INDEX = ON' + SELECT 'PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END END IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 18d04305..b27fa984 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: 2026-06-08 08:34:02 +Version: 2026-06-08 08:57:14 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 08:34:02 //-- + --// Version: 2026-06-08 08:57:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 08:34:02 //-- + --// Version: 2026-06-08 08:57:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 08:34:02 //-- + --// Version: 2026-06-08 08:57:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6801,7 +6801,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 08:34:02 //-- + --// Version: 2026-06-08 08:57:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -9014,10 +9014,10 @@ BEGIN SELECT 'FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max)) END - 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 + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'PAD_INDEX = ON' + SELECT 'PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END END IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 From 7677f269bdc03f1e3afd3bf1f2758699c45e74d9 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 8 Jun 2026 09:13:27 +0200 Subject: [PATCH 043/177] 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 865540cb..6cc1cc58 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-08 08:57:14 //-- + --// Version: 2026-06-08 09:12:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 89c49dce..d19b7ddf 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 08:57:14 //-- + --// Version: 2026-06-08 09:12:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index d55840e3..32be9c8b 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 08:57:14 //-- + --// Version: 2026-06-08 09:12:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 5a13dd67..057edaab 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 08:57:14 //-- + --// Version: 2026-06-08 09:12:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2275,7 +2275,7 @@ BEGIN SELECT 'PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'DATA_COMPRESSION = ' + @DataCompression diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index b27fa984..ec2cd477 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: 2026-06-08 08:57:14 +Version: 2026-06-08 09:12:40 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 08:57:14 //-- + --// Version: 2026-06-08 09:12:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 08:57:14 //-- + --// Version: 2026-06-08 09:12:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 08:57:14 //-- + --// Version: 2026-06-08 09:12:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6801,7 +6801,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 08:57:14 //-- + --// Version: 2026-06-08 09:12:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -9020,7 +9020,7 @@ BEGIN SELECT 'PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'DATA_COMPRESSION = ' + @DataCompression From 69ff35c02be01403c2cfc24dd63261ef32c06096 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 9 Jun 2026 19:20:42 +0200 Subject: [PATCH 044/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 6 ++- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 90 ++++++++++++++++---------------- MaintenanceSolution.sql | 102 +++++++++++++++++++------------------ 5 files changed, 103 insertions(+), 99 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 6cc1cc58..61db885f 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-08 09:12:40 //-- + --// Version: 2026-06-09 19:19:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index d19b7ddf..9ef733db 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 09:12:40 //-- + --// Version: 2026-06-09 19:19:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2863,7 +2863,9 @@ BEGIN WHERE database_id = DB_ID(@CurrentDatabaseName) END - IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentInStandby = 1) + IF @CurrentDatabaseState = 'ONLINE' + AND NOT @CurrentUserAccess = 'SINGLE_USER' + AND NOT @CurrentInStandby = 1 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 32be9c8b..3779eac3 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 09:12:40 //-- + --// Version: 2026-06-09 19:19:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 057edaab..b72cd7b4 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -23,6 +23,9 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @FillFactor int = NULL, @PadIndex nvarchar(max) = NULL, @DataCompression nvarchar(max) = NULL, +@WaitAtLowPriorityMaxDuration int = NULL, +@WaitAtLowPriorityAbortAfterWait nvarchar(max) = NULL, +@Resumable nvarchar(max) = 'N', @LOBCompaction nvarchar(max) = 'Y', @UpdateStatistics nvarchar(max) = NULL, @OnlyModifiedStatistics nvarchar(max) = 'N', @@ -35,9 +38,6 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @Indexes nvarchar(max) = NULL, @TimeLimit int = NULL, @Delay int = NULL, -@WaitAtLowPriorityMaxDuration int = NULL, -@WaitAtLowPriorityAbortAfterWait nvarchar(max) = NULL, -@Resumable nvarchar(max) = 'N', @AvailabilityGroups nvarchar(max) = NULL, @LockTimeout int = NULL, @LockMessageSeverity int = 16, @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 09:12:40 //-- + --// Version: 2026-06-09 19:19:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -306,6 +306,9 @@ BEGIN SET @Parameters += ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar(max)),'NULL') SET @Parameters += ', @PadIndex = ' + ISNULL('''' + REPLACE(@PadIndex,'''','''''') + '''','NULL') SET @Parameters += ', @DataCompression = ' + ISNULL('''' + REPLACE(@DataCompression,'''','''''') + '''','NULL') + SET @Parameters += ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)),'NULL') + SET @Parameters += ', @WaitAtLowPriorityAbortAfterWait = ' + ISNULL('''' + REPLACE(@WaitAtLowPriorityAbortAfterWait,'''','''''') + '''','NULL') + SET @Parameters += ', @Resumable = ' + ISNULL('''' + REPLACE(@Resumable,'''','''''') + '''','NULL') SET @Parameters += ', @LOBCompaction = ' + ISNULL('''' + REPLACE(@LOBCompaction,'''','''''') + '''','NULL') SET @Parameters += ', @UpdateStatistics = ' + ISNULL('''' + REPLACE(@UpdateStatistics,'''','''''') + '''','NULL') SET @Parameters += ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') @@ -318,9 +321,6 @@ BEGIN SET @Parameters += ', @Indexes = ' + ISNULL('''' + REPLACE(@Indexes,'''','''''') + '''','NULL') SET @Parameters += ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar(max)),'NULL') SET @Parameters += ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar(max)),'NULL') - SET @Parameters += ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)),'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(max)),'NULL') SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar(max)),'NULL') @@ -915,6 +915,44 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @WaitAtLowPriorityMaxDuration < 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + + IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') + BEGIN + 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 @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 @SortInTempdb = 'Y' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 3 + END + + ---------------------------------------------------------------------------------------------------- + IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -1049,44 +1087,6 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @WaitAtLowPriorityMaxDuration < 0 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1 - END - - ---------------------------------------------------------------------------------------------------- - - IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') - BEGIN - 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 @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 @SortInTempdb = 'Y' - BEGIN - 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, [State]) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index ec2cd477..11ec0dcb 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: 2026-06-08 09:12:40 +Version: 2026-06-09 19:19:51 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 09:12:40 //-- + --// Version: 2026-06-09 19:19:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 09:12:40 //-- + --// Version: 2026-06-09 19:19:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3268,7 +3268,9 @@ BEGIN WHERE database_id = DB_ID(@CurrentDatabaseName) END - IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentInStandby = 1) + IF @CurrentDatabaseState = 'ONLINE' + AND NOT @CurrentUserAccess = 'SINGLE_USER' + AND NOT @CurrentInStandby = 1 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) @@ -4850,7 +4852,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 09:12:40 //-- + --// Version: 2026-06-09 19:19:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6768,6 +6770,9 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @FillFactor int = NULL, @PadIndex nvarchar(max) = NULL, @DataCompression nvarchar(max) = NULL, +@WaitAtLowPriorityMaxDuration int = NULL, +@WaitAtLowPriorityAbortAfterWait nvarchar(max) = NULL, +@Resumable nvarchar(max) = 'N', @LOBCompaction nvarchar(max) = 'Y', @UpdateStatistics nvarchar(max) = NULL, @OnlyModifiedStatistics nvarchar(max) = 'N', @@ -6780,9 +6785,6 @@ ALTER PROCEDURE [dbo].[IndexOptimize] @Indexes nvarchar(max) = NULL, @TimeLimit int = NULL, @Delay int = NULL, -@WaitAtLowPriorityMaxDuration int = NULL, -@WaitAtLowPriorityAbortAfterWait nvarchar(max) = NULL, -@Resumable nvarchar(max) = 'N', @AvailabilityGroups nvarchar(max) = NULL, @LockTimeout int = NULL, @LockMessageSeverity int = 16, @@ -6801,7 +6803,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-08 09:12:40 //-- + --// Version: 2026-06-09 19:19:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7051,6 +7053,9 @@ BEGIN SET @Parameters += ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar(max)),'NULL') SET @Parameters += ', @PadIndex = ' + ISNULL('''' + REPLACE(@PadIndex,'''','''''') + '''','NULL') SET @Parameters += ', @DataCompression = ' + ISNULL('''' + REPLACE(@DataCompression,'''','''''') + '''','NULL') + SET @Parameters += ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)),'NULL') + SET @Parameters += ', @WaitAtLowPriorityAbortAfterWait = ' + ISNULL('''' + REPLACE(@WaitAtLowPriorityAbortAfterWait,'''','''''') + '''','NULL') + SET @Parameters += ', @Resumable = ' + ISNULL('''' + REPLACE(@Resumable,'''','''''') + '''','NULL') SET @Parameters += ', @LOBCompaction = ' + ISNULL('''' + REPLACE(@LOBCompaction,'''','''''') + '''','NULL') SET @Parameters += ', @UpdateStatistics = ' + ISNULL('''' + REPLACE(@UpdateStatistics,'''','''''') + '''','NULL') SET @Parameters += ', @OnlyModifiedStatistics = ' + ISNULL('''' + REPLACE(@OnlyModifiedStatistics,'''','''''') + '''','NULL') @@ -7063,9 +7068,6 @@ BEGIN SET @Parameters += ', @Indexes = ' + ISNULL('''' + REPLACE(@Indexes,'''','''''') + '''','NULL') SET @Parameters += ', @TimeLimit = ' + ISNULL(CAST(@TimeLimit AS nvarchar(max)),'NULL') SET @Parameters += ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar(max)),'NULL') - SET @Parameters += ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)),'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(max)),'NULL') SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar(max)),'NULL') @@ -7660,6 +7662,44 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @WaitAtLowPriorityMaxDuration < 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1 + END + + ---------------------------------------------------------------------------------------------------- + + IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') + BEGIN + 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 @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 @SortInTempdb = 'Y' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 3 + END + + ---------------------------------------------------------------------------------------------------- + IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -7794,44 +7834,6 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @WaitAtLowPriorityMaxDuration < 0 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1 - END - - ---------------------------------------------------------------------------------------------------- - - IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') - BEGIN - 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 @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 @SortInTempdb = 'Y' - BEGIN - 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, [State]) From 307d1838186a80123643ea42cefc49156ccac304 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 13 Jun 2026 23:47:54 +0200 Subject: [PATCH 045/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 42 +++++++++++++++--------------- DatabaseIntegrityCheck.sql | 4 +-- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 52 +++++++++++++++++++------------------- 5 files changed, 51 insertions(+), 51 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 61db885f..ec47d2ca 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-09 19:19:51 //-- + --// Version: 2026-06-13 22:45:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 9ef733db..5c5df2ba 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-09 19:19:51 //-- + --// Version: 2026-06-13 22:45:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1257,7 +1257,7 @@ BEGIN END IF @Compress = 'Y' AND @BackupSoftware IS NULL - AND NOT (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786, -1785266663)) + AND NOT (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @Compress is not supported. Backup compression is not supported in this edition of SQL Server.', 16, 2 @@ -1671,7 +1671,7 @@ BEGIN SELECT 'The value for the parameter @Encrypt is not supported.', 16, 1 END - IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (SERVERPROPERTY('EngineEdition') IN(3, 8) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786, -1785266663)) + IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (SERVERPROPERTY('EngineEdition') IN(3, 8) OR SERVERPROPERTY('EditionID') IN(-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @Encrypt is not supported.', 16, 2 @@ -3110,8 +3110,8 @@ BEGIN 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}','') - IF @BackupSetName IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupSetName}','') + IF @Description IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}','') + IF @BackupSetName IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@BackupSetName,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupSetName}','') IF @Directory IS NULL AND @MirrorDirectory IS NULL AND @URL IS NULL AND @DefaultDirectory LIKE '%' + '.' + @@SERVICENAME + @DirectorySeparator + 'MSSQL' + @DirectorySeparator + 'Backup' BEGIN @@ -3259,7 +3259,7 @@ BEGIN -- Directory structure - replace tokens with real values SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}',@DirectorySeparator) - 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,'{ServerName}',CASE WHEN SERVERPROPERTY('EngineEdition') = 8 AND CHARINDEX('.',CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) > 0 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,'')) @@ -3320,8 +3320,8 @@ BEGIN 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 @BackupSetName IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{BackupSetName}','') + IF @Description IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}','') + IF @BackupSetName IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@BackupSetName,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{BackupSetName}','') IF @CurrentNumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileNumber}','') IF @CurrentNumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}','') @@ -3424,7 +3424,7 @@ BEGIN END -- File name - replace tokens with real values - 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,'{ServerName}',CASE WHEN SERVERPROPERTY('EngineEdition') = 8 AND CHARINDEX('.',CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) > 0 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,'')) @@ -3453,7 +3453,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' 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 @@ -3485,7 +3485,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(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles >= 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) IF @CurrentDirectoryPath = 'NUL' BEGIN @@ -3522,7 +3522,7 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) AND Mirror = 1 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles >= 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -3552,7 +3552,7 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) AND Mirror = 0 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles >= 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -3582,7 +3582,7 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 1) AND Mirror = 1 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles >= 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -3722,7 +3722,7 @@ BEGIN 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 OR @ReturnCode IS NULL RAISERROR(''Error deleting files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + REPLACE(@CurrentFileExtension,'''','''''') + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' @@ -3731,7 +3731,7 @@ BEGIN 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(max)) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + REPLACE(@CurrentFileExtension,'''','''''') + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar(max)) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -3749,7 +3749,7 @@ BEGIN SET @CurrentCommandType = 'xp_ss_delete' - 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(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + REPLACE(@CurrentFileExtension,'''','''''') + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @EncryptionKey = @EncryptionKey, @EncryptionKeyPlaceholder = @EncryptionKeyPlaceholder, @LogToTable = @LogToTable, @Execute = @Execute @@ -4017,7 +4017,7 @@ BEGIN IF @DataDomainBoostNoOutputTable = 'Y' SET @CurrentCommand += 'INSERT INTO @DataDomainBoostOutput ([Message]) ' SET @CurrentCommand += 'EXECUTE @ReturnCode = dbo.emc_run_backup ''' - SET @CurrentCommand += ' -c ' + CASE WHEN @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)) END + SET @CurrentCommand += ' -c ' + CASE WHEN @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL THEN REPLACE(@Cluster,'''','''''') ELSE REPLACE(CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)),'''','''''') END SET @CurrentCommand += ' -l ' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'full' @@ -4245,7 +4245,7 @@ BEGIN 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 OR @ReturnCode IS NULL RAISERROR(''Error deleting files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + REPLACE(@CurrentFileExtension,'''','''''') + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' @@ -4254,7 +4254,7 @@ BEGIN 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(max)) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + REPLACE(@CurrentFileExtension,'''','''''') + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar(max)) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -4272,7 +4272,7 @@ BEGIN SET @CurrentCommandType = 'xp_ss_delete' - 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(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + REPLACE(@CurrentFileExtension,'''','''''') + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @EncryptionKey = @EncryptionKey, @EncryptionKeyPlaceholder = @EncryptionKeyPlaceholder, @LogToTable = @LogToTable, @Execute = @Execute diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 3779eac3..bde6825c 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-09 19:19:51 //-- + --// Version: 2026-06-13 22:45:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1796,7 +1796,7 @@ BEGIN SET @CurrentCommand = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - SET @CurrentCommand += 'DBCC CHECKTABLE (N' + QUOTENAME(QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName),'''') + SET @CurrentCommand += 'DBCC CHECKTABLE (N''' + REPLACE(QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName),'''','''''') + '''' IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' SET @CurrentCommand += ') WITH ALL_ERRORMSGS' IF @DataPurity = 'Y' SET @CurrentCommand += ', DATA_PURITY' diff --git a/IndexOptimize.sql b/IndexOptimize.sql index b72cd7b4..134cbb5e 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-09 19:19:51 //-- + --// Version: 2026-06-13 22:45:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 11ec0dcb..6856cffd 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: 2026-06-09 19:19:51 +Version: 2026-06-13 22:45:08 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-09 19:19:51 //-- + --// Version: 2026-06-13 22:45:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-09 19:19:51 //-- + --// Version: 2026-06-13 22:45:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1662,7 +1662,7 @@ BEGIN END IF @Compress = 'Y' AND @BackupSoftware IS NULL - AND NOT (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, 284895786, -1785266663)) + AND NOT (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @Compress is not supported. Backup compression is not supported in this edition of SQL Server.', 16, 2 @@ -2076,7 +2076,7 @@ BEGIN SELECT 'The value for the parameter @Encrypt is not supported.', 16, 1 END - IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (SERVERPROPERTY('EngineEdition') IN(3, 8) OR SERVERPROPERTY('EditionID') IN(-1534726760, 284895786, -1785266663)) + IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (SERVERPROPERTY('EngineEdition') IN(3, 8) OR SERVERPROPERTY('EditionID') IN(-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @Encrypt is not supported.', 16, 2 @@ -3515,8 +3515,8 @@ BEGIN 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}','') - IF @BackupSetName IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupSetName}','') + IF @Description IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}','') + IF @BackupSetName IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@BackupSetName,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupSetName}','') IF @Directory IS NULL AND @MirrorDirectory IS NULL AND @URL IS NULL AND @DefaultDirectory LIKE '%' + '.' + @@SERVICENAME + @DirectorySeparator + 'MSSQL' + @DirectorySeparator + 'Backup' BEGIN @@ -3664,7 +3664,7 @@ BEGIN -- Directory structure - replace tokens with real values SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}',@DirectorySeparator) - 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,'{ServerName}',CASE WHEN SERVERPROPERTY('EngineEdition') = 8 AND CHARINDEX('.',CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) > 0 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,'')) @@ -3725,8 +3725,8 @@ BEGIN 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 @BackupSetName IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{BackupSetName}','') + IF @Description IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}','') + IF @BackupSetName IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@BackupSetName,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{BackupSetName}','') IF @CurrentNumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileNumber}','') IF @CurrentNumberOfFiles = 1 SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}','') @@ -3829,7 +3829,7 @@ BEGIN END -- File name - replace tokens with real values - 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,'{ServerName}',CASE WHEN SERVERPROPERTY('EngineEdition') = 8 AND CHARINDEX('.',CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) > 0 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,'')) @@ -3858,7 +3858,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' 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 @@ -3890,7 +3890,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(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles >= 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) IF @CurrentDirectoryPath = 'NUL' BEGIN @@ -3927,7 +3927,7 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentDirectories WHERE Mirror = 1) AND Mirror = 1 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles >= 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -3957,7 +3957,7 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 0) AND Mirror = 0 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles >= 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -3987,7 +3987,7 @@ BEGIN AND @CurrentFileNumber <= DirectoryNumber * (SELECT @CurrentNumberOfFiles / COUNT(*) FROM @CurrentURLs WHERE Mirror = 1) AND Mirror = 1 - SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles > 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) + SET @CurrentFileName = REPLACE(@CurrentDatabaseFileName, '{FileNumber}', CASE WHEN @CurrentNumberOfFiles >= 1 AND @CurrentNumberOfFiles <= 9 THEN CAST(@CurrentFileNumber AS nvarchar(max)) WHEN @CurrentNumberOfFiles >= 10 THEN RIGHT('0' + CAST(@CurrentFileNumber AS nvarchar(max)),2) ELSE '' END) SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName @@ -4127,7 +4127,7 @@ BEGIN 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 OR @ReturnCode IS NULL RAISERROR(''Error deleting files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + REPLACE(@CurrentFileExtension,'''','''''') + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' @@ -4136,7 +4136,7 @@ BEGIN 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(max)) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + REPLACE(@CurrentFileExtension,'''','''''') + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar(max)) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -4154,7 +4154,7 @@ BEGIN SET @CurrentCommandType = 'xp_ss_delete' - 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(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + REPLACE(@CurrentFileExtension,'''','''''') + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @EncryptionKey = @EncryptionKey, @EncryptionKeyPlaceholder = @EncryptionKeyPlaceholder, @LogToTable = @LogToTable, @Execute = @Execute @@ -4422,7 +4422,7 @@ BEGIN IF @DataDomainBoostNoOutputTable = 'Y' SET @CurrentCommand += 'INSERT INTO @DataDomainBoostOutput ([Message]) ' SET @CurrentCommand += 'EXECUTE @ReturnCode = dbo.emc_run_backup ''' - SET @CurrentCommand += ' -c ' + CASE WHEN @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL THEN @Cluster ELSE CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)) END + SET @CurrentCommand += ' -c ' + CASE WHEN @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL THEN REPLACE(@Cluster,'''','''''') ELSE REPLACE(CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)),'''','''''') END SET @CurrentCommand += ' -l ' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'full' @@ -4650,7 +4650,7 @@ BEGIN 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 OR @ReturnCode IS NULL RAISERROR(''Error deleting files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_delete_file 0, N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + ''', ''' + REPLACE(@CurrentFileExtension,'''','''''') + ''', ''' + CONVERT(nvarchar(19),@CurrentCleanupDate,126) + ''' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting files.'', 16, 1)' END IF @BackupSoftware = 'LITESPEED' @@ -4659,7 +4659,7 @@ BEGIN 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(max)) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_slssqlmaint N''-MAINTDEL -DELFOLDER "' + REPLACE(@CurrentDirectoryPath,'''','''''') + '" -DELEXTENSION "' + REPLACE(@CurrentFileExtension,'''','''''') + '" -DELUNIT "' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar(max)) + '" -DELUNITTYPE "minutes" -DELUSEAGE'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting LiteSpeed backup files.'', 16, 1)' END IF @BackupSoftware = 'SQLBACKUP' @@ -4677,7 +4677,7 @@ BEGIN SET @CurrentCommandType = 'xp_ss_delete' - 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(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' + SET @CurrentCommand = 'DECLARE @ReturnCode int EXECUTE @ReturnCode = dbo.xp_ss_delete @filename = N''' + REPLACE(@CurrentDirectoryPath,'''','''''') + '\*.' + REPLACE(@CurrentFileExtension,'''','''''') + ''', @age = ''' + CAST(DATEDIFF(mi,@CurrentCleanupDate,SYSDATETIME()) + 1 AS nvarchar(max)) + 'Minutes'' IF @ReturnCode <> 0 OR @ReturnCode IS NULL RAISERROR(''Error deleting SQLsafe backup files.'', 16, 1)' END EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 1, @DatabaseName = @CurrentDatabaseName, @EncryptionKey = @EncryptionKey, @EncryptionKeyPlaceholder = @EncryptionKeyPlaceholder, @LogToTable = @LogToTable, @Execute = @Execute @@ -4852,7 +4852,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-09 19:19:51 //-- + --// Version: 2026-06-13 22:45:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6608,7 +6608,7 @@ BEGIN SET @CurrentCommand = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - SET @CurrentCommand += 'DBCC CHECKTABLE (N' + QUOTENAME(QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName),'''') + SET @CurrentCommand += 'DBCC CHECKTABLE (N''' + REPLACE(QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName),'''','''''') + '''' IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' SET @CurrentCommand += ') WITH ALL_ERRORMSGS' IF @DataPurity = 'Y' SET @CurrentCommand += ', DATA_PURITY' @@ -6803,7 +6803,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-09 19:19:51 //-- + --// Version: 2026-06-13 22:45:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 94906513a2553ca069387e443f76353333899d50 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 15 Jun 2026 20:54:17 +0200 Subject: [PATCH 046/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 10 +++++----- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index ec47d2ca..f2f03911 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-13 22:45:08 //-- + --// Version: 2026-06-15 19:51:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 5c5df2ba..b1256a51 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-13 22:45:08 //-- + --// Version: 2026-06-15 19:51:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index bde6825c..2d38f213 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-13 22:45:08 //-- + --// Version: 2026-06-15 19:51:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 134cbb5e..a068fa38 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-13 22:45:08 //-- + --// Version: 2026-06-15 19:51:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 6856cffd..ef4f38b4 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: 2026-06-13 22:45:08 +Version: 2026-06-15 19:51:16 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-13 22:45:08 //-- + --// Version: 2026-06-15 19:51:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-13 22:45:08 //-- + --// Version: 2026-06-15 19:51:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4852,7 +4852,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-13 22:45:08 //-- + --// Version: 2026-06-15 19:51:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6803,7 +6803,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-13 22:45:08 //-- + --// Version: 2026-06-15 19:51:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 689e88f2030c9a30528da751f7f74d27892a2273 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 15 Jun 2026 20:55:19 +0200 Subject: [PATCH 047/177] Add files via upload From 7bf729f2db2792fcdf07afcd250176434a50d7d2 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 16 Jun 2026 06:10:11 +0200 Subject: [PATCH 048/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 10 ++++++++-- DatabaseIntegrityCheck.sql | 6 +++--- IndexOptimize.sql | 8 ++++---- MaintenanceSolution.sql | 28 +++++++++++++++++----------- 5 files changed, 33 insertions(+), 21 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index f2f03911..5c85a0ed 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-15 19:51:16 //-- + --// Version: 2026-06-16 06:09:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index b1256a51..c345f8e2 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-15 19:51:16 //-- + --// Version: 2026-06-16 06:09:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1343,6 +1343,12 @@ BEGIN SELECT 'The value for the parameter @ChangeBackupType is not supported.', 16, 1 END + IF @ChangeBackupType = 'Y' AND NOT @BackupType IN ('DIFF', 'LOG') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'Setting @ChangeBackupType to ''Y'' is only supported with differential and log backups.', 16, 2 + END + ---------------------------------------------------------------------------------------------------- IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') @@ -2376,7 +2382,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 2d38f213..47a4e498 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-15 19:51:16 //-- + --// Version: 2026-06-16 06:09:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -871,7 +871,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @LockMessageSeverity NOT IN(10, 16) + IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 @@ -879,7 +879,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 diff --git a/IndexOptimize.sql b/IndexOptimize.sql index a068fa38..8259ad95 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-15 19:51:16 //-- + --// Version: 2026-06-16 06:09:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1095,7 +1095,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @LockMessageSeverity NOT IN(10, 16) + IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 @@ -1103,7 +1103,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 @@ -2329,7 +2329,7 @@ BEGIN 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 + ', ' + SET @CurrentComment += 'StatisticsType: ' + 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 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' ELSE 'N/A' END + ', ' SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar(max)),'N/A') + ', ' diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index ef4f38b4..2c24e454 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: 2026-06-15 19:51:16 +Version: 2026-06-16 06:09:15 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-15 19:51:16 //-- + --// Version: 2026-06-16 06:09:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-15 19:51:16 //-- + --// Version: 2026-06-16 06:09:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1748,6 +1748,12 @@ BEGIN SELECT 'The value for the parameter @ChangeBackupType is not supported.', 16, 1 END + IF @ChangeBackupType = 'Y' AND NOT @BackupType IN ('DIFF', 'LOG') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'Setting @ChangeBackupType to ''Y'' is only supported with differential and log backups.', 16, 2 + END + ---------------------------------------------------------------------------------------------------- IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') @@ -2781,7 +2787,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 @@ -4852,7 +4858,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-15 19:51:16 //-- + --// Version: 2026-06-16 06:09:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5683,7 +5689,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @LockMessageSeverity NOT IN(10, 16) + IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 @@ -5691,7 +5697,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 @@ -6803,7 +6809,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-15 19:51:16 //-- + --// Version: 2026-06-16 06:09:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7842,7 +7848,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @LockMessageSeverity NOT IN(10, 16) + IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 @@ -7850,7 +7856,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) > 1 + IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 @@ -9076,7 +9082,7 @@ BEGIN 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 + ', ' + SET @CurrentComment += 'StatisticsType: ' + 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 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' ELSE 'N/A' END + ', ' SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar(max)),'N/A') + ', ' From bec8ad912890179b6649121dbb47d237c1de5eaf Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 16 Jun 2026 20:03:50 +0200 Subject: [PATCH 049/177] 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 5c85a0ed..83120181 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-16 06:09:15 //-- + --// Version: 2026-06-16 20:02:59 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index c345f8e2..725693b9 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-16 06:09:15 //-- + --// Version: 2026-06-16 20:02:59 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 47a4e498..5aeff24f 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-16 06:09:15 //-- + --// Version: 2026-06-16 20:02:59 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 8259ad95..f22ca4e5 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-16 06:09:15 //-- + --// Version: 2026-06-16 20:02:59 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2284,13 +2284,13 @@ BEGIN IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END + SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 AND @CurrentHasClusteredColumnstore = 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 @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 AND @CurrentHasClusteredColumnstore = 0) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max)) + SELECT 'MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max)) END IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 2c24e454..143b4401 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: 2026-06-16 06:09:15 +Version: 2026-06-16 20:02:59 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-16 06:09:15 //-- + --// Version: 2026-06-16 20:02:59 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-16 06:09:15 //-- + --// Version: 2026-06-16 20:02:59 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4858,7 +4858,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-16 06:09:15 //-- + --// Version: 2026-06-16 20:02:59 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6809,7 +6809,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-16 06:09:15 //-- + --// Version: 2026-06-16 20:02:59 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -9037,13 +9037,13 @@ BEGIN IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END + SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 AND @CurrentHasClusteredColumnstore = 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 @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 AND @CurrentHasClusteredColumnstore = 0) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max)) + SELECT 'MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max)) END IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' From 7835358118c7039c41406989206abd42b68aca11 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 20 Jun 2026 15:03:06 +0200 Subject: [PATCH 050/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 3 ++- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 11 ++++++----- 5 files changed, 11 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 83120181..cfbaa369 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-16 20:02:59 //-- + --// Version: 2026-06-20 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 725693b9..6a4e0d6f 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-16 20:02:59 //-- + --// Version: 2026-06-20 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 5aeff24f..dde46d08 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-16 20:02:59 //-- + --// Version: 2026-06-20 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1669,6 +1669,7 @@ BEGIN SET @CurrentCommand = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'DBCC CHECKALLOC (' + QUOTENAME(@CurrentDatabaseName) + IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' SET @CurrentCommand += ') WITH ALL_ERRORMSGS' IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ', NO_INFOMSGS' IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' diff --git a/IndexOptimize.sql b/IndexOptimize.sql index f22ca4e5..9e9ddb54 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-16 20:02:59 //-- + --// Version: 2026-06-20 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 143b4401..e9501b7e 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: 2026-06-16 20:02:59 +Version: 2026-06-20 15:00:38 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-16 20:02:59 //-- + --// Version: 2026-06-20 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-16 20:02:59 //-- + --// Version: 2026-06-20 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4858,7 +4858,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-16 20:02:59 //-- + --// Version: 2026-06-20 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6487,6 +6487,7 @@ BEGIN SET @CurrentCommand = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'DBCC CHECKALLOC (' + QUOTENAME(@CurrentDatabaseName) + IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' SET @CurrentCommand += ') WITH ALL_ERRORMSGS' IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ', NO_INFOMSGS' IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' @@ -6809,7 +6810,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-16 20:02:59 //-- + --// Version: 2026-06-20 15:00:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 824bd62f71e038ecace497ef6426352c2ab37dfd Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 21 Jun 2026 12:30:49 +0200 Subject: [PATCH 051/177] Add files via upload --- CommandExecute.sql | 4 ++-- DatabaseBackup.sql | 4 ++-- DatabaseIntegrityCheck.sql | 4 ++-- IndexOptimize.sql | 4 ++-- MaintenanceSolution.sql | 18 +++++++++--------- 5 files changed, 17 insertions(+), 17 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index cfbaa369..762cc8c9 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-20 15:00:38 //-- + --// Version: 2026-06-21 12:30:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -158,7 +158,7 @@ BEGIN --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 6a4e0d6f..6a11fb90 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-20 15:00:38 //-- + --// Version: 2026-06-21 12:30:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2480,7 +2480,7 @@ BEGIN --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index dde46d08..4430537b 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-20 15:00:38 //-- + --// Version: 2026-06-21 12:30:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1041,7 +1041,7 @@ BEGIN --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 9e9ddb54..79e5920b 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-20 15:00:38 //-- + --// Version: 2026-06-21 12:30:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1222,7 +1222,7 @@ BEGIN --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index e9501b7e..6fee5a9b 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: 2026-06-20 15:00:38 +Version: 2026-06-21 12:30:01 You can contact me by e-mail at ola@hallengren.com. @@ -139,7 +139,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-20 15:00:38 //-- + --// Version: 2026-06-21 12:30:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -259,7 +259,7 @@ BEGIN --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor @@ -498,7 +498,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-20 15:00:38 //-- + --// Version: 2026-06-21 12:30:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2885,7 +2885,7 @@ BEGIN --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor @@ -4858,7 +4858,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-20 15:00:38 //-- + --// Version: 2026-06-21 12:30:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5859,7 +5859,7 @@ BEGIN --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor @@ -6810,7 +6810,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-20 15:00:38 //-- + --// Version: 2026-06-21 12:30:01 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7976,7 +7976,7 @@ BEGIN --// Raise errors //-- ---------------------------------------------------------------------------------------------------- - DECLARE ErrorCursor CURSOR FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC + DECLARE ErrorCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC OPEN ErrorCursor From b9d87eee6a391196b98cd2f64ae6d277c51a8d90 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 21 Jun 2026 12:41:50 +0200 Subject: [PATCH 052/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 16 +++++----------- 5 files changed, 9 insertions(+), 15 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 762cc8c9..41354ddc 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-21 12:30:01 //-- + --// Version: 2026-06-21 12:38:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 6a11fb90..eaba90ea 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:30:01 //-- + --// Version: 2026-06-21 12:38:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 4430537b..4a76f1a3 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:30:01 //-- + --// Version: 2026-06-21 12:38:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 79e5920b..0533447b 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:30:01 //-- + --// Version: 2026-06-21 12:38:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 6fee5a9b..2825ed05 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: 2026-06-21 12:30:01 +Version: 2026-06-21 12:38:26 You can contact me by e-mail at ola@hallengren.com. @@ -38,12 +38,6 @@ BEGIN RAISERROR(@ErrorMessage,16,1) WITH NOWAIT END -IF NOT (SELECT [compatibility_level] FROM sys.databases WHERE [name] = DB_NAME()) >= 90 -BEGIN - SET @ErrorMessage = 'The database ' + QUOTENAME(DB_NAME()) + ' has to be in compatibility level 90 or higher.' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT -END - IF @BackupDirectory IS NOT NULL AND @BackupURL IS NOT NULL BEGIN SET @ErrorMessage = 'Only one of the variables @BackupDirectory and @BackupURL can be set.' @@ -139,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:30:01 //-- + --// Version: 2026-06-21 12:38:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -498,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:30:01 //-- + --// Version: 2026-06-21 12:38:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4858,7 +4852,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:30:01 //-- + --// Version: 2026-06-21 12:38:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6810,7 +6804,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:30:01 //-- + --// Version: 2026-06-21 12:38:26 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From c4295f52a8823a7f2200f40fd3a01d7b8f44cbd9 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 21 Jun 2026 12:56:48 +0200 Subject: [PATCH 053/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 +++++------- 5 files changed, 9 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 41354ddc..9b1a79e5 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-21 12:38:26 //-- + --// Version: 2026-06-21 12:55:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index eaba90ea..071ecd19 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:38:26 //-- + --// Version: 2026-06-21 12:55:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 4a76f1a3..24a1423c 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:38:26 //-- + --// Version: 2026-06-21 12:55:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 0533447b..d9b0dd73 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:38:26 //-- + --// Version: 2026-06-21 12:55:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 2825ed05..93107963 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: 2026-06-21 12:38:26 +Version: 2026-06-21 12:55:55 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:38:26 //-- + --// Version: 2026-06-21 12:55:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:38:26 //-- + --// Version: 2026-06-21 12:55:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4852,7 +4852,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:38:26 //-- + --// Version: 2026-06-21 12:55:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6804,7 +6804,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:38:26 //-- + --// Version: 2026-06-21 12:55:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -9360,8 +9360,6 @@ BEGIN DECLARE @CurrentJobStepDatabaseName nvarchar(max) DECLARE @CurrentOutputFileName nvarchar(max) - DECLARE @Version numeric(18,10) = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4) + '.' + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),2) AS numeric(18,10)) - DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END SELECT @HostPlatform = host_platform From 627ac4525babf672af2b8371451c166600590d4c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 25 Jun 2026 10:26:05 +0200 Subject: [PATCH 054/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 14 ++++----- DatabaseIntegrityCheck.sql | 26 ++++++++-------- IndexOptimize.sql | 20 ++++++------ MaintenanceSolution.sql | 64 +++++++++++++++++++------------------- 5 files changed, 63 insertions(+), 63 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 9b1a79e5..6598b849 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-21 12:55:55 //-- + --// Version: 2026-06-25 10:21:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 071ecd19..481689d2 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:55:55 //-- + --// Version: 2026-06-25 10:21:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -580,7 +580,7 @@ BEGIN SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(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 @@ -589,7 +589,7 @@ BEGIN SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(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 = 0 @@ -600,7 +600,7 @@ BEGIN INNER JOIN (SELECT tmpDatabases.DatabaseName, MIN(SelectedDatabases.StartPosition) AS StartPosition FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(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 @@ -671,14 +671,14 @@ BEGIN SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 1 UPDATE tmpAvailabilityGroups SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 UPDATE tmpAvailabilityGroups @@ -687,7 +687,7 @@ BEGIN INNER JOIN (SELECT tmpAvailabilityGroups.AvailabilityGroupName, MIN(SelectedAvailabilityGroups.StartPosition) AS StartPosition FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 1 GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2 ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 24a1423c..fe966c2f 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:55:55 //-- + --// Version: 2026-06-25 10:21:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -424,7 +424,7 @@ BEGIN SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(REPLACE(SelectedDatabases.DatabaseName,'[','[[]'),'_','[_]') AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL) AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) AND NOT ((tmpDatabases.DatabaseName = 'tempdb' OR tmpDatabases.[Snapshot] = 1) AND tmpDatabases.DatabaseName <> SelectedDatabases.DatabaseName) @@ -434,7 +434,7 @@ BEGIN SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(REPLACE(SelectedDatabases.DatabaseName,'[','[[]'),'_','[_]') AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL) AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) AND NOT ((tmpDatabases.DatabaseName = 'tempdb' OR tmpDatabases.[Snapshot] = 1) AND tmpDatabases.DatabaseName <> SelectedDatabases.DatabaseName) @@ -446,7 +446,7 @@ BEGIN INNER JOIN (SELECT tmpDatabases.DatabaseName, MIN(SelectedDatabases.StartPosition) AS StartPosition FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(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 @@ -517,14 +517,14 @@ BEGIN SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 1 UPDATE tmpAvailabilityGroups SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 UPDATE tmpAvailabilityGroups @@ -533,7 +533,7 @@ BEGIN INNER JOIN (SELECT tmpAvailabilityGroups.AvailabilityGroupName, MIN(SelectedAvailabilityGroups.StartPosition) AS StartPosition FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 1 GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2 ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName @@ -1538,14 +1538,14 @@ BEGIN SET tmpFileGroups.Selected = SelectedFileGroups.Selected FROM @tmpFileGroups tmpFileGroups INNER JOIN @SelectedFileGroups SelectedFileGroups - ON @CurrentDatabaseName LIKE REPLACE(SelectedFileGroups.DatabaseName,'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(SelectedFileGroups.FileGroupName,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedFileGroups.DatabaseName,'[','[[]'),'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(REPLACE(SelectedFileGroups.FileGroupName,'[','[[]'),'_','[_]') WHERE SelectedFileGroups.Selected = 1 UPDATE tmpFileGroups SET tmpFileGroups.Selected = SelectedFileGroups.Selected FROM @tmpFileGroups tmpFileGroups INNER JOIN @SelectedFileGroups SelectedFileGroups - ON @CurrentDatabaseName LIKE REPLACE(SelectedFileGroups.DatabaseName,'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(SelectedFileGroups.FileGroupName,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedFileGroups.DatabaseName,'[','[[]'),'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(REPLACE(SelectedFileGroups.FileGroupName,'[','[[]'),'_','[_]') WHERE SelectedFileGroups.Selected = 0 UPDATE tmpFileGroups @@ -1554,7 +1554,7 @@ BEGIN 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,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedFileGroups.DatabaseName,'[','[[]'),'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(REPLACE(SelectedFileGroups.FileGroupName,'[','[[]'),'_','[_]') WHERE SelectedFileGroups.Selected = 1 GROUP BY tmpFileGroups.FileGroupName) SelectedFileGroups2 ON tmpFileGroups.FileGroupName = SelectedFileGroups2.FileGroupName @@ -1704,14 +1704,14 @@ BEGIN SET tmpObjects.Selected = SelectedObjects.Selected 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,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedObjects.DatabaseName,'[','[[]'),'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(REPLACE(SelectedObjects.SchemaName,'[','[[]'),'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(REPLACE(SelectedObjects.ObjectName,'[','[[]'),'_','[_]') WHERE SelectedObjects.Selected = 1 UPDATE tmpObjects SET tmpObjects.Selected = SelectedObjects.Selected 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,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedObjects.DatabaseName,'[','[[]'),'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(REPLACE(SelectedObjects.SchemaName,'[','[[]'),'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(REPLACE(SelectedObjects.ObjectName,'[','[[]'),'_','[_]') WHERE SelectedObjects.Selected = 0 UPDATE tmpObjects @@ -1720,7 +1720,7 @@ BEGIN 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,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedObjects.DatabaseName,'[','[[]'),'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(REPLACE(SelectedObjects.SchemaName,'[','[[]'),'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(REPLACE(SelectedObjects.ObjectName,'[','[[]'),'_','[_]') WHERE SelectedObjects.Selected = 1 GROUP BY tmpObjects.SchemaName, tmpObjects.ObjectName) SelectedObjects2 ON tmpObjects.SchemaName = SelectedObjects2.SchemaName AND tmpObjects.ObjectName = SelectedObjects2.ObjectName diff --git a/IndexOptimize.sql b/IndexOptimize.sql index d9b0dd73..3bd1e41a 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:55:55 //-- + --// Version: 2026-06-25 10:21:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -521,7 +521,7 @@ BEGIN SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(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 @@ -530,7 +530,7 @@ BEGIN SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(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 = 0 @@ -541,7 +541,7 @@ BEGIN INNER JOIN (SELECT tmpDatabases.DatabaseName, MIN(SelectedDatabases.StartPosition) AS StartPosition FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(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 @@ -612,14 +612,14 @@ BEGIN SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 1 UPDATE tmpAvailabilityGroups SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 UPDATE tmpAvailabilityGroups @@ -628,7 +628,7 @@ BEGIN INNER JOIN (SELECT tmpAvailabilityGroups.AvailabilityGroupName, MIN(SelectedAvailabilityGroups.StartPosition) AS StartPosition FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 1 GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2 ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName @@ -1805,14 +1805,14 @@ BEGIN SET tmpIndexesStatistics.Selected = SelectedIndexes.Selected 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,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(REPLACE(SelectedIndexes.IndexName,'[','[[]'),'_','[_]') WHERE SelectedIndexes.Selected = 1 UPDATE tmpIndexesStatistics SET tmpIndexesStatistics.Selected = SelectedIndexes.Selected 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,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(REPLACE(SelectedIndexes.IndexName,'[','[[]'),'_','[_]') WHERE SelectedIndexes.Selected = 0 UPDATE tmpIndexesStatistics @@ -1821,7 +1821,7 @@ BEGIN 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,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(REPLACE(SelectedIndexes.IndexName,'[','[[]'),'_','[_]') WHERE SelectedIndexes.Selected = 1 GROUP BY tmpIndexesStatistics.SchemaName, tmpIndexesStatistics.ObjectName, tmpIndexesStatistics.IndexName, tmpIndexesStatistics.StatisticsName) SelectedIndexes2 ON tmpIndexesStatistics.SchemaName = SelectedIndexes2.SchemaName diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 93107963..d6287d8f 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: 2026-06-21 12:55:55 +Version: 2026-06-25 10:21:34 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:55:55 //-- + --// Version: 2026-06-25 10:21:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:55:55 //-- + --// Version: 2026-06-25 10:21:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -979,7 +979,7 @@ BEGIN SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(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 @@ -988,7 +988,7 @@ BEGIN SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(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 = 0 @@ -999,7 +999,7 @@ BEGIN INNER JOIN (SELECT tmpDatabases.DatabaseName, MIN(SelectedDatabases.StartPosition) AS StartPosition FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(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 @@ -1070,14 +1070,14 @@ BEGIN SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 1 UPDATE tmpAvailabilityGroups SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 UPDATE tmpAvailabilityGroups @@ -1086,7 +1086,7 @@ BEGIN INNER JOIN (SELECT tmpAvailabilityGroups.AvailabilityGroupName, MIN(SelectedAvailabilityGroups.StartPosition) AS StartPosition FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 1 GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2 ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName @@ -4852,7 +4852,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:55:55 //-- + --// Version: 2026-06-25 10:21:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5236,7 +5236,7 @@ BEGIN SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(REPLACE(SelectedDatabases.DatabaseName,'[','[[]'),'_','[_]') AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL) AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) AND NOT ((tmpDatabases.DatabaseName = 'tempdb' OR tmpDatabases.[Snapshot] = 1) AND tmpDatabases.DatabaseName <> SelectedDatabases.DatabaseName) @@ -5246,7 +5246,7 @@ BEGIN SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(REPLACE(SelectedDatabases.DatabaseName,'[','[[]'),'_','[_]') AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL) AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) AND NOT ((tmpDatabases.DatabaseName = 'tempdb' OR tmpDatabases.[Snapshot] = 1) AND tmpDatabases.DatabaseName <> SelectedDatabases.DatabaseName) @@ -5258,7 +5258,7 @@ BEGIN INNER JOIN (SELECT tmpDatabases.DatabaseName, MIN(SelectedDatabases.StartPosition) AS StartPosition FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(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 @@ -5329,14 +5329,14 @@ BEGIN SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 1 UPDATE tmpAvailabilityGroups SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 UPDATE tmpAvailabilityGroups @@ -5345,7 +5345,7 @@ BEGIN INNER JOIN (SELECT tmpAvailabilityGroups.AvailabilityGroupName, MIN(SelectedAvailabilityGroups.StartPosition) AS StartPosition FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 1 GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2 ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName @@ -6350,14 +6350,14 @@ BEGIN SET tmpFileGroups.Selected = SelectedFileGroups.Selected FROM @tmpFileGroups tmpFileGroups INNER JOIN @SelectedFileGroups SelectedFileGroups - ON @CurrentDatabaseName LIKE REPLACE(SelectedFileGroups.DatabaseName,'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(SelectedFileGroups.FileGroupName,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedFileGroups.DatabaseName,'[','[[]'),'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(REPLACE(SelectedFileGroups.FileGroupName,'[','[[]'),'_','[_]') WHERE SelectedFileGroups.Selected = 1 UPDATE tmpFileGroups SET tmpFileGroups.Selected = SelectedFileGroups.Selected FROM @tmpFileGroups tmpFileGroups INNER JOIN @SelectedFileGroups SelectedFileGroups - ON @CurrentDatabaseName LIKE REPLACE(SelectedFileGroups.DatabaseName,'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(SelectedFileGroups.FileGroupName,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedFileGroups.DatabaseName,'[','[[]'),'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(REPLACE(SelectedFileGroups.FileGroupName,'[','[[]'),'_','[_]') WHERE SelectedFileGroups.Selected = 0 UPDATE tmpFileGroups @@ -6366,7 +6366,7 @@ BEGIN 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,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedFileGroups.DatabaseName,'[','[[]'),'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(REPLACE(SelectedFileGroups.FileGroupName,'[','[[]'),'_','[_]') WHERE SelectedFileGroups.Selected = 1 GROUP BY tmpFileGroups.FileGroupName) SelectedFileGroups2 ON tmpFileGroups.FileGroupName = SelectedFileGroups2.FileGroupName @@ -6516,14 +6516,14 @@ BEGIN SET tmpObjects.Selected = SelectedObjects.Selected 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,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedObjects.DatabaseName,'[','[[]'),'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(REPLACE(SelectedObjects.SchemaName,'[','[[]'),'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(REPLACE(SelectedObjects.ObjectName,'[','[[]'),'_','[_]') WHERE SelectedObjects.Selected = 1 UPDATE tmpObjects SET tmpObjects.Selected = SelectedObjects.Selected 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,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedObjects.DatabaseName,'[','[[]'),'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(REPLACE(SelectedObjects.SchemaName,'[','[[]'),'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(REPLACE(SelectedObjects.ObjectName,'[','[[]'),'_','[_]') WHERE SelectedObjects.Selected = 0 UPDATE tmpObjects @@ -6532,7 +6532,7 @@ BEGIN 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,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedObjects.DatabaseName,'[','[[]'),'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(REPLACE(SelectedObjects.SchemaName,'[','[[]'),'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(REPLACE(SelectedObjects.ObjectName,'[','[[]'),'_','[_]') WHERE SelectedObjects.Selected = 1 GROUP BY tmpObjects.SchemaName, tmpObjects.ObjectName) SelectedObjects2 ON tmpObjects.SchemaName = SelectedObjects2.SchemaName AND tmpObjects.ObjectName = SelectedObjects2.ObjectName @@ -6804,7 +6804,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-21 12:55:55 //-- + --// Version: 2026-06-25 10:21:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7269,7 +7269,7 @@ BEGIN SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(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 @@ -7278,7 +7278,7 @@ BEGIN SET tmpDatabases.Selected = SelectedDatabases.Selected FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(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 = 0 @@ -7289,7 +7289,7 @@ BEGIN INNER JOIN (SELECT tmpDatabases.DatabaseName, MIN(SelectedDatabases.StartPosition) AS StartPosition FROM @tmpDatabases tmpDatabases INNER JOIN @SelectedDatabases SelectedDatabases - ON tmpDatabases.DatabaseName LIKE REPLACE(SelectedDatabases.DatabaseName,'_','[_]') + ON tmpDatabases.DatabaseName LIKE REPLACE(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 @@ -7360,14 +7360,14 @@ BEGIN SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 1 UPDATE tmpAvailabilityGroups SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 0 UPDATE tmpAvailabilityGroups @@ -7376,7 +7376,7 @@ BEGIN INNER JOIN (SELECT tmpAvailabilityGroups.AvailabilityGroupName, MIN(SelectedAvailabilityGroups.StartPosition) AS StartPosition FROM @tmpAvailabilityGroups tmpAvailabilityGroups INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups - ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'_','[_]') + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') WHERE SelectedAvailabilityGroups.Selected = 1 GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2 ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName @@ -8553,14 +8553,14 @@ BEGIN SET tmpIndexesStatistics.Selected = SelectedIndexes.Selected 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,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(REPLACE(SelectedIndexes.IndexName,'[','[[]'),'_','[_]') WHERE SelectedIndexes.Selected = 1 UPDATE tmpIndexesStatistics SET tmpIndexesStatistics.Selected = SelectedIndexes.Selected 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,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(REPLACE(SelectedIndexes.IndexName,'[','[[]'),'_','[_]') WHERE SelectedIndexes.Selected = 0 UPDATE tmpIndexesStatistics @@ -8569,7 +8569,7 @@ BEGIN 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,'_','[_]') + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(REPLACE(SelectedIndexes.IndexName,'[','[[]'),'_','[_]') WHERE SelectedIndexes.Selected = 1 GROUP BY tmpIndexesStatistics.SchemaName, tmpIndexesStatistics.ObjectName, tmpIndexesStatistics.IndexName, tmpIndexesStatistics.StatisticsName) SelectedIndexes2 ON tmpIndexesStatistics.SchemaName = SelectedIndexes2.SchemaName From 547996a9bb912f0ad6bca551acf227cbaa5c55eb Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 28 Jun 2026 11:09:43 +0200 Subject: [PATCH 055/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 24 +- DatabaseIntegrityCheck.sql | 48 ++- IndexOptimize.sql | 667 ++++++++++++++++++++------------- MaintenanceSolution.sql | 743 ++++++++++++++++++++++--------------- 5 files changed, 867 insertions(+), 617 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 6598b849..59fc7445 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-25 10:21:34 //-- + --// Version: 2026-06-28 10:45:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 481689d2..95d29a15 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-25 10:21:34 //-- + --// Version: 2026-06-28 10:45:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -216,15 +216,15 @@ BEGIN StartPosition int, DatabaseSize bigint, LogSizeSinceLastLogBackup float, - [Order] int, - Selected bit, - Completed bit, - PRIMARY KEY(Selected, Completed, [Order], ID)) + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, AvailabilityGroupName nvarchar(max), StartPosition int, - Selected bit) + Selected bit DEFAULT 0) DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), AvailabilityGroupName nvarchar(max)) @@ -546,9 +546,8 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT name AS AvailabilityGroupName, - 0 AS Selected + INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName) + SELECT name AS AvailabilityGroupName FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) @@ -559,14 +558,11 @@ BEGIN 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) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup) SELECT [name] AS DatabaseName, RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')) AS DatabaseNameFS, 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, - 0 AS Completed + NULL AS AvailabilityGroup FROM sys.databases WHERE [name] <> 'tempdb' AND source_database_id IS NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index fe966c2f..f8f9f0e0 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-25 10:21:34 //-- + --// Version: 2026-06-28 10:45:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -122,15 +122,15 @@ BEGIN LastCommandTime datetime2, DatabaseSize bigint, LastGoodCheckDbTime datetime2, - [Order] int, - Selected bit, - Completed bit, - PRIMARY KEY(Selected, Completed, [Order], ID)) + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, AvailabilityGroupName nvarchar(max), StartPosition int, - Selected bit) + Selected bit DEFAULT 0) DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), AvailabilityGroupName nvarchar(max)) @@ -139,10 +139,10 @@ BEGIN FileGroupID int, FileGroupName nvarchar(max), StartPosition int, - [Order] int, - Selected bit, - Completed bit, - PRIMARY KEY(Selected, Completed, [Order], ID)) + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @tmpObjects TABLE (ID int IDENTITY, SchemaID int, @@ -151,10 +151,10 @@ BEGIN ObjectName nvarchar(max), ObjectType nvarchar(max), StartPosition int, - [Order] int, - Selected bit, - Completed bit, - PRIMARY KEY(Selected, Completed, [Order], ID)) + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), DatabaseType nvarchar(max), @@ -392,9 +392,8 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT name AS AvailabilityGroupName, - 0 AS Selected + INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName) + SELECT name AS AvailabilityGroupName FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) @@ -405,14 +404,11 @@ BEGIN 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) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot]) SELECT [name] AS DatabaseName, 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], - 0 AS Selected, - 0 AS Completed + CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot] FROM sys.databases ORDER BY [name] ASC @@ -1519,9 +1515,9 @@ BEGIN 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' + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName 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) + INSERT INTO @tmpFileGroups (FileGroupID, FileGroupName) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -1685,9 +1681,9 @@ BEGIN 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) AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL) 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 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) AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL) ORDER BY schemas.name ASC, objects.name ASC' - INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, [Order], Selected, Completed) + INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 3bd1e41a..01876636 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-25 10:21:34 //-- + --// Version: 2026-06-28 10:45:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -80,8 +80,6 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 - DECLARE @PartitionLevelStatistics bit - DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -96,6 +94,7 @@ BEGIN DECLARE @CurrentDatabaseState nvarchar(max) DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) + DECLARE @CurrentDatabaseHasReadOnlyFileGroup bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier @@ -176,28 +175,28 @@ BEGIN AvailabilityGroup bit, StartPosition int, DatabaseSize bigint, - [Order] int, - Selected bit, - Completed bit, - PRIMARY KEY(Selected, Completed, [Order], ID)) + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, AvailabilityGroupName nvarchar(max), StartPosition int, - Selected bit) + Selected bit DEFAULT 0) DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), AvailabilityGroupName nvarchar(max)) DECLARE @tmpIndexesStatistics TABLE (ID int IDENTITY, SchemaID int, - SchemaName nvarchar(max), + SchemaName nvarchar(128), ObjectID int, - ObjectName nvarchar(max), - ObjectType nvarchar(max), + ObjectName nvarchar(128), + ObjectType nvarchar(2), IsMemoryOptimized bit, IndexID int, - IndexName nvarchar(max), + IndexName nvarchar(128), IndexType int, AllowPageLocks bit, HasFilter bit, @@ -213,17 +212,37 @@ BEGIN OnReadOnlyFileGroup bit, ResumableIndexOperation bit, StatisticsID int, - StatisticsName nvarchar(max), + StatisticsName nvarchar(128), [NoRecompute] bit, IsIncremental bit, PartitionID bigint, PartitionNumber int, PartitionCount int, StartPosition int, - [Order] int, - Selected bit, - Completed bit, - PRIMARY KEY(Selected, Completed, [Order], ID)) + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) + + DECLARE @tmpObjectProperties TABLE (ObjectID int NOT NULL, + HasClusteredColumnstore bit, + HasNonClusteredColumnstore bit, + IsClusteredIndexComputed bit, + PRIMARY KEY (ObjectID)) + + DECLARE @tmpIndexProperties TABLE (ObjectID int NOT NULL, + IndexID int NOT NULL, + IsImageText bit, + IsNewLOB bit, + IsFileStream bit, + IsColumnstoreOrdered bit, + IsComputed bit, + IsTimestamp bit, + PRIMARY KEY (ObjectID, IndexID)) + + DECLARE @tmpResumableOperations TABLE (ObjectID int NOT NULL, + IndexID int NOT NULL, + PartitionNumber int) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), DatabaseType nvarchar(max), @@ -488,9 +507,8 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT name AS AvailabilityGroupName, - 0 AS Selected + INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName) + SELECT name AS AvailabilityGroupName FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) @@ -501,13 +519,10 @@ BEGIN 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) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup) SELECT [name] AS DatabaseName, 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, - 0 AS Completed + NULL AS AvailabilityGroup FROM sys.databases WHERE [name] <> 'tempdb' AND source_database_id IS NULL @@ -1246,12 +1261,6 @@ BEGIN GOTO Logging END - ---------------------------------------------------------------------------------------------------- - --// Should statistics be updated on the partition level? //-- - ---------------------------------------------------------------------------------------------------- - - SET @PartitionLevelStatistics = CASE WHEN @PartitionLevel = 'Y' THEN 1 ELSE 0 END - ---------------------------------------------------------------------------------------------------- --// Update database order //-- ---------------------------------------------------------------------------------------------------- @@ -1609,265 +1618,385 @@ BEGIN AND (@CurrentExecuteAsUserExists = 1 OR @CurrentExecuteAsUserExists IS NULL) 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 @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, 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 @CurrentCommand = @CurrentCommand + 'SELECT schemas.[schema_id] AS SchemaID' - + ', schemas.[name] AS SchemaName' - + ', objects.[object_id] AS ObjectID' - + ', objects.[name] AS ObjectName' - + ', RTRIM(objects.[type]) AS ObjectType' - + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' - + ', indexes.index_id AS IndexID' - + ', indexes.[name] AS IndexName' - + ', indexes.[type] AS IndexType' - + ', indexes.allow_page_locks AS AllowPageLocks' - + ', indexes.has_filter AS HasFilter' - - + ', 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] = 5) THEN 1 ELSE 0 END AS HasClusteredColumnstore' - - + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 6) THEN 1 ELSE 0 END AS HasNonClusteredColumnstore' - - + ', ' + CASE WHEN (@Version >= 16 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' - - + ', 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 OR index_columns.is_included_column = 1) 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.indexes indexes2 ON index_columns.object_id = indexes2.object_id AND index_columns.index_id = indexes2.index_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND indexes2.[type] = 1 AND index_columns.object_id = indexes.object_id) THEN 1 ELSE 0 END AS IsClusteredIndexComputed' - - + ', 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.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND 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 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' + CASE WHEN @PartitionLevel = 'Y' THEN ' AND (index_resumable_operations.partition_number = partitions.partition_number OR index_resumable_operations.partition_number IS NULL)' ELSE '' END + ') THEN 1 ELSE 0 END AS ResumableIndexOperation' - - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental 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 - + ', 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]' + -- Check if there are read-only filegroups in the database + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT @ParamDatabaseHasReadOnlyFileGroup = CASE WHEN EXISTS(SELECT * FROM sys.filegroups filegroups WHERE filegroups.is_read_only = 1) THEN 1 ELSE 0 END' + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseHasReadOnlyFileGroup bit OUTPUT', @ParamDatabaseHasReadOnlyFileGroup = @CurrentDatabaseHasReadOnlyFileGroup OUTPUT + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select indexes on tables + 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' + + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' + + ', indexes.index_id AS IndexID' + + ', indexes.[name] AS IndexName' + + ', indexes.[type] AS IndexType' + + ', indexes.allow_page_locks AS AllowPageLocks' + + ', indexes.has_filter AS HasFilter' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', 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' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ', 0 AS ResumableIndexOperation' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental 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 + + ' 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.tables tables ON objects.[object_id] = tables.[object_id]' + + ' INNER JOIN sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' IF @PartitionLevel = 'Y' BEGIN - 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]' + SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' + END + SET @CurrentCommand += ' WHERE objects.[type] = ''U''' + + ' AND tables.is_external = 0' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + ' AND indexes.[type] IN(1,2,5,6,7)' + + ' AND indexes.is_disabled = 0' + + ' AND indexes.is_hypothetical = 0' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error END - SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] IN(''U'',''V'')' - + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' - + 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 + -- Select special indexes (XML and spatial) + 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' + + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' + + ', indexes.index_id AS IndexID' + + ', indexes.[name] AS IndexName' + + ', indexes.[type] AS IndexType' + + ', indexes.allow_page_locks AS AllowPageLocks' + + ', indexes.has_filter AS HasFilter' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', 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) 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 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ', 0 AS ResumableIndexOperation' + + ' 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.tables tables ON objects.[object_id] = tables.[object_id]' + + ' WHERE objects.[type] = ''U''' + + ' AND tables.is_external = 0' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + ' AND indexes.[type] IN(3,4)' + + ' AND indexes.is_disabled = 0' + + ' AND indexes.is_hypothetical = 0' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END - IF (EXISTS(SELECT * FROM @ActionsPreferred) AND @UpdateStatistics = 'COLUMNS') OR @UpdateStatistics = 'ALL' - BEGIN - SET @CurrentCommand = @CurrentCommand + ' UNION ' + -- Select indexes on views + 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 IsMemoryOptimized' + + ', indexes.index_id AS IndexID' + + ', indexes.[name] AS IndexName' + + ', indexes.[type] AS IndexType' + + ', indexes.allow_page_locks AS AllowPageLocks' + + ', indexes.has_filter AS HasFilter' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', 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' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ', 0 AS ResumableIndexOperation' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental 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 + + ' 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.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' + IF @PartitionLevel = 'Y' + BEGIN + SET @CurrentCommand += ' LEFT OUTER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' + END + SET @CurrentCommand += ' WHERE objects.[type] = ''V''' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + ' AND indexes.[type] IN(1,2)' + + ' AND indexes.is_disabled = 0' + + ' AND indexes.is_hypothetical = 0' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select object properties + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT objects.[object_id] AS ObjectID' + + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 5) THEN 1 ELSE 0 END AS HasClusteredColumnstore' + + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 6) THEN 1 ELSE 0 END AS HasNonClusteredColumnstore' + + ', 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.indexes indexes2 ON index_columns.object_id = indexes2.object_id AND index_columns.index_id = indexes2.index_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND indexes2.[type] = 1 AND index_columns.object_id = objects.object_id) THEN 1 ELSE 0 END AS IsClusteredIndexComputed' + + ' FROM sys.objects objects' + + ' LEFT OUTER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + + ' WHERE objects.[type] IN(''U'',''V'')' + + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + INSERT INTO @tmpObjectProperties (ObjectID, HasClusteredColumnstore, HasNonClusteredColumnstore, IsClusteredIndexComputed) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select index properties + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT indexes.[object_id] AS ObjectID' + + ', indexes.index_id AS IndexID' + + ', 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] = indexes.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] = indexes.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] = indexes.[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] = indexes.object_id AND columns.is_filestream = 1) THEN 1 ELSE 0 END AS IsFileStream' + + ', ' + CASE WHEN (@Version >= 16 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' + + ', 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 OR index_columns.is_included_column = 1) 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.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND types.[name] = ''timestamp'') THEN 1 ELSE 0 END AS IsTimestamp' + + ' FROM sys.indexes indexes' + + ' INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id]' + + ' LEFT OUTER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + + ' WHERE objects.[type] IN(''U'',''V'')' + + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' + + 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' + + INSERT INTO @tmpIndexProperties (ObjectID, IndexID, IsImageText, IsNewLOB, IsFileStream, IsColumnstoreOrdered, IsComputed, IsTimestamp) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select paused resumable index operations + SET @CurrentCommand = 'SELECT index_resumable_operations.object_id AS ObjectID' + + ', index_resumable_operations.index_id AS IndexID' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'index_resumable_operations.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END + + ' FROM sys.index_resumable_operations index_resumable_operations' + + ' WHERE index_resumable_operations.state_desc = ''PAUSED''' + + INSERT INTO @tmpResumableOperations (ObjectID, IndexID, PartitionNumber) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END END IF @UpdateStatistics IN('ALL','COLUMNS') BEGIN - SET @CurrentCommand = @CurrentCommand + 'SELECT schemas.[schema_id] AS SchemaID' - + ', schemas.[name] AS SchemaName' - + ', objects.[object_id] AS ObjectID' - + ', objects.[name] AS ObjectName' - + ', RTRIM(objects.[type]) AS ObjectType' - + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' - + ', NULL AS IndexID, NULL AS IndexName' - + ', NULL AS IndexType' - + ', NULL AS AllowPageLocks' - + ', NULL AS HasFilter' - + ', NULL AS IsImageText' - + ', NULL AS IsNewLOB' - + ', NULL AS IsFileStream' - + ', NULL AS HasClusteredColumnstore' - + ', NULL AS HasNonClusteredColumnstore' - + ', NULL AS IsColumnstoreOrdered' - + ', NULL AS IsComputed' - + ', NULL AS IsClusteredIndexComputed' - + ', NULL AS IsTimestamp' - + ', NULL AS OnReadOnlyFileGroup' - + ', NULL AS ResumableIndexOperation' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental AS IsIncremental' - + ', NULL AS PartitionID' - + ', ' + 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' - + ', 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]' - - IF @PartitionLevelStatistics = 1 + -- Select column level statistics + 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' + + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental AS IsIncremental' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'dm_db_incremental_stats_properties.partition_number' ELSE 'NULL' END + ' AS PartitionNumber' + + ' 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]' + IF @PartitionLevel = 'Y' BEGIN - SET @CurrentCommand = @CurrentCommand + ' OUTER APPLY sys.dm_db_incremental_stats_properties(stats.object_id, stats.stats_id) dm_db_incremental_stats_properties' + SET @CurrentCommand += ' OUTER APPLY sys.dm_db_incremental_stats_properties(stats.object_id, stats.stats_id) dm_db_incremental_stats_properties' + END + SET @CurrentCommand += ' WHERE objects.[type] IN(''U'',''V'')' + + ' AND (tables.is_memory_optimized = 0 OR tables.is_memory_optimized IS NULL)' + + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' + + 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)' + + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes2 WHERE indexes2.[object_id] = stats.[object_id] AND indexes2.type = 1 AND indexes2.is_disabled = 1)' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error END - SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] IN(''U'',''V'')' - + ' AND (tables.is_memory_optimized = 0 OR tables.is_memory_optimized IS NULL)' - + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' - + 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)' - + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes2 WHERE indexes2.[object_id] = stats.[object_id] AND indexes2.type = 1 AND indexes2.is_disabled = 1)' - - SET @CurrentCommand = @CurrentCommand + ' UNION ' - - SET @CurrentCommand = @CurrentCommand + 'SELECT schemas.[schema_id] AS SchemaID' - + ', schemas.[name] AS SchemaName' - + ', objects.[object_id] AS ObjectID' - + ', objects.[name] AS ObjectName' - + ', RTRIM(objects.[type]) AS ObjectType' - + ', tables.is_memory_optimized AS IsMemoryOptimized' - + ', NULL AS IndexID, NULL AS IndexName' - + ', NULL AS IndexType' - + ', NULL AS AllowPageLocks' - + ', NULL AS HasFilter' - + ', NULL AS IsImageText' - + ', NULL AS IsNewLOB' - + ', NULL AS IsFileStream' - + ', NULL AS HasClusteredColumnstore' - + ', NULL AS HasNonClusteredColumnstore' - + ', NULL AS IsColumnstoreOrdered' - + ', NULL AS IsComputed' - + ', NULL AS IsClusteredIndexComputed' - + ', NULL AS IsTimestamp' - + ', NULL AS OnReadOnlyFileGroup' - + ', NULL AS ResumableIndexOperation' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental AS IsIncremental' - + ', NULL AS PartitionID' - + ', NULL AS PartitionNumber' - + ', 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]' - + ' INNER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' - - SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] = ''U''' - + ' AND tables.is_memory_optimized = 1' - + 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)' + -- Select column-level statistics for memory optimized tables + 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' + + ', tables.is_memory_optimized AS IsMemoryOptimized' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental AS IsIncremental' + + ' 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]' + + ' INNER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + + ' WHERE objects.[type] = ''U''' + + ' AND tables.is_memory_optimized = 1' + + 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)' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END END - SET @CurrentCommand = @CurrentCommand + ') IndexesStatistics' + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.IsImageText = tmpIndexProperties.IsImageText, + tmpIndexesStatistics.IsNewLOB = tmpIndexProperties.IsNewLOB, + tmpIndexesStatistics.IsFileStream = tmpIndexProperties.IsFileStream, + tmpIndexesStatistics.HasClusteredColumnstore = tmpObjectProperties.HasClusteredColumnstore, + tmpIndexesStatistics.HasNonClusteredColumnstore = tmpObjectProperties.HasNonClusteredColumnstore, + tmpIndexesStatistics.IsClusteredIndexComputed = tmpObjectProperties.IsClusteredIndexComputed, + tmpIndexesStatistics.IsColumnstoreOrdered = tmpIndexProperties.IsColumnstoreOrdered, + tmpIndexesStatistics.IsComputed = tmpIndexProperties.IsComputed, + tmpIndexesStatistics.IsTimestamp = tmpIndexProperties.IsTimestamp + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @tmpObjectProperties tmpObjectProperties ON tmpIndexesStatistics.ObjectID = tmpObjectProperties.ObjectID + INNER JOIN @tmpIndexProperties tmpIndexProperties ON tmpIndexesStatistics.ObjectID = tmpIndexProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexProperties.IndexID + OPTION (RECOMPILE) - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand - SET @Error = @@ERROR - IF @Error <> 0 + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.ResumableIndexOperation = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @tmpResumableOperations tmpResumableOperations ON tmpIndexesStatistics.ObjectID = tmpResumableOperations.ObjectID AND tmpIndexesStatistics.IndexID = tmpResumableOperations.IndexID AND (tmpIndexesStatistics.PartitionNumber = tmpResumableOperations.PartitionNumber OR tmpResumableOperations.PartitionNumber IS NULL) + OPTION (RECOMPILE) + + IF @PartitionLevel = 'Y' BEGIN - SET @ReturnCode = @Error + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.PartitionCount = PartitionCounts.PartitionCount + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN (SELECT ObjectID, IndexID, COUNT(*) AS PartitionCount FROM @tmpIndexesStatistics WHERE IndexID IS NOT NULL GROUP BY ObjectID, IndexID) PartitionCounts ON tmpIndexesStatistics.ObjectID = PartitionCounts.ObjectID AND tmpIndexesStatistics.IndexID = PartitionCounts.IndexID + OPTION (RECOMPILE) END - END - IF @Indexes IS NULL - BEGIN - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.Selected = 1 + IF @Indexes IS NULL + BEGIN + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.Selected = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + END + ELSE + BEGIN + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.Selected = SelectedIndexes.Selected + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @SelectedIndexes SelectedIndexes + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(REPLACE(SelectedIndexes.IndexName,'[','[[]'),'_','[_]') + WHERE SelectedIndexes.Selected = 1 + + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.Selected = SelectedIndexes.Selected + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @SelectedIndexes SelectedIndexes + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(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(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(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) + END; + + WITH tmpIndexesStatistics AS ( + 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 - END - ELSE - BEGIN + WHERE Selected = 1 + ) UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.Selected = SelectedIndexes.Selected - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @SelectedIndexes SelectedIndexes - ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(REPLACE(SelectedIndexes.IndexName,'[','[[]'),'_','[_]') - WHERE SelectedIndexes.Selected = 1 + SET [Order] = RowNumber - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.Selected = SelectedIndexes.Selected - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @SelectedIndexes SelectedIndexes - ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(REPLACE(SelectedIndexes.IndexName,'[','[[]'),'_','[_]') - WHERE SelectedIndexes.Selected = 0 + SELECT @ErrorMessage = STRING_AGG(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) - 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(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(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) - END; - - WITH tmpIndexesStatistics AS ( - 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 - ) - UPDATE tmpIndexesStatistics - SET [Order] = RowNumber - - SELECT @ErrorMessage = STRING_AGG(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 @ErrorMessage IS NOT NULL - BEGIN - SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + @ErrorMessage + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - END + IF @ErrorMessage IS NOT NULL + BEGIN + SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + @ErrorMessage + '.' + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END - SELECT @ErrorMessage = STRING_AGG(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) + SELECT @ErrorMessage = STRING_AGG(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 @ErrorMessage IS NOT NULL - BEGIN - SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + @ErrorMessage + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + IF @ErrorMessage IS NOT NULL + BEGIN + SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + @ErrorMessage + '.' + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END END WHILE (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) @@ -1989,7 +2118,7 @@ BEGIN SET @CurrentCommand = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 BEGIN SET @CurrentCommand += 'SELECT @ParamObjectRowCount = row_count FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id = (SELECT MIN(index_id) FROM sys.indexes WHERE [object_id] = @ParamObjectID) AND partition_number = @ParamPartitionNumber' END @@ -2021,7 +2150,7 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 BEGIN SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' END @@ -2164,7 +2293,7 @@ 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 ((@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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL AND @CurrentObjectRowCount > 0)) - 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)))) + AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) BEGIN SET @CurrentUpdateStatistics = 'Y' END @@ -2178,7 +2307,7 @@ BEGIN SET @CurrentStatisticsResample = @StatisticsResample -- Incremental statistics only supports RESAMPLE - IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 BEGIN SET @CurrentStatisticsSample = NULL SET @CurrentStatisticsPersistSample = NULL @@ -2402,7 +2531,7 @@ BEGIN FROM @CurrentUpdateStatisticsWithClauseArguments END - IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 @@ -2521,6 +2650,7 @@ BEGIN SET @CurrentDatabaseState = NULL SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL + SET @CurrentDatabaseHasReadOnlyFileGroup = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL @@ -2535,6 +2665,9 @@ BEGIN SET @CurrentCommand = NULL DELETE FROM @tmpIndexesStatistics + DELETE FROM @tmpObjectProperties + DELETE FROM @tmpIndexProperties + DELETE FROM @tmpResumableOperations END diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index d6287d8f..b110023c 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: 2026-06-25 10:21:34 +Version: 2026-06-28 10:45:05 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-25 10:21:34 //-- + --// Version: 2026-06-28 10:45:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-25 10:21:34 //-- + --// Version: 2026-06-28 10:45:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -615,15 +615,15 @@ BEGIN StartPosition int, DatabaseSize bigint, LogSizeSinceLastLogBackup float, - [Order] int, - Selected bit, - Completed bit, - PRIMARY KEY(Selected, Completed, [Order], ID)) + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, AvailabilityGroupName nvarchar(max), StartPosition int, - Selected bit) + Selected bit DEFAULT 0) DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), AvailabilityGroupName nvarchar(max)) @@ -945,9 +945,8 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT name AS AvailabilityGroupName, - 0 AS Selected + INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName) + SELECT name AS AvailabilityGroupName FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) @@ -958,14 +957,11 @@ BEGIN 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) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseNameFS, DatabaseType, AvailabilityGroup) SELECT [name] AS DatabaseName, RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE([name],'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|','')) AS DatabaseNameFS, 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, - 0 AS Completed + NULL AS AvailabilityGroup FROM sys.databases WHERE [name] <> 'tempdb' AND source_database_id IS NULL @@ -4852,7 +4848,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-25 10:21:34 //-- + --// Version: 2026-06-28 10:45:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4934,15 +4930,15 @@ BEGIN LastCommandTime datetime2, DatabaseSize bigint, LastGoodCheckDbTime datetime2, - [Order] int, - Selected bit, - Completed bit, - PRIMARY KEY(Selected, Completed, [Order], ID)) + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, AvailabilityGroupName nvarchar(max), StartPosition int, - Selected bit) + Selected bit DEFAULT 0) DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), AvailabilityGroupName nvarchar(max)) @@ -4951,10 +4947,10 @@ BEGIN FileGroupID int, FileGroupName nvarchar(max), StartPosition int, - [Order] int, - Selected bit, - Completed bit, - PRIMARY KEY(Selected, Completed, [Order], ID)) + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @tmpObjects TABLE (ID int IDENTITY, SchemaID int, @@ -4963,10 +4959,10 @@ BEGIN ObjectName nvarchar(max), ObjectType nvarchar(max), StartPosition int, - [Order] int, - Selected bit, - Completed bit, - PRIMARY KEY(Selected, Completed, [Order], ID)) + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), DatabaseType nvarchar(max), @@ -5204,9 +5200,8 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT name AS AvailabilityGroupName, - 0 AS Selected + INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName) + SELECT name AS AvailabilityGroupName FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) @@ -5217,14 +5212,11 @@ BEGIN 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) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup, [Snapshot]) SELECT [name] AS DatabaseName, 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], - 0 AS Selected, - 0 AS Completed + CASE WHEN source_database_id IS NOT NULL THEN 1 ELSE 0 END AS [Snapshot] FROM sys.databases ORDER BY [name] ASC @@ -6331,9 +6323,9 @@ BEGIN 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' + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; SELECT data_space_id AS FileGroupID, name AS FileGroupName 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) + INSERT INTO @tmpFileGroups (FileGroupID, FileGroupName) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -6497,9 +6489,9 @@ BEGIN 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) AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL) 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 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) AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL) ORDER BY schemas.name ASC, objects.name ASC' - INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, [Order], Selected, Completed) + INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 SET @ReturnCode = @Error @@ -6804,7 +6796,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-25 10:21:34 //-- + --// Version: 2026-06-28 10:45:05 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6828,8 +6820,6 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 - DECLARE @PartitionLevelStatistics bit - DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -6844,6 +6834,7 @@ BEGIN DECLARE @CurrentDatabaseState nvarchar(max) DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) + DECLARE @CurrentDatabaseHasReadOnlyFileGroup bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier @@ -6924,28 +6915,28 @@ BEGIN AvailabilityGroup bit, StartPosition int, DatabaseSize bigint, - [Order] int, - Selected bit, - Completed bit, - PRIMARY KEY(Selected, Completed, [Order], ID)) + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, AvailabilityGroupName nvarchar(max), StartPosition int, - Selected bit) + Selected bit DEFAULT 0) DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), AvailabilityGroupName nvarchar(max)) DECLARE @tmpIndexesStatistics TABLE (ID int IDENTITY, SchemaID int, - SchemaName nvarchar(max), + SchemaName nvarchar(128), ObjectID int, - ObjectName nvarchar(max), - ObjectType nvarchar(max), + ObjectName nvarchar(128), + ObjectType nvarchar(2), IsMemoryOptimized bit, IndexID int, - IndexName nvarchar(max), + IndexName nvarchar(128), IndexType int, AllowPageLocks bit, HasFilter bit, @@ -6961,17 +6952,37 @@ BEGIN OnReadOnlyFileGroup bit, ResumableIndexOperation bit, StatisticsID int, - StatisticsName nvarchar(max), + StatisticsName nvarchar(128), [NoRecompute] bit, IsIncremental bit, PartitionID bigint, PartitionNumber int, PartitionCount int, StartPosition int, - [Order] int, - Selected bit, - Completed bit, - PRIMARY KEY(Selected, Completed, [Order], ID)) + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) + + DECLARE @tmpObjectProperties TABLE (ObjectID int NOT NULL, + HasClusteredColumnstore bit, + HasNonClusteredColumnstore bit, + IsClusteredIndexComputed bit, + PRIMARY KEY (ObjectID)) + + DECLARE @tmpIndexProperties TABLE (ObjectID int NOT NULL, + IndexID int NOT NULL, + IsImageText bit, + IsNewLOB bit, + IsFileStream bit, + IsColumnstoreOrdered bit, + IsComputed bit, + IsTimestamp bit, + PRIMARY KEY (ObjectID, IndexID)) + + DECLARE @tmpResumableOperations TABLE (ObjectID int NOT NULL, + IndexID int NOT NULL, + PartitionNumber int) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), DatabaseType nvarchar(max), @@ -7236,9 +7247,8 @@ BEGIN IF SERVERPROPERTY('IsHadrEnabled') = 1 BEGIN - INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName, Selected) - SELECT name AS AvailabilityGroupName, - 0 AS Selected + INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName) + SELECT name AS AvailabilityGroupName FROM sys.availability_groups INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) @@ -7249,13 +7259,10 @@ BEGIN 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) + INSERT INTO @tmpDatabases (DatabaseName, DatabaseType, AvailabilityGroup) SELECT [name] AS DatabaseName, 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, - 0 AS Completed + NULL AS AvailabilityGroup FROM sys.databases WHERE [name] <> 'tempdb' AND source_database_id IS NULL @@ -7994,12 +8001,6 @@ BEGIN GOTO Logging END - ---------------------------------------------------------------------------------------------------- - --// Should statistics be updated on the partition level? //-- - ---------------------------------------------------------------------------------------------------- - - SET @PartitionLevelStatistics = CASE WHEN @PartitionLevel = 'Y' THEN 1 ELSE 0 END - ---------------------------------------------------------------------------------------------------- --// Update database order //-- ---------------------------------------------------------------------------------------------------- @@ -8357,265 +8358,385 @@ BEGIN AND (@CurrentExecuteAsUserExists = 1 OR @CurrentExecuteAsUserExists IS NULL) 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 @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, 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 @CurrentCommand = @CurrentCommand + 'SELECT schemas.[schema_id] AS SchemaID' - + ', schemas.[name] AS SchemaName' - + ', objects.[object_id] AS ObjectID' - + ', objects.[name] AS ObjectName' - + ', RTRIM(objects.[type]) AS ObjectType' - + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' - + ', indexes.index_id AS IndexID' - + ', indexes.[name] AS IndexName' - + ', indexes.[type] AS IndexType' - + ', indexes.allow_page_locks AS AllowPageLocks' - + ', indexes.has_filter AS HasFilter' - - + ', 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] = 5) THEN 1 ELSE 0 END AS HasClusteredColumnstore' - - + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 6) THEN 1 ELSE 0 END AS HasNonClusteredColumnstore' - - + ', ' + CASE WHEN (@Version >= 16 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' - - + ', 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 OR index_columns.is_included_column = 1) 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.indexes indexes2 ON index_columns.object_id = indexes2.object_id AND index_columns.index_id = indexes2.index_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND indexes2.[type] = 1 AND index_columns.object_id = indexes.object_id) THEN 1 ELSE 0 END AS IsClusteredIndexComputed' - - + ', 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.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND 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 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' + CASE WHEN @PartitionLevel = 'Y' THEN ' AND (index_resumable_operations.partition_number = partitions.partition_number OR index_resumable_operations.partition_number IS NULL)' ELSE '' END + ') THEN 1 ELSE 0 END AS ResumableIndexOperation' - - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental 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 - + ', 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]' + -- Check if there are read-only filegroups in the database + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT @ParamDatabaseHasReadOnlyFileGroup = CASE WHEN EXISTS(SELECT * FROM sys.filegroups filegroups WHERE filegroups.is_read_only = 1) THEN 1 ELSE 0 END' + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseHasReadOnlyFileGroup bit OUTPUT', @ParamDatabaseHasReadOnlyFileGroup = @CurrentDatabaseHasReadOnlyFileGroup OUTPUT + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select indexes on tables + 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' + + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' + + ', indexes.index_id AS IndexID' + + ', indexes.[name] AS IndexName' + + ', indexes.[type] AS IndexType' + + ', indexes.allow_page_locks AS AllowPageLocks' + + ', indexes.has_filter AS HasFilter' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', 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' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ', 0 AS ResumableIndexOperation' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental 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 + + ' 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.tables tables ON objects.[object_id] = tables.[object_id]' + + ' INNER JOIN sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' IF @PartitionLevel = 'Y' BEGIN - 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]' + SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' + END + SET @CurrentCommand += ' WHERE objects.[type] = ''U''' + + ' AND tables.is_external = 0' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + ' AND indexes.[type] IN(1,2,5,6,7)' + + ' AND indexes.is_disabled = 0' + + ' AND indexes.is_hypothetical = 0' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error END - SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] IN(''U'',''V'')' - + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' - + 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 + -- Select special indexes (XML and spatial) + 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' + + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' + + ', indexes.index_id AS IndexID' + + ', indexes.[name] AS IndexName' + + ', indexes.[type] AS IndexType' + + ', indexes.allow_page_locks AS AllowPageLocks' + + ', indexes.has_filter AS HasFilter' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', 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) 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 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ', 0 AS ResumableIndexOperation' + + ' 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.tables tables ON objects.[object_id] = tables.[object_id]' + + ' WHERE objects.[type] = ''U''' + + ' AND tables.is_external = 0' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + ' AND indexes.[type] IN(3,4)' + + ' AND indexes.is_disabled = 0' + + ' AND indexes.is_hypothetical = 0' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END - IF (EXISTS(SELECT * FROM @ActionsPreferred) AND @UpdateStatistics = 'COLUMNS') OR @UpdateStatistics = 'ALL' - BEGIN - SET @CurrentCommand = @CurrentCommand + ' UNION ' + -- Select indexes on views + 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 IsMemoryOptimized' + + ', indexes.index_id AS IndexID' + + ', indexes.[name] AS IndexName' + + ', indexes.[type] AS IndexType' + + ', indexes.allow_page_locks AS AllowPageLocks' + + ', indexes.has_filter AS HasFilter' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', 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' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ', 0 AS ResumableIndexOperation' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental 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 + + ' 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.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' + IF @PartitionLevel = 'Y' + BEGIN + SET @CurrentCommand += ' LEFT OUTER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' + END + SET @CurrentCommand += ' WHERE objects.[type] = ''V''' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + ' AND indexes.[type] IN(1,2)' + + ' AND indexes.is_disabled = 0' + + ' AND indexes.is_hypothetical = 0' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select object properties + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT objects.[object_id] AS ObjectID' + + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 5) THEN 1 ELSE 0 END AS HasClusteredColumnstore' + + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 6) THEN 1 ELSE 0 END AS HasNonClusteredColumnstore' + + ', 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.indexes indexes2 ON index_columns.object_id = indexes2.object_id AND index_columns.index_id = indexes2.index_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND indexes2.[type] = 1 AND index_columns.object_id = objects.object_id) THEN 1 ELSE 0 END AS IsClusteredIndexComputed' + + ' FROM sys.objects objects' + + ' LEFT OUTER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + + ' WHERE objects.[type] IN(''U'',''V'')' + + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + INSERT INTO @tmpObjectProperties (ObjectID, HasClusteredColumnstore, HasNonClusteredColumnstore, IsClusteredIndexComputed) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select index properties + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT indexes.[object_id] AS ObjectID' + + ', indexes.index_id AS IndexID' + + ', 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] = indexes.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] = indexes.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] = indexes.[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] = indexes.object_id AND columns.is_filestream = 1) THEN 1 ELSE 0 END AS IsFileStream' + + ', ' + CASE WHEN (@Version >= 16 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' + + ', 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 OR index_columns.is_included_column = 1) 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.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND types.[name] = ''timestamp'') THEN 1 ELSE 0 END AS IsTimestamp' + + ' FROM sys.indexes indexes' + + ' INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id]' + + ' LEFT OUTER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + + ' WHERE objects.[type] IN(''U'',''V'')' + + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' + + 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' + + INSERT INTO @tmpIndexProperties (ObjectID, IndexID, IsImageText, IsNewLOB, IsFileStream, IsColumnstoreOrdered, IsComputed, IsTimestamp) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select paused resumable index operations + SET @CurrentCommand = 'SELECT index_resumable_operations.object_id AS ObjectID' + + ', index_resumable_operations.index_id AS IndexID' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'index_resumable_operations.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END + + ' FROM sys.index_resumable_operations index_resumable_operations' + + ' WHERE index_resumable_operations.state_desc = ''PAUSED''' + + INSERT INTO @tmpResumableOperations (ObjectID, IndexID, PartitionNumber) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END END IF @UpdateStatistics IN('ALL','COLUMNS') BEGIN - SET @CurrentCommand = @CurrentCommand + 'SELECT schemas.[schema_id] AS SchemaID' - + ', schemas.[name] AS SchemaName' - + ', objects.[object_id] AS ObjectID' - + ', objects.[name] AS ObjectName' - + ', RTRIM(objects.[type]) AS ObjectType' - + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' - + ', NULL AS IndexID, NULL AS IndexName' - + ', NULL AS IndexType' - + ', NULL AS AllowPageLocks' - + ', NULL AS HasFilter' - + ', NULL AS IsImageText' - + ', NULL AS IsNewLOB' - + ', NULL AS IsFileStream' - + ', NULL AS HasClusteredColumnstore' - + ', NULL AS HasNonClusteredColumnstore' - + ', NULL AS IsColumnstoreOrdered' - + ', NULL AS IsComputed' - + ', NULL AS IsClusteredIndexComputed' - + ', NULL AS IsTimestamp' - + ', NULL AS OnReadOnlyFileGroup' - + ', NULL AS ResumableIndexOperation' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental AS IsIncremental' - + ', NULL AS PartitionID' - + ', ' + 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' - + ', 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]' - - IF @PartitionLevelStatistics = 1 + -- Select column level statistics + 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' + + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental AS IsIncremental' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'dm_db_incremental_stats_properties.partition_number' ELSE 'NULL' END + ' AS PartitionNumber' + + ' 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]' + IF @PartitionLevel = 'Y' + BEGIN + SET @CurrentCommand += ' OUTER APPLY sys.dm_db_incremental_stats_properties(stats.object_id, stats.stats_id) dm_db_incremental_stats_properties' + END + SET @CurrentCommand += ' WHERE objects.[type] IN(''U'',''V'')' + + ' AND (tables.is_memory_optimized = 0 OR tables.is_memory_optimized IS NULL)' + + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' + + 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)' + + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes2 WHERE indexes2.[object_id] = stats.[object_id] AND indexes2.type = 1 AND indexes2.is_disabled = 1)' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 BEGIN - SET @CurrentCommand = @CurrentCommand + ' OUTER APPLY sys.dm_db_incremental_stats_properties(stats.object_id, stats.stats_id) dm_db_incremental_stats_properties' + SET @ReturnCode = @Error END - SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] IN(''U'',''V'')' - + ' AND (tables.is_memory_optimized = 0 OR tables.is_memory_optimized IS NULL)' - + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' - + 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)' - + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes2 WHERE indexes2.[object_id] = stats.[object_id] AND indexes2.type = 1 AND indexes2.is_disabled = 1)' - - SET @CurrentCommand = @CurrentCommand + ' UNION ' - - SET @CurrentCommand = @CurrentCommand + 'SELECT schemas.[schema_id] AS SchemaID' - + ', schemas.[name] AS SchemaName' - + ', objects.[object_id] AS ObjectID' - + ', objects.[name] AS ObjectName' - + ', RTRIM(objects.[type]) AS ObjectType' - + ', tables.is_memory_optimized AS IsMemoryOptimized' - + ', NULL AS IndexID, NULL AS IndexName' - + ', NULL AS IndexType' - + ', NULL AS AllowPageLocks' - + ', NULL AS HasFilter' - + ', NULL AS IsImageText' - + ', NULL AS IsNewLOB' - + ', NULL AS IsFileStream' - + ', NULL AS HasClusteredColumnstore' - + ', NULL AS HasNonClusteredColumnstore' - + ', NULL AS IsColumnstoreOrdered' - + ', NULL AS IsComputed' - + ', NULL AS IsClusteredIndexComputed' - + ', NULL AS IsTimestamp' - + ', NULL AS OnReadOnlyFileGroup' - + ', NULL AS ResumableIndexOperation' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental AS IsIncremental' - + ', NULL AS PartitionID' - + ', NULL AS PartitionNumber' - + ', 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]' - + ' INNER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' - - SET @CurrentCommand = @CurrentCommand + ' WHERE objects.[type] = ''U''' - + ' AND tables.is_memory_optimized = 1' - + 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)' + -- Select column-level statistics for memory optimized tables + 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' + + ', tables.is_memory_optimized AS IsMemoryOptimized' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental AS IsIncremental' + + ' 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]' + + ' INNER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + + ' WHERE objects.[type] = ''U''' + + ' AND tables.is_memory_optimized = 1' + + 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)' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END END - SET @CurrentCommand = @CurrentCommand + ') IndexesStatistics' + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.IsImageText = tmpIndexProperties.IsImageText, + tmpIndexesStatistics.IsNewLOB = tmpIndexProperties.IsNewLOB, + tmpIndexesStatistics.IsFileStream = tmpIndexProperties.IsFileStream, + tmpIndexesStatistics.HasClusteredColumnstore = tmpObjectProperties.HasClusteredColumnstore, + tmpIndexesStatistics.HasNonClusteredColumnstore = tmpObjectProperties.HasNonClusteredColumnstore, + tmpIndexesStatistics.IsClusteredIndexComputed = tmpObjectProperties.IsClusteredIndexComputed, + tmpIndexesStatistics.IsColumnstoreOrdered = tmpIndexProperties.IsColumnstoreOrdered, + tmpIndexesStatistics.IsComputed = tmpIndexProperties.IsComputed, + tmpIndexesStatistics.IsTimestamp = tmpIndexProperties.IsTimestamp + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @tmpObjectProperties tmpObjectProperties ON tmpIndexesStatistics.ObjectID = tmpObjectProperties.ObjectID + INNER JOIN @tmpIndexProperties tmpIndexProperties ON tmpIndexesStatistics.ObjectID = tmpIndexProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexProperties.IndexID + OPTION (RECOMPILE) - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsNewLOB, IsFileStream, HasClusteredColumnstore, HasNonClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, PartitionCount, [Order], Selected, Completed) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand - SET @Error = @@ERROR - IF @Error <> 0 + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.ResumableIndexOperation = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @tmpResumableOperations tmpResumableOperations ON tmpIndexesStatistics.ObjectID = tmpResumableOperations.ObjectID AND tmpIndexesStatistics.IndexID = tmpResumableOperations.IndexID AND (tmpIndexesStatistics.PartitionNumber = tmpResumableOperations.PartitionNumber OR tmpResumableOperations.PartitionNumber IS NULL) + OPTION (RECOMPILE) + + IF @PartitionLevel = 'Y' BEGIN - SET @ReturnCode = @Error + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.PartitionCount = PartitionCounts.PartitionCount + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN (SELECT ObjectID, IndexID, COUNT(*) AS PartitionCount FROM @tmpIndexesStatistics WHERE IndexID IS NOT NULL GROUP BY ObjectID, IndexID) PartitionCounts ON tmpIndexesStatistics.ObjectID = PartitionCounts.ObjectID AND tmpIndexesStatistics.IndexID = PartitionCounts.IndexID + OPTION (RECOMPILE) END - END - IF @Indexes IS NULL - BEGIN - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.Selected = 1 + IF @Indexes IS NULL + BEGIN + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.Selected = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + END + ELSE + BEGIN + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.Selected = SelectedIndexes.Selected + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @SelectedIndexes SelectedIndexes + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(REPLACE(SelectedIndexes.IndexName,'[','[[]'),'_','[_]') + WHERE SelectedIndexes.Selected = 1 + + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.Selected = SelectedIndexes.Selected + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @SelectedIndexes SelectedIndexes + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(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(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(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) + END; + + WITH tmpIndexesStatistics AS ( + 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 - END - ELSE - BEGIN + WHERE Selected = 1 + ) UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.Selected = SelectedIndexes.Selected - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @SelectedIndexes SelectedIndexes - ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(REPLACE(SelectedIndexes.IndexName,'[','[[]'),'_','[_]') - WHERE SelectedIndexes.Selected = 1 + SET [Order] = RowNumber - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.Selected = SelectedIndexes.Selected - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @SelectedIndexes SelectedIndexes - ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(REPLACE(SelectedIndexes.IndexName,'[','[[]'),'_','[_]') - WHERE SelectedIndexes.Selected = 0 + SELECT @ErrorMessage = STRING_AGG(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) - 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(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(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) - END; - - WITH tmpIndexesStatistics AS ( - 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 - ) - UPDATE tmpIndexesStatistics - SET [Order] = RowNumber - - SELECT @ErrorMessage = STRING_AGG(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 @ErrorMessage IS NOT NULL - BEGIN - SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + @ErrorMessage + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT - END + IF @ErrorMessage IS NOT NULL + BEGIN + SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + @ErrorMessage + '.' + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END - SELECT @ErrorMessage = STRING_AGG(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) + SELECT @ErrorMessage = STRING_AGG(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 @ErrorMessage IS NOT NULL - BEGIN - SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + @ErrorMessage + '.' - RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR - RAISERROR(@EmptyLine,10,1) WITH NOWAIT + IF @ErrorMessage IS NOT NULL + BEGIN + SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + @ErrorMessage + '.' + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END END WHILE (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) @@ -8737,7 +8858,7 @@ BEGIN SET @CurrentCommand = '' IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 BEGIN SET @CurrentCommand += 'SELECT @ParamObjectRowCount = row_count FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id = (SELECT MIN(index_id) FROM sys.indexes WHERE [object_id] = @ParamObjectID) AND partition_number = @ParamPartitionNumber' END @@ -8769,7 +8890,7 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 BEGIN SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' END @@ -8912,7 +9033,7 @@ 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 ((@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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL AND @CurrentObjectRowCount > 0)) - 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)))) + AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) BEGIN SET @CurrentUpdateStatistics = 'Y' END @@ -8926,7 +9047,7 @@ BEGIN SET @CurrentStatisticsResample = @StatisticsResample -- Incremental statistics only supports RESAMPLE - IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 BEGIN SET @CurrentStatisticsSample = NULL SET @CurrentStatisticsPersistSample = NULL @@ -9150,7 +9271,7 @@ BEGIN FROM @CurrentUpdateStatisticsWithClauseArguments END - IF @PartitionLevelStatistics = 1 AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 @@ -9269,6 +9390,7 @@ BEGIN SET @CurrentDatabaseState = NULL SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL + SET @CurrentDatabaseHasReadOnlyFileGroup = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL @@ -9283,6 +9405,9 @@ BEGIN SET @CurrentCommand = NULL DELETE FROM @tmpIndexesStatistics + DELETE FROM @tmpObjectProperties + DELETE FROM @tmpIndexProperties + DELETE FROM @tmpResumableOperations END From a91ec4c9da9a9cb2001d8ec2086cadb6d9d15bbc Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 29 Jun 2026 22:31:16 +0200 Subject: [PATCH 056/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 278 +++++++++++++++++------------------ MaintenanceSolution.sql | 286 +++++++++++++++++++------------------ 5 files changed, 289 insertions(+), 281 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 59fc7445..9cdcd796 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-28 10:45:05 //-- + --// Version: 2026-06-29 20:49:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 95d29a15..ae145e58 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-28 10:45:05 //-- + --// Version: 2026-06-29 20:49:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index f8f9f0e0..fbb560b3 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-28 10:45:05 //-- + --// Version: 2026-06-29 20:49:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 01876636..87e69091 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-28 10:45:05 //-- + --// Version: 2026-06-29 20:49:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -153,7 +153,7 @@ BEGIN DECLARE @CurrentHasFilter bit DECLARE @CurrentNoRecompute bit DECLARE @CurrentIsIncremental bit - DECLARE @CurrentObjectRowCount bigint + DECLARE @CurrentObjectHasRows bit DECLARE @CurrentRowCount bigint DECLARE @CurrentModificationCounter bigint DECLARE @CurrentOnReadOnlyFileGroup bit @@ -1861,7 +1861,7 @@ BEGIN SET @ReturnCode = @Error END - -- Select column-level statistics for memory optimized tables + -- Select column level statistics for memory optimized tables SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + ' SELECT schemas.[schema_id] AS SchemaID' + ', schemas.[name] AS SchemaName' @@ -2079,104 +2079,6 @@ BEGIN END CATCH END - -- Does the statistics exist? - IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL - BEGIN - SET @CurrentCommand = '' - - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - - 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 = @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 - SET @CurrentStatisticsExists = 0 - GOTO NoAction - END - END TRY - BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 - SET @ReturnCode = ERROR_NUMBER() - END - - GOTO NoAction - END CATCH - END - - -- What is the object row count? - IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL - BEGIN - SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - - IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 - BEGIN - SET @CurrentCommand += 'SELECT @ParamObjectRowCount = row_count FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id = (SELECT MIN(index_id) FROM sys.indexes WHERE [object_id] = @ParamObjectID) AND partition_number = @ParamPartitionNumber' - END - ELSE - BEGIN - SET @CurrentCommand += 'SELECT @ParamObjectRowCount = SUM(row_count) FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id = (SELECT MIN(index_id) FROM sys.indexes WHERE [object_id] = @ParamObjectID)' - END - - BEGIN TRY - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamPartitionNumber int, @ParamObjectRowCount bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamObjectRowCount = @CurrentObjectRowCount OUTPUT - END TRY - BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The row count 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 - SET @ReturnCode = ERROR_NUMBER() - END - GOTO NoAction - END CATCH - 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 - BEGIN - SET @CurrentCommand = '' - - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - - IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 - BEGIN - SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' - END - ELSE - BEGIN - SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' - END - - BEGIN TRY - 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 - END TRY - BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 - SET @ReturnCode = ERROR_NUMBER() - END - - GOTO NoAction - END CATCH - END - -- Is the index fragmented? IF @CurrentIndexID IS NOT NULL AND @CurrentOnReadOnlyFileGroup = 0 @@ -2289,33 +2191,8 @@ BEGIN SET @CurrentMaxDOP = 1 END - -- 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 ((@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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL AND @CurrentObjectRowCount > 0)) - AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) - BEGIN - SET @CurrentUpdateStatistics = 'Y' - END - ELSE - BEGIN - SET @CurrentUpdateStatistics = 'N' - END - - SET @CurrentStatisticsSample = @StatisticsSample - SET @CurrentStatisticsPersistSample = @StatisticsPersistSample - SET @CurrentStatisticsResample = @StatisticsResample - - -- Incremental statistics only supports RESAMPLE - IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 - BEGIN - SET @CurrentStatisticsSample = NULL - SET @CurrentStatisticsPersistSample = NULL - SET @CurrentStatisticsResample = 'Y' - END - -- Create index comment - IF @CurrentIndexID IS NOT NULL + IF @CurrentAction 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 @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 + ', ' @@ -2334,7 +2211,7 @@ BEGIN SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar(max)),'N/A') END - IF @CurrentIndexID IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) + IF @CurrentAction IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) BEGIN SET @CurrentExtendedInfo = (SELECT * FROM (SELECT CAST(@CurrentPageCount AS nvarchar(max)) AS [PageCount], @@ -2342,7 +2219,7 @@ BEGIN ) 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) + IF @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentDatabaseContext = @CurrentDatabaseName @@ -2454,8 +2331,131 @@ BEGIN SET @CurrentMaxDOP = @MaxDOP - -- Create statistics comment + -- Should the statistics be updated? - Pre checks and final decision 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 ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) + BEGIN + -- Does the statistics exist? + SET @CurrentCommand = '' + + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + 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 = @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 + SET @CurrentStatisticsExists = 0 + GOTO NoAction + END + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + + GOTO NoAction + END CATCH + + -- Does the object or partition have rows? + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) + BEGIN + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 + BEGIN + SET @CurrentCommand += 'SELECT @ParamObjectHasRows = CASE WHEN EXISTS (SELECT * FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id IN (0,1) AND partition_number = @ParamPartitionNumber AND row_count > 0) THEN 1 ELSE 0 END' + END + ELSE + BEGIN + SET @CurrentCommand += 'SELECT @ParamObjectHasRows = CASE WHEN EXISTS (SELECT * FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id IN (0,1) AND row_count > 0) THEN 1 ELSE 0 END' + END + + BEGIN TRY + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamPartitionNumber int, @ParamObjectHasRows bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamObjectHasRows = @CurrentObjectHasRows OUTPUT + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The row count 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 + SET @ReturnCode = ERROR_NUMBER() + END + GOTO NoAction + END CATCH + END + + -- Has the data in the statistics been modified since the statistics was last updated? + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) + BEGIN + SET @CurrentCommand = '' + + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 + BEGIN + SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' + END + ELSE + BEGIN + SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' + END + + BEGIN TRY + 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 + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + + GOTO NoAction + END CATCH + END + + -- Update statistics? + IF ((@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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL AND @CurrentObjectHasRows = 1)) + BEGIN + SET @CurrentUpdateStatistics = 'Y' + END + ELSE + BEGIN + SET @CurrentUpdateStatistics = 'N' + END + END + + SET @CurrentStatisticsSample = @StatisticsSample + SET @CurrentStatisticsPersistSample = @StatisticsPersistSample + SET @CurrentStatisticsResample = @StatisticsResample + + -- Incremental statistics only supports RESAMPLE + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 + BEGIN + SET @CurrentStatisticsSample = NULL + SET @CurrentStatisticsPersistSample = NULL + SET @CurrentStatisticsResample = 'Y' + END + + -- Create statistics comment + IF @CurrentUpdateStatistics = 'Y' BEGIN SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' SET @CurrentComment += 'StatisticsType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' @@ -2465,15 +2465,19 @@ BEGIN SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar(max)),'N/A') END - IF @CurrentStatisticsID IS NOT NULL AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) + IF @CurrentUpdateStatistics = 'Y' AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) BEGIN - SET @CurrentExtendedInfo = (SELECT * - FROM (SELECT CAST(@CurrentRowCount AS nvarchar(max)) AS [RowCount], - CAST(@CurrentModificationCounter AS nvarchar(max)) AS ModificationCounter - ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentRowCount AS nvarchar(max)) AS [RowCount], + CAST(@CurrentModificationCounter AS nvarchar(max)) AS ModificationCounter + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) + END + ELSE + BEGIN + SET @CurrentExtendedInfo = NULL END - IF @CurrentStatisticsID IS NOT NULL AND @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentDatabaseContext = @CurrentDatabaseName @@ -2590,7 +2594,7 @@ BEGIN SET @CurrentHasFilter = NULL SET @CurrentNoRecompute = NULL SET @CurrentIsIncremental = NULL - SET @CurrentObjectRowCount = NULL + SET @CurrentObjectHasRows = NULL SET @CurrentRowCount = NULL SET @CurrentModificationCounter = NULL SET @CurrentOnReadOnlyFileGroup = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index b110023c..e23bf000 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: 2026-06-28 10:45:05 +Version: 2026-06-29 20:49:12 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-28 10:45:05 //-- + --// Version: 2026-06-29 20:49:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-28 10:45:05 //-- + --// Version: 2026-06-29 20:49:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4848,7 +4848,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-28 10:45:05 //-- + --// Version: 2026-06-29 20:49:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6796,7 +6796,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-28 10:45:05 //-- + --// Version: 2026-06-29 20:49:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6893,7 +6893,7 @@ BEGIN DECLARE @CurrentHasFilter bit DECLARE @CurrentNoRecompute bit DECLARE @CurrentIsIncremental bit - DECLARE @CurrentObjectRowCount bigint + DECLARE @CurrentObjectHasRows bit DECLARE @CurrentRowCount bigint DECLARE @CurrentModificationCounter bigint DECLARE @CurrentOnReadOnlyFileGroup bit @@ -8601,7 +8601,7 @@ BEGIN SET @ReturnCode = @Error END - -- Select column-level statistics for memory optimized tables + -- Select column level statistics for memory optimized tables SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + ' SELECT schemas.[schema_id] AS SchemaID' + ', schemas.[name] AS SchemaName' @@ -8819,104 +8819,6 @@ BEGIN END CATCH END - -- Does the statistics exist? - IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL - BEGIN - SET @CurrentCommand = '' - - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - - 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 = @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 - SET @CurrentStatisticsExists = 0 - GOTO NoAction - END - END TRY - BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 - SET @ReturnCode = ERROR_NUMBER() - END - - GOTO NoAction - END CATCH - END - - -- What is the object row count? - IF @CurrentStatisticsID IS NOT NULL AND @UpdateStatistics IS NOT NULL - BEGIN - SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - - IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 - BEGIN - SET @CurrentCommand += 'SELECT @ParamObjectRowCount = row_count FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id = (SELECT MIN(index_id) FROM sys.indexes WHERE [object_id] = @ParamObjectID) AND partition_number = @ParamPartitionNumber' - END - ELSE - BEGIN - SET @CurrentCommand += 'SELECT @ParamObjectRowCount = SUM(row_count) FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id = (SELECT MIN(index_id) FROM sys.indexes WHERE [object_id] = @ParamObjectID)' - END - - BEGIN TRY - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamPartitionNumber int, @ParamObjectRowCount bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamObjectRowCount = @CurrentObjectRowCount OUTPUT - END TRY - BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The row count 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 - SET @ReturnCode = ERROR_NUMBER() - END - GOTO NoAction - END CATCH - 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 - BEGIN - SET @CurrentCommand = '' - - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - - IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 - BEGIN - SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' - END - ELSE - BEGIN - SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' - END - - BEGIN TRY - 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 - END TRY - BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 - SET @ReturnCode = ERROR_NUMBER() - END - - GOTO NoAction - END CATCH - END - -- Is the index fragmented? IF @CurrentIndexID IS NOT NULL AND @CurrentOnReadOnlyFileGroup = 0 @@ -9029,33 +8931,8 @@ BEGIN SET @CurrentMaxDOP = 1 END - -- 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 ((@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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL AND @CurrentObjectRowCount > 0)) - AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) - BEGIN - SET @CurrentUpdateStatistics = 'Y' - END - ELSE - BEGIN - SET @CurrentUpdateStatistics = 'N' - END - - SET @CurrentStatisticsSample = @StatisticsSample - SET @CurrentStatisticsPersistSample = @StatisticsPersistSample - SET @CurrentStatisticsResample = @StatisticsResample - - -- Incremental statistics only supports RESAMPLE - IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 - BEGIN - SET @CurrentStatisticsSample = NULL - SET @CurrentStatisticsPersistSample = NULL - SET @CurrentStatisticsResample = 'Y' - END - -- Create index comment - IF @CurrentIndexID IS NOT NULL + IF @CurrentAction 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 @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 + ', ' @@ -9074,7 +8951,7 @@ BEGIN SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar(max)),'N/A') END - IF @CurrentIndexID IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) + IF @CurrentAction IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) BEGIN SET @CurrentExtendedInfo = (SELECT * FROM (SELECT CAST(@CurrentPageCount AS nvarchar(max)) AS [PageCount], @@ -9082,7 +8959,7 @@ BEGIN ) 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) + IF @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentDatabaseContext = @CurrentDatabaseName @@ -9194,8 +9071,131 @@ BEGIN SET @CurrentMaxDOP = @MaxDOP - -- Create statistics comment + -- Should the statistics be updated? - Pre checks and final decision 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 ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) + BEGIN + -- Does the statistics exist? + SET @CurrentCommand = '' + + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + 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 = @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 + SET @CurrentStatisticsExists = 0 + GOTO NoAction + END + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + + GOTO NoAction + END CATCH + + -- Does the object or partition have rows? + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) + BEGIN + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 + BEGIN + SET @CurrentCommand += 'SELECT @ParamObjectHasRows = CASE WHEN EXISTS (SELECT * FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id IN (0,1) AND partition_number = @ParamPartitionNumber AND row_count > 0) THEN 1 ELSE 0 END' + END + ELSE + BEGIN + SET @CurrentCommand += 'SELECT @ParamObjectHasRows = CASE WHEN EXISTS (SELECT * FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id IN (0,1) AND row_count > 0) THEN 1 ELSE 0 END' + END + + BEGIN TRY + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamPartitionNumber int, @ParamObjectHasRows bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamObjectHasRows = @CurrentObjectHasRows OUTPUT + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The row count 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 + SET @ReturnCode = ERROR_NUMBER() + END + GOTO NoAction + END CATCH + END + + -- Has the data in the statistics been modified since the statistics was last updated? + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) + BEGIN + SET @CurrentCommand = '' + + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 + BEGIN + SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' + END + ELSE + BEGIN + SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' + END + + BEGIN TRY + 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 + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + + GOTO NoAction + END CATCH + END + + -- Update statistics? + IF ((@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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL AND @CurrentObjectHasRows = 1)) + BEGIN + SET @CurrentUpdateStatistics = 'Y' + END + ELSE + BEGIN + SET @CurrentUpdateStatistics = 'N' + END + END + + SET @CurrentStatisticsSample = @StatisticsSample + SET @CurrentStatisticsPersistSample = @StatisticsPersistSample + SET @CurrentStatisticsResample = @StatisticsResample + + -- Incremental statistics only supports RESAMPLE + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 + BEGIN + SET @CurrentStatisticsSample = NULL + SET @CurrentStatisticsPersistSample = NULL + SET @CurrentStatisticsResample = 'Y' + END + + -- Create statistics comment + IF @CurrentUpdateStatistics = 'Y' BEGIN SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' SET @CurrentComment += 'StatisticsType: ' + CASE WHEN @CurrentIndexID IS NOT NULL THEN 'Index' ELSE 'Column' END + ', ' @@ -9205,15 +9205,19 @@ BEGIN SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar(max)),'N/A') END - IF @CurrentStatisticsID IS NOT NULL AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) + IF @CurrentUpdateStatistics = 'Y' AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) BEGIN - SET @CurrentExtendedInfo = (SELECT * - FROM (SELECT CAST(@CurrentRowCount AS nvarchar(max)) AS [RowCount], - CAST(@CurrentModificationCounter AS nvarchar(max)) AS ModificationCounter - ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentRowCount AS nvarchar(max)) AS [RowCount], + CAST(@CurrentModificationCounter AS nvarchar(max)) AS ModificationCounter + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) + END + ELSE + BEGIN + SET @CurrentExtendedInfo = NULL END - IF @CurrentStatisticsID IS NOT NULL AND @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + IF @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN SET @CurrentDatabaseContext = @CurrentDatabaseName @@ -9330,7 +9334,7 @@ BEGIN SET @CurrentHasFilter = NULL SET @CurrentNoRecompute = NULL SET @CurrentIsIncremental = NULL - SET @CurrentObjectRowCount = NULL + SET @CurrentObjectHasRows = NULL SET @CurrentRowCount = NULL SET @CurrentModificationCounter = NULL SET @CurrentOnReadOnlyFileGroup = NULL From 962475547235fc28818a39d249ef8bb2b4649250 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 3 Jul 2026 20:40:43 +0200 Subject: [PATCH 057/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 30 ++++--- DatabaseIntegrityCheck.sql | 48 +++++----- IndexOptimize.sql | 97 ++++++++++++++------ MaintenanceSolution.sql | 179 ++++++++++++++++++++++++------------- 5 files changed, 233 insertions(+), 123 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 9cdcd796..c0e67823 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-06-29 20:49:12 //-- + --// Version: 2026-07-03 20:28:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index ae145e58..20752ea5 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-29 20:49:12 //-- + --// Version: 2026-07-03 20:28:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -209,9 +209,9 @@ BEGIN ParentDirectoryExists bit) DECLARE @tmpDatabases TABLE (ID int IDENTITY, - DatabaseName nvarchar(max), - DatabaseNameFS nvarchar(max), - DatabaseType nvarchar(max), + DatabaseName nvarchar(128), + DatabaseNameFS nvarchar(128), + DatabaseType nvarchar(1), AvailabilityGroup bit, StartPosition int, DatabaseSize bigint, @@ -222,16 +222,16 @@ BEGIN PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, - AvailabilityGroupName nvarchar(max), + AvailabilityGroupName nvarchar(128), StartPosition int, Selected bit DEFAULT 0) - DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), - AvailabilityGroupName nvarchar(max)) + DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(128), + AvailabilityGroupName nvarchar(128)) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), - DatabaseType nvarchar(max), - AvailabilityGroup nvarchar(max), + DatabaseType nvarchar(1), + AvailabilityGroup bit, StartPosition int, Selected bit) @@ -262,7 +262,7 @@ BEGIN Mirror bit, DirectoryNumber int) - DECLARE @CurrentFiles TABLE ([Type] nvarchar(max), + DECLARE @CurrentFiles TABLE ([Type] nvarchar(4), FilePath nvarchar(max), Mirror bit) @@ -720,7 +720,7 @@ BEGIN --// Check database names //-- ---------------------------------------------------------------------------------------------------- - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @tmpDatabases WHERE Selected = 1 @@ -732,7 +732,7 @@ BEGIN SELECT 'The names of the following databases are not supported: ' + @ErrorMessage + '.', 16, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @tmpDatabases WHERE UPPER(DatabaseNameFS) IN(SELECT UPPER(DatabaseNameFS) FROM @tmpDatabases GROUP BY UPPER(DatabaseNameFS) HAVING COUNT(*) > 1 AND MAX(CAST(Selected AS int)) = 1) @@ -2440,7 +2440,8 @@ BEGIN --// Check that selected databases and availability groups exist //-- ---------------------------------------------------------------------------------------------------- - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedDatabases WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) @@ -2451,7 +2452,8 @@ BEGIN SELECT 'The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(AvailabilityGroupName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY AvailabilityGroupName ASC) FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName NOT LIKE '%[%]%' AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index fbb560b3..8c035255 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-29 20:49:12 //-- + --// Version: 2026-07-03 20:28:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -114,8 +114,8 @@ BEGIN DECLARE @CurrentState int DECLARE @tmpDatabases TABLE (ID int IDENTITY, - DatabaseName nvarchar(max), - DatabaseType nvarchar(max), + DatabaseName nvarchar(128), + DatabaseType nvarchar(1), AvailabilityGroup bit, [Snapshot] bit, StartPosition int, @@ -128,16 +128,16 @@ BEGIN PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, - AvailabilityGroupName nvarchar(max), + AvailabilityGroupName nvarchar(128), StartPosition int, Selected bit DEFAULT 0) - DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), - AvailabilityGroupName nvarchar(max)) + DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(128), + AvailabilityGroupName nvarchar(128)) DECLARE @tmpFileGroups TABLE (ID int IDENTITY, FileGroupID int, - FileGroupName nvarchar(max), + FileGroupName nvarchar(128), StartPosition int, [Order] int DEFAULT 0, Selected bit DEFAULT 0, @@ -146,10 +146,10 @@ BEGIN DECLARE @tmpObjects TABLE (ID int IDENTITY, SchemaID int, - SchemaName nvarchar(max), + SchemaName nvarchar(128), ObjectID int, - ObjectName nvarchar(max), - ObjectType nvarchar(max), + ObjectName nvarchar(128), + ObjectType nvarchar(2), StartPosition int, [Order] int DEFAULT 0, Selected bit DEFAULT 0, @@ -157,8 +157,8 @@ BEGIN PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), - DatabaseType nvarchar(max), - AvailabilityGroup nvarchar(max), + DatabaseType nvarchar(1), + AvailabilityGroup bit, StartPosition int, Selected bit) @@ -955,7 +955,8 @@ BEGIN --// Check that selected databases and availability groups exist //-- ---------------------------------------------------------------------------------------------------- - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedDatabases WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) @@ -966,7 +967,8 @@ BEGIN SELECT 'The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedFileGroups WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) @@ -977,7 +979,8 @@ BEGIN SELECT 'The following databases in the @FileGroups parameter do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedObjects WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) @@ -988,7 +991,8 @@ BEGIN SELECT 'The following databases in the @Objects parameter do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(AvailabilityGroupName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY AvailabilityGroupName ASC) FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName NOT LIKE '%[%]%' AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) @@ -999,7 +1003,8 @@ BEGIN SELECT 'The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedFileGroups WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName IN (SELECT DatabaseName FROM @tmpDatabases) @@ -1011,7 +1016,8 @@ BEGIN SELECT 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedObjects WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName IN (SELECT DatabaseName FROM @tmpDatabases) @@ -1564,7 +1570,8 @@ BEGIN UPDATE tmpFileGroups SET [Order] = RowNumber - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName) + '.' + QUOTENAME(FileGroupName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)) + '.' + QUOTENAME(FileGroupName), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC, FileGroupName ASC) FROM @SelectedFileGroups SelectedFileGroups WHERE DatabaseName = @CurrentDatabaseName AND FileGroupName NOT LIKE '%[%]%' @@ -1730,7 +1737,8 @@ BEGIN UPDATE tmpObjects SET [Order] = RowNumber - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC, SchemaName ASC, ObjectName ASC) FROM @SelectedObjects SelectedObjects WHERE DatabaseName = @CurrentDatabaseName AND SchemaName NOT LIKE '%[%]%' diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 87e69091..7dc59204 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-29 20:49:12 //-- + --// Version: 2026-07-03 20:28:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -170,8 +170,8 @@ BEGIN DECLARE @CurrentDelay datetime DECLARE @tmpDatabases TABLE (ID int IDENTITY, - DatabaseName nvarchar(max), - DatabaseType nvarchar(max), + DatabaseName nvarchar(128), + DatabaseType nvarchar(1), AvailabilityGroup bit, StartPosition int, DatabaseSize bigint, @@ -181,12 +181,12 @@ BEGIN PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, - AvailabilityGroupName nvarchar(max), + AvailabilityGroupName nvarchar(128), StartPosition int, Selected bit DEFAULT 0) - DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), - AvailabilityGroupName nvarchar(max)) + DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(128), + AvailabilityGroupName nvarchar(128)) DECLARE @tmpIndexesStatistics TABLE (ID int IDENTITY, SchemaID int, @@ -240,13 +240,20 @@ BEGIN IsTimestamp bit, PRIMARY KEY (ObjectID, IndexID)) + DECLARE @tmpIndexStatisticsProperties TABLE (ObjectID int NOT NULL, + StatisticsID int NOT NULL, + StatisticsName nvarchar(128), + [NoRecompute] bit, + IsIncremental bit, + PRIMARY KEY (ObjectID, StatisticsID)) + DECLARE @tmpResumableOperations TABLE (ObjectID int NOT NULL, IndexID int NOT NULL, PartitionNumber int) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), - DatabaseType nvarchar(max), - AvailabilityGroup nvarchar(max), + DatabaseType nvarchar(1), + AvailabilityGroup bit, StartPosition int, Selected bit) @@ -1188,7 +1195,8 @@ BEGIN --// Check that selected databases and availability groups exist //-- ---------------------------------------------------------------------------------------------------- - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedDatabases WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) @@ -1199,7 +1207,8 @@ BEGIN SELECT 'The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedIndexes WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) @@ -1210,7 +1219,8 @@ BEGIN SELECT 'The following databases in the @Indexes parameter do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(AvailabilityGroupName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY AvailabilityGroupName ASC) FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName NOT LIKE '%[%]%' AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) @@ -1221,7 +1231,8 @@ BEGIN SELECT 'The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedIndexes WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName IN (SELECT DatabaseName FROM @tmpDatabases) @@ -1649,17 +1660,12 @@ BEGIN + ' 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' ELSE ', 0 AS OnReadOnlyFileGroup' END + ', 0 AS ResumableIndexOperation' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental 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 + ' 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.tables tables ON objects.[object_id] = tables.[object_id]' - + ' INNER JOIN sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' IF @PartitionLevel = 'Y' BEGIN SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' @@ -1671,7 +1677,7 @@ BEGIN + ' AND indexes.is_disabled = 0' + ' AND indexes.is_hypothetical = 0' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation, PartitionID, PartitionNumber) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -1714,6 +1720,32 @@ BEGIN SET @ReturnCode = @Error END + -- Select statistics on indexes on tables + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT stats.[object_id] AS ObjectID' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental AS IsIncremental' + + ' FROM sys.stats stats' + + ' INNER JOIN sys.indexes indexes ON stats.[object_id] = indexes.[object_id] AND stats.stats_id = indexes.index_id' + + ' INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id]' + + ' INNER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + + ' WHERE objects.[type] = ''U''' + + ' AND tables.is_external = 0' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + ' AND indexes.[type] IN(1,2,5,6,7)' + + ' AND indexes.is_disabled = 0' + + ' AND indexes.is_hypothetical = 0' + + INSERT INTO @tmpIndexStatisticsProperties (ObjectID, StatisticsID, StatisticsName, [NoRecompute], IsIncremental) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + -- Select indexes on views SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + ' SELECT schemas.[schema_id] AS SchemaID' @@ -1808,11 +1840,12 @@ BEGIN END -- Select paused resumable index operations - SET @CurrentCommand = 'SELECT index_resumable_operations.object_id AS ObjectID' - + ', index_resumable_operations.index_id AS IndexID' - + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'index_resumable_operations.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END - + ' FROM sys.index_resumable_operations index_resumable_operations' - + ' WHERE index_resumable_operations.state_desc = ''PAUSED''' + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + 'SELECT index_resumable_operations.object_id AS ObjectID' + + ', index_resumable_operations.index_id AS IndexID' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'index_resumable_operations.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END + + ' FROM sys.index_resumable_operations index_resumable_operations' + + ' WHERE index_resumable_operations.state_desc = ''PAUSED''' INSERT INTO @tmpResumableOperations (ObjectID, IndexID, PartitionNumber) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand @@ -1891,6 +1924,15 @@ BEGIN END END + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.StatisticsID = tmpIndexStatisticsProperties.StatisticsID, + tmpIndexesStatistics.StatisticsName = tmpIndexStatisticsProperties.StatisticsName, + tmpIndexesStatistics.[NoRecompute] = tmpIndexStatisticsProperties.[NoRecompute], + tmpIndexesStatistics.IsIncremental = tmpIndexStatisticsProperties.IsIncremental + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @tmpIndexStatisticsProperties tmpIndexStatisticsProperties ON tmpIndexesStatistics.ObjectID = tmpIndexStatisticsProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexStatisticsProperties.StatisticsID + OPTION (RECOMPILE) + UPDATE tmpIndexesStatistics SET tmpIndexesStatistics.IsImageText = tmpIndexProperties.IsImageText, tmpIndexesStatistics.IsNewLOB = tmpIndexProperties.IsNewLOB, @@ -1966,7 +2008,8 @@ BEGIN UPDATE tmpIndexesStatistics SET [Order] = RowNumber - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC, SchemaName ASC, ObjectName ASC) FROM @SelectedIndexes SelectedIndexes WHERE DatabaseName = @CurrentDatabaseName AND SchemaName NOT LIKE '%[%]%' @@ -1982,7 +2025,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + '.' + QUOTENAME(IndexName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + '.' + QUOTENAME(IndexName), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC, SchemaName ASC, ObjectName ASC, IndexName ASC) FROM @SelectedIndexes SelectedIndexes WHERE DatabaseName = @CurrentDatabaseName AND SchemaName NOT LIKE '%[%]%' @@ -2333,7 +2377,7 @@ BEGIN -- Should the statistics be updated? - Pre checks and final decision 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 ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) BEGIN -- Does the statistics exist? @@ -2671,6 +2715,7 @@ BEGIN DELETE FROM @tmpIndexesStatistics DELETE FROM @tmpObjectProperties DELETE FROM @tmpIndexProperties + DELETE FROM @tmpIndexStatisticsProperties DELETE FROM @tmpResumableOperations END diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index e23bf000..1d7047d1 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: 2026-06-29 20:49:12 +Version: 2026-07-03 20:28:19 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-29 20:49:12 //-- + --// Version: 2026-07-03 20:28:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-29 20:49:12 //-- + --// Version: 2026-07-03 20:28:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -608,9 +608,9 @@ BEGIN ParentDirectoryExists bit) DECLARE @tmpDatabases TABLE (ID int IDENTITY, - DatabaseName nvarchar(max), - DatabaseNameFS nvarchar(max), - DatabaseType nvarchar(max), + DatabaseName nvarchar(128), + DatabaseNameFS nvarchar(128), + DatabaseType nvarchar(1), AvailabilityGroup bit, StartPosition int, DatabaseSize bigint, @@ -621,16 +621,16 @@ BEGIN PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, - AvailabilityGroupName nvarchar(max), + AvailabilityGroupName nvarchar(128), StartPosition int, Selected bit DEFAULT 0) - DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), - AvailabilityGroupName nvarchar(max)) + DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(128), + AvailabilityGroupName nvarchar(128)) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), - DatabaseType nvarchar(max), - AvailabilityGroup nvarchar(max), + DatabaseType nvarchar(1), + AvailabilityGroup bit, StartPosition int, Selected bit) @@ -661,7 +661,7 @@ BEGIN Mirror bit, DirectoryNumber int) - DECLARE @CurrentFiles TABLE ([Type] nvarchar(max), + DECLARE @CurrentFiles TABLE ([Type] nvarchar(4), FilePath nvarchar(max), Mirror bit) @@ -1119,7 +1119,7 @@ BEGIN --// Check database names //-- ---------------------------------------------------------------------------------------------------- - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @tmpDatabases WHERE Selected = 1 @@ -1131,7 +1131,7 @@ BEGIN SELECT 'The names of the following databases are not supported: ' + @ErrorMessage + '.', 16, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @tmpDatabases WHERE UPPER(DatabaseNameFS) IN(SELECT UPPER(DatabaseNameFS) FROM @tmpDatabases GROUP BY UPPER(DatabaseNameFS) HAVING COUNT(*) > 1 AND MAX(CAST(Selected AS int)) = 1) @@ -2839,7 +2839,8 @@ BEGIN --// Check that selected databases and availability groups exist //-- ---------------------------------------------------------------------------------------------------- - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedDatabases WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) @@ -2850,7 +2851,8 @@ BEGIN SELECT 'The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(AvailabilityGroupName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY AvailabilityGroupName ASC) FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName NOT LIKE '%[%]%' AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) @@ -4848,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-29 20:49:12 //-- + --// Version: 2026-07-03 20:28:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4922,8 +4924,8 @@ BEGIN DECLARE @CurrentState int DECLARE @tmpDatabases TABLE (ID int IDENTITY, - DatabaseName nvarchar(max), - DatabaseType nvarchar(max), + DatabaseName nvarchar(128), + DatabaseType nvarchar(1), AvailabilityGroup bit, [Snapshot] bit, StartPosition int, @@ -4936,16 +4938,16 @@ BEGIN PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, - AvailabilityGroupName nvarchar(max), + AvailabilityGroupName nvarchar(128), StartPosition int, Selected bit DEFAULT 0) - DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), - AvailabilityGroupName nvarchar(max)) + DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(128), + AvailabilityGroupName nvarchar(128)) DECLARE @tmpFileGroups TABLE (ID int IDENTITY, FileGroupID int, - FileGroupName nvarchar(max), + FileGroupName nvarchar(128), StartPosition int, [Order] int DEFAULT 0, Selected bit DEFAULT 0, @@ -4954,10 +4956,10 @@ BEGIN DECLARE @tmpObjects TABLE (ID int IDENTITY, SchemaID int, - SchemaName nvarchar(max), + SchemaName nvarchar(128), ObjectID int, - ObjectName nvarchar(max), - ObjectType nvarchar(max), + ObjectName nvarchar(128), + ObjectType nvarchar(2), StartPosition int, [Order] int DEFAULT 0, Selected bit DEFAULT 0, @@ -4965,8 +4967,8 @@ BEGIN PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), - DatabaseType nvarchar(max), - AvailabilityGroup nvarchar(max), + DatabaseType nvarchar(1), + AvailabilityGroup bit, StartPosition int, Selected bit) @@ -5763,7 +5765,8 @@ BEGIN --// Check that selected databases and availability groups exist //-- ---------------------------------------------------------------------------------------------------- - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedDatabases WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) @@ -5774,7 +5777,8 @@ BEGIN SELECT 'The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedFileGroups WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) @@ -5785,7 +5789,8 @@ BEGIN SELECT 'The following databases in the @FileGroups parameter do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedObjects WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) @@ -5796,7 +5801,8 @@ BEGIN SELECT 'The following databases in the @Objects parameter do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(AvailabilityGroupName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY AvailabilityGroupName ASC) FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName NOT LIKE '%[%]%' AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) @@ -5807,7 +5813,8 @@ BEGIN SELECT 'The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedFileGroups WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName IN (SELECT DatabaseName FROM @tmpDatabases) @@ -5819,7 +5826,8 @@ BEGIN SELECT 'The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedObjects WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName IN (SELECT DatabaseName FROM @tmpDatabases) @@ -6372,7 +6380,8 @@ BEGIN UPDATE tmpFileGroups SET [Order] = RowNumber - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName) + '.' + QUOTENAME(FileGroupName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)) + '.' + QUOTENAME(FileGroupName), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC, FileGroupName ASC) FROM @SelectedFileGroups SelectedFileGroups WHERE DatabaseName = @CurrentDatabaseName AND FileGroupName NOT LIKE '%[%]%' @@ -6538,7 +6547,8 @@ BEGIN UPDATE tmpObjects SET [Order] = RowNumber - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC, SchemaName ASC, ObjectName ASC) FROM @SelectedObjects SelectedObjects WHERE DatabaseName = @CurrentDatabaseName AND SchemaName NOT LIKE '%[%]%' @@ -6796,7 +6806,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-06-29 20:49:12 //-- + --// Version: 2026-07-03 20:28:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6910,8 +6920,8 @@ BEGIN DECLARE @CurrentDelay datetime DECLARE @tmpDatabases TABLE (ID int IDENTITY, - DatabaseName nvarchar(max), - DatabaseType nvarchar(max), + DatabaseName nvarchar(128), + DatabaseType nvarchar(1), AvailabilityGroup bit, StartPosition int, DatabaseSize bigint, @@ -6921,12 +6931,12 @@ BEGIN PRIMARY KEY (Selected, Completed, [Order], ID)) DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, - AvailabilityGroupName nvarchar(max), + AvailabilityGroupName nvarchar(128), StartPosition int, Selected bit DEFAULT 0) - DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(max), - AvailabilityGroupName nvarchar(max)) + DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(128), + AvailabilityGroupName nvarchar(128)) DECLARE @tmpIndexesStatistics TABLE (ID int IDENTITY, SchemaID int, @@ -6980,13 +6990,20 @@ BEGIN IsTimestamp bit, PRIMARY KEY (ObjectID, IndexID)) + DECLARE @tmpIndexStatisticsProperties TABLE (ObjectID int NOT NULL, + StatisticsID int NOT NULL, + StatisticsName nvarchar(128), + [NoRecompute] bit, + IsIncremental bit, + PRIMARY KEY (ObjectID, StatisticsID)) + DECLARE @tmpResumableOperations TABLE (ObjectID int NOT NULL, IndexID int NOT NULL, PartitionNumber int) DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), - DatabaseType nvarchar(max), - AvailabilityGroup nvarchar(max), + DatabaseType nvarchar(1), + AvailabilityGroup bit, StartPosition int, Selected bit) @@ -7928,7 +7945,8 @@ BEGIN --// Check that selected databases and availability groups exist //-- ---------------------------------------------------------------------------------------------------- - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedDatabases WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) @@ -7939,7 +7957,8 @@ BEGIN SELECT 'The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedIndexes WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) @@ -7950,7 +7969,8 @@ BEGIN SELECT 'The following databases in the @Indexes parameter do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(AvailabilityGroupName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY AvailabilityGroupName ASC) FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName NOT LIKE '%[%]%' AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) @@ -7961,7 +7981,8 @@ BEGIN SELECT 'The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1 END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) FROM @SelectedIndexes WHERE DatabaseName NOT LIKE '%[%]%' AND DatabaseName IN (SELECT DatabaseName FROM @tmpDatabases) @@ -8389,17 +8410,12 @@ BEGIN + ' 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' ELSE ', 0 AS OnReadOnlyFileGroup' END + ', 0 AS ResumableIndexOperation' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental 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 + ' 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.tables tables ON objects.[object_id] = tables.[object_id]' - + ' INNER JOIN sys.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' IF @PartitionLevel = 'Y' BEGIN SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' @@ -8411,7 +8427,7 @@ BEGIN + ' AND indexes.is_disabled = 0' + ' AND indexes.is_hypothetical = 0' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation, PartitionID, PartitionNumber) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -8454,6 +8470,32 @@ BEGIN SET @ReturnCode = @Error END + -- Select statistics on indexes on tables + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT stats.[object_id] AS ObjectID' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental AS IsIncremental' + + ' FROM sys.stats stats' + + ' INNER JOIN sys.indexes indexes ON stats.[object_id] = indexes.[object_id] AND stats.stats_id = indexes.index_id' + + ' INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id]' + + ' INNER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + + ' WHERE objects.[type] = ''U''' + + ' AND tables.is_external = 0' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + ' AND indexes.[type] IN(1,2,5,6,7)' + + ' AND indexes.is_disabled = 0' + + ' AND indexes.is_hypothetical = 0' + + INSERT INTO @tmpIndexStatisticsProperties (ObjectID, StatisticsID, StatisticsName, [NoRecompute], IsIncremental) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + -- Select indexes on views SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + ' SELECT schemas.[schema_id] AS SchemaID' @@ -8548,11 +8590,12 @@ BEGIN END -- Select paused resumable index operations - SET @CurrentCommand = 'SELECT index_resumable_operations.object_id AS ObjectID' - + ', index_resumable_operations.index_id AS IndexID' - + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'index_resumable_operations.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END - + ' FROM sys.index_resumable_operations index_resumable_operations' - + ' WHERE index_resumable_operations.state_desc = ''PAUSED''' + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + 'SELECT index_resumable_operations.object_id AS ObjectID' + + ', index_resumable_operations.index_id AS IndexID' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'index_resumable_operations.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END + + ' FROM sys.index_resumable_operations index_resumable_operations' + + ' WHERE index_resumable_operations.state_desc = ''PAUSED''' INSERT INTO @tmpResumableOperations (ObjectID, IndexID, PartitionNumber) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand @@ -8631,6 +8674,15 @@ BEGIN END END + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.StatisticsID = tmpIndexStatisticsProperties.StatisticsID, + tmpIndexesStatistics.StatisticsName = tmpIndexStatisticsProperties.StatisticsName, + tmpIndexesStatistics.[NoRecompute] = tmpIndexStatisticsProperties.[NoRecompute], + tmpIndexesStatistics.IsIncremental = tmpIndexStatisticsProperties.IsIncremental + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @tmpIndexStatisticsProperties tmpIndexStatisticsProperties ON tmpIndexesStatistics.ObjectID = tmpIndexStatisticsProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexStatisticsProperties.StatisticsID + OPTION (RECOMPILE) + UPDATE tmpIndexesStatistics SET tmpIndexesStatistics.IsImageText = tmpIndexProperties.IsImageText, tmpIndexesStatistics.IsNewLOB = tmpIndexProperties.IsNewLOB, @@ -8706,7 +8758,8 @@ BEGIN UPDATE tmpIndexesStatistics SET [Order] = RowNumber - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC, SchemaName ASC, ObjectName ASC) FROM @SelectedIndexes SelectedIndexes WHERE DatabaseName = @CurrentDatabaseName AND SchemaName NOT LIKE '%[%]%' @@ -8722,7 +8775,8 @@ BEGIN RAISERROR(@EmptyLine,10,1) WITH NOWAIT END - SELECT @ErrorMessage = STRING_AGG(QUOTENAME(DatabaseName) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + '.' + QUOTENAME(IndexName), ', ') + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + '.' + QUOTENAME(IndexName), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC, SchemaName ASC, ObjectName ASC, IndexName ASC) FROM @SelectedIndexes SelectedIndexes WHERE DatabaseName = @CurrentDatabaseName AND SchemaName NOT LIKE '%[%]%' @@ -9073,7 +9127,7 @@ BEGIN -- Should the statistics be updated? - Pre checks and final decision 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 ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) BEGIN -- Does the statistics exist? @@ -9411,6 +9465,7 @@ BEGIN DELETE FROM @tmpIndexesStatistics DELETE FROM @tmpObjectProperties DELETE FROM @tmpIndexProperties + DELETE FROM @tmpIndexStatisticsProperties DELETE FROM @tmpResumableOperations END From dcc8fd25eea3e4aa1c20774a669d84627a77057d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 3 Jul 2026 20:47:57 +0200 Subject: [PATCH 058/177] 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 c0e67823..e4f6a41d 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-03 20:28:19 //-- + --// Version: 2026-07-03 20:47:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 20752ea5..9d104496 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 20:28:19 //-- + --// Version: 2026-07-03 20:47:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 8c035255..86305e44 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 20:28:19 //-- + --// Version: 2026-07-03 20:47:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 7dc59204..9845b52d 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 20:28:19 //-- + --// Version: 2026-07-03 20:47:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1841,7 +1841,7 @@ BEGIN -- Select paused resumable index operations SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + 'SELECT index_resumable_operations.object_id AS ObjectID' + + ' SELECT index_resumable_operations.object_id AS ObjectID' + ', index_resumable_operations.index_id AS IndexID' + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'index_resumable_operations.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END + ' FROM sys.index_resumable_operations index_resumable_operations' diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 1d7047d1..09928a33 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: 2026-07-03 20:28:19 +Version: 2026-07-03 20:47:15 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 20:28:19 //-- + --// Version: 2026-07-03 20:47:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 20:28:19 //-- + --// Version: 2026-07-03 20:47:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 20:28:19 //-- + --// Version: 2026-07-03 20:47:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6806,7 +6806,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 20:28:19 //-- + --// Version: 2026-07-03 20:47:15 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8591,7 +8591,7 @@ BEGIN -- Select paused resumable index operations SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + 'SELECT index_resumable_operations.object_id AS ObjectID' + + ' SELECT index_resumable_operations.object_id AS ObjectID' + ', index_resumable_operations.index_id AS IndexID' + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'index_resumable_operations.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END + ' FROM sys.index_resumable_operations index_resumable_operations' From 84e8108169213df79e337a1bb5574e969a4a41b0 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 3 Jul 2026 22:09:18 +0200 Subject: [PATCH 059/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 76 ++++++++++++++++++---------------- MaintenanceSolution.sql | 84 ++++++++++++++++++++------------------ 5 files changed, 89 insertions(+), 77 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index e4f6a41d..0b1eeaca 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-03 20:47:15 //-- + --// Version: 2026-07-03 22:08:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 9d104496..42c061c2 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 20:47:15 //-- + --// Version: 2026-07-03 22:08:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 86305e44..0aa2f6ac 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 20:47:15 //-- + --// Version: 2026-07-03 22:08:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 9845b52d..bb5b6406 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 20:47:15 //-- + --// Version: 2026-07-03 22:08:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1720,32 +1720,6 @@ BEGIN SET @ReturnCode = @Error END - -- Select statistics on indexes on tables - SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT stats.[object_id] AS ObjectID' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental AS IsIncremental' - + ' FROM sys.stats stats' - + ' INNER JOIN sys.indexes indexes ON stats.[object_id] = indexes.[object_id] AND stats.stats_id = indexes.index_id' - + ' INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id]' - + ' INNER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' - + ' WHERE objects.[type] = ''U''' - + ' AND tables.is_external = 0' - + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END - + ' AND indexes.[type] IN(1,2,5,6,7)' - + ' AND indexes.is_disabled = 0' - + ' AND indexes.is_hypothetical = 0' - - INSERT INTO @tmpIndexStatisticsProperties (ObjectID, StatisticsID, StatisticsName, [NoRecompute], IsIncremental) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand - SET @Error = @@ERROR - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - END - -- Select indexes on views SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + ' SELECT schemas.[schema_id] AS SchemaID' @@ -1856,6 +1830,35 @@ BEGIN END END + IF @UpdateStatistics IN('ALL','INDEX') + BEGIN + -- Select statistics on indexes on tables + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT stats.[object_id] AS ObjectID' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental AS IsIncremental' + + ' FROM sys.stats stats' + + ' INNER JOIN sys.indexes indexes ON stats.[object_id] = indexes.[object_id] AND stats.stats_id = indexes.index_id' + + ' INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id]' + + ' INNER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + + ' WHERE objects.[type] = ''U''' + + ' AND tables.is_external = 0' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + ' AND indexes.[type] IN(1,2,5,6,7)' + + ' AND indexes.is_disabled = 0' + + ' AND indexes.is_hypothetical = 0' + + INSERT INTO @tmpIndexStatisticsProperties (ObjectID, StatisticsID, StatisticsName, [NoRecompute], IsIncremental) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + END + IF @UpdateStatistics IN('ALL','COLUMNS') BEGIN -- Select column level statistics @@ -1924,14 +1927,17 @@ BEGIN END END - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.StatisticsID = tmpIndexStatisticsProperties.StatisticsID, - tmpIndexesStatistics.StatisticsName = tmpIndexStatisticsProperties.StatisticsName, - tmpIndexesStatistics.[NoRecompute] = tmpIndexStatisticsProperties.[NoRecompute], - tmpIndexesStatistics.IsIncremental = tmpIndexStatisticsProperties.IsIncremental - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @tmpIndexStatisticsProperties tmpIndexStatisticsProperties ON tmpIndexesStatistics.ObjectID = tmpIndexStatisticsProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexStatisticsProperties.StatisticsID - OPTION (RECOMPILE) + IF @UpdateStatistics IN('ALL','INDEX') + BEGIN + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.StatisticsID = tmpIndexStatisticsProperties.StatisticsID, + tmpIndexesStatistics.StatisticsName = tmpIndexStatisticsProperties.StatisticsName, + tmpIndexesStatistics.[NoRecompute] = tmpIndexStatisticsProperties.[NoRecompute], + tmpIndexesStatistics.IsIncremental = tmpIndexStatisticsProperties.IsIncremental + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @tmpIndexStatisticsProperties tmpIndexStatisticsProperties ON tmpIndexesStatistics.ObjectID = tmpIndexStatisticsProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexStatisticsProperties.StatisticsID + OPTION (RECOMPILE) + END UPDATE tmpIndexesStatistics SET tmpIndexesStatistics.IsImageText = tmpIndexProperties.IsImageText, diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 09928a33..81ba7c73 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: 2026-07-03 20:47:15 +Version: 2026-07-03 22:08:38 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 20:47:15 //-- + --// Version: 2026-07-03 22:08:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 20:47:15 //-- + --// Version: 2026-07-03 22:08:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 20:47:15 //-- + --// Version: 2026-07-03 22:08:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6806,7 +6806,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 20:47:15 //-- + --// Version: 2026-07-03 22:08:38 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8470,32 +8470,6 @@ BEGIN SET @ReturnCode = @Error END - -- Select statistics on indexes on tables - SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT stats.[object_id] AS ObjectID' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental AS IsIncremental' - + ' FROM sys.stats stats' - + ' INNER JOIN sys.indexes indexes ON stats.[object_id] = indexes.[object_id] AND stats.stats_id = indexes.index_id' - + ' INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id]' - + ' INNER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' - + ' WHERE objects.[type] = ''U''' - + ' AND tables.is_external = 0' - + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END - + ' AND indexes.[type] IN(1,2,5,6,7)' - + ' AND indexes.is_disabled = 0' - + ' AND indexes.is_hypothetical = 0' - - INSERT INTO @tmpIndexStatisticsProperties (ObjectID, StatisticsID, StatisticsName, [NoRecompute], IsIncremental) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand - SET @Error = @@ERROR - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - END - -- Select indexes on views SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + ' SELECT schemas.[schema_id] AS SchemaID' @@ -8606,6 +8580,35 @@ BEGIN END END + IF @UpdateStatistics IN('ALL','INDEX') + BEGIN + -- Select statistics on indexes on tables + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT stats.[object_id] AS ObjectID' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental AS IsIncremental' + + ' FROM sys.stats stats' + + ' INNER JOIN sys.indexes indexes ON stats.[object_id] = indexes.[object_id] AND stats.stats_id = indexes.index_id' + + ' INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id]' + + ' INNER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' + + ' WHERE objects.[type] = ''U''' + + ' AND tables.is_external = 0' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + + ' AND indexes.[type] IN(1,2,5,6,7)' + + ' AND indexes.is_disabled = 0' + + ' AND indexes.is_hypothetical = 0' + + INSERT INTO @tmpIndexStatisticsProperties (ObjectID, StatisticsID, StatisticsName, [NoRecompute], IsIncremental) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + END + IF @UpdateStatistics IN('ALL','COLUMNS') BEGIN -- Select column level statistics @@ -8674,14 +8677,17 @@ BEGIN END END - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.StatisticsID = tmpIndexStatisticsProperties.StatisticsID, - tmpIndexesStatistics.StatisticsName = tmpIndexStatisticsProperties.StatisticsName, - tmpIndexesStatistics.[NoRecompute] = tmpIndexStatisticsProperties.[NoRecompute], - tmpIndexesStatistics.IsIncremental = tmpIndexStatisticsProperties.IsIncremental - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @tmpIndexStatisticsProperties tmpIndexStatisticsProperties ON tmpIndexesStatistics.ObjectID = tmpIndexStatisticsProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexStatisticsProperties.StatisticsID - OPTION (RECOMPILE) + IF @UpdateStatistics IN('ALL','INDEX') + BEGIN + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.StatisticsID = tmpIndexStatisticsProperties.StatisticsID, + tmpIndexesStatistics.StatisticsName = tmpIndexStatisticsProperties.StatisticsName, + tmpIndexesStatistics.[NoRecompute] = tmpIndexStatisticsProperties.[NoRecompute], + tmpIndexesStatistics.IsIncremental = tmpIndexStatisticsProperties.IsIncremental + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @tmpIndexStatisticsProperties tmpIndexStatisticsProperties ON tmpIndexesStatistics.ObjectID = tmpIndexStatisticsProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexStatisticsProperties.StatisticsID + OPTION (RECOMPILE) + END UPDATE tmpIndexesStatistics SET tmpIndexesStatistics.IsImageText = tmpIndexProperties.IsImageText, From 1b15b277549decc8a4139cc0130cb9cad89248c2 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 3 Jul 2026 22:14:50 +0200 Subject: [PATCH 060/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 21 +++++++++------------ MaintenanceSolution.sql | 29 +++++++++++++---------------- 5 files changed, 25 insertions(+), 31 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 0b1eeaca..9d1822e2 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-03 22:08:38 //-- + --// Version: 2026-07-03 22:14:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 42c061c2..106726d3 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 22:08:38 //-- + --// Version: 2026-07-03 22:14:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 0aa2f6ac..ca17a4eb 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 22:08:38 //-- + --// Version: 2026-07-03 22:14:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index bb5b6406..f63aa5f6 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 22:08:38 //-- + --// Version: 2026-07-03 22:14:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1927,17 +1927,14 @@ BEGIN END END - IF @UpdateStatistics IN('ALL','INDEX') - BEGIN - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.StatisticsID = tmpIndexStatisticsProperties.StatisticsID, - tmpIndexesStatistics.StatisticsName = tmpIndexStatisticsProperties.StatisticsName, - tmpIndexesStatistics.[NoRecompute] = tmpIndexStatisticsProperties.[NoRecompute], - tmpIndexesStatistics.IsIncremental = tmpIndexStatisticsProperties.IsIncremental - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @tmpIndexStatisticsProperties tmpIndexStatisticsProperties ON tmpIndexesStatistics.ObjectID = tmpIndexStatisticsProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexStatisticsProperties.StatisticsID - OPTION (RECOMPILE) - END + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.StatisticsID = tmpIndexStatisticsProperties.StatisticsID, + tmpIndexesStatistics.StatisticsName = tmpIndexStatisticsProperties.StatisticsName, + tmpIndexesStatistics.[NoRecompute] = tmpIndexStatisticsProperties.[NoRecompute], + tmpIndexesStatistics.IsIncremental = tmpIndexStatisticsProperties.IsIncremental + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @tmpIndexStatisticsProperties tmpIndexStatisticsProperties ON tmpIndexesStatistics.ObjectID = tmpIndexStatisticsProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexStatisticsProperties.StatisticsID + OPTION (RECOMPILE) UPDATE tmpIndexesStatistics SET tmpIndexesStatistics.IsImageText = tmpIndexProperties.IsImageText, diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 81ba7c73..cf68675b 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: 2026-07-03 22:08:38 +Version: 2026-07-03 22:14:11 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 22:08:38 //-- + --// Version: 2026-07-03 22:14:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 22:08:38 //-- + --// Version: 2026-07-03 22:14:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4850,7 +4850,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 22:08:38 //-- + --// Version: 2026-07-03 22:14:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6806,7 +6806,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 22:08:38 //-- + --// Version: 2026-07-03 22:14:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8677,17 +8677,14 @@ BEGIN END END - IF @UpdateStatistics IN('ALL','INDEX') - BEGIN - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.StatisticsID = tmpIndexStatisticsProperties.StatisticsID, - tmpIndexesStatistics.StatisticsName = tmpIndexStatisticsProperties.StatisticsName, - tmpIndexesStatistics.[NoRecompute] = tmpIndexStatisticsProperties.[NoRecompute], - tmpIndexesStatistics.IsIncremental = tmpIndexStatisticsProperties.IsIncremental - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @tmpIndexStatisticsProperties tmpIndexStatisticsProperties ON tmpIndexesStatistics.ObjectID = tmpIndexStatisticsProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexStatisticsProperties.StatisticsID - OPTION (RECOMPILE) - END + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.StatisticsID = tmpIndexStatisticsProperties.StatisticsID, + tmpIndexesStatistics.StatisticsName = tmpIndexStatisticsProperties.StatisticsName, + tmpIndexesStatistics.[NoRecompute] = tmpIndexStatisticsProperties.[NoRecompute], + tmpIndexesStatistics.IsIncremental = tmpIndexStatisticsProperties.IsIncremental + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @tmpIndexStatisticsProperties tmpIndexStatisticsProperties ON tmpIndexesStatistics.ObjectID = tmpIndexStatisticsProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexStatisticsProperties.StatisticsID + OPTION (RECOMPILE) UPDATE tmpIndexesStatistics SET tmpIndexesStatistics.IsImageText = tmpIndexProperties.IsImageText, From 5909f733ecf062e14b7a002cbaa049683511610d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 4 Jul 2026 12:08:08 +0200 Subject: [PATCH 061/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 41 +++++++---------------- DatabaseIntegrityCheck.sql | 8 ++++- IndexOptimize.sql | 14 +++++++- MaintenanceSolution.sql | 67 +++++++++++++++++++------------------- 5 files changed, 65 insertions(+), 67 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 9d1822e2..38d945bf 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-03 22:14:11 //-- + --// Version: 2026-07-04 11:58:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 106726d3..079b5637 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 22:14:11 //-- + --// Version: 2026-07-04 11:58:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -301,7 +301,7 @@ BEGIN END END - DECLARE @AmazonRDS bit = CASE WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- @@ -846,7 +846,7 @@ BEGIN 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 + SELECT 'The same directory has been specified multiple times in the parameters @Directory and @MirrorDirectory.', 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 @@ -887,12 +887,6 @@ BEGIN 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 @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -1031,13 +1025,13 @@ BEGIN 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 + SELECT 'The same URL has been specified multiple times in the parameters @URL and @MirrorURL.', 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 + SELECT 'The number of URLs for the parameters @URL and @MirrorURL has to be the same.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -1048,18 +1042,6 @@ BEGIN 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 - ---------------------------------------------------------------------------------------------------- --// Get directory separator //-- ---------------------------------------------------------------------------------------------------- @@ -1706,7 +1688,6 @@ BEGIN 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, [State]) SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16, 4 @@ -2293,25 +2274,25 @@ BEGIN IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16, 1 + SELECT 'The value for the parameter @ObjectLevelRecoveryMap 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 + SELECT 'The value for the parameter @ObjectLevelRecoveryMap 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 + SELECT 'The value for the parameter @ObjectLevelRecoveryMap 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 + SELECT 'The value for the parameter @ObjectLevelRecoveryMap is not supported.', 16, 4 END ---------------------------------------------------------------------------------------------------- @@ -2365,7 +2346,7 @@ BEGIN IF @RetainDays IS NOT NULL AND @BackupSoftware <> 'LITESPEED' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @RetainDays is not supported.', 16, 1 + SELECT 'The value for the parameter @RetainDays is not supported.', 16, 2 END ---------------------------------------------------------------------------------------------------- @@ -3448,7 +3429,7 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),3)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),6)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',@CurrentNumberOfFiles) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',CAST(@CurrentNumberOfFiles AS nvarchar(max))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3))) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index ca17a4eb..fe9e01d4 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 22:14:11 //-- + --// Version: 2026-07-04 11:58:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -865,6 +865,12 @@ BEGIN SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 1 END + IF @LockTimeout > 86400 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 2 + END + ---------------------------------------------------------------------------------------------------- IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL diff --git a/IndexOptimize.sql b/IndexOptimize.sql index f63aa5f6..e9863cc3 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 22:14:11 //-- + --// Version: 2026-07-04 11:58:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1107,6 +1107,12 @@ BEGIN SELECT 'The value for the parameter @Delay is not supported.', 16, 1 END + IF @Delay >= 86400 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Delay is not supported.', 16, 2 + END + ---------------------------------------------------------------------------------------------------- IF @LockTimeout < 0 @@ -1115,6 +1121,12 @@ BEGIN SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 1 END + IF @LockTimeout > 86400 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 2 + END + ---------------------------------------------------------------------------------------------------- IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index cf68675b..d53f7930 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: 2026-07-03 22:14:11 +Version: 2026-07-04 11:58:45 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 22:14:11 //-- + --// Version: 2026-07-04 11:58:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 22:14:11 //-- + --// Version: 2026-07-04 11:58:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -700,7 +700,7 @@ BEGIN END END - DECLARE @AmazonRDS bit = CASE WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- @@ -1245,7 +1245,7 @@ BEGIN 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 + SELECT 'The same directory has been specified multiple times in the parameters @Directory and @MirrorDirectory.', 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 @@ -1286,12 +1286,6 @@ BEGIN 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 @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -1430,13 +1424,13 @@ BEGIN 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 + SELECT 'The same URL has been specified multiple times in the parameters @URL and @MirrorURL.', 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 + SELECT 'The number of URLs for the parameters @URL and @MirrorURL has to be the same.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -1447,18 +1441,6 @@ BEGIN 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 - ---------------------------------------------------------------------------------------------------- --// Get directory separator //-- ---------------------------------------------------------------------------------------------------- @@ -2105,7 +2087,6 @@ BEGIN 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, [State]) SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16, 4 @@ -2692,25 +2673,25 @@ BEGIN IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ObjectLevelRecovery is not supported.', 16, 1 + SELECT 'The value for the parameter @ObjectLevelRecoveryMap 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 + SELECT 'The value for the parameter @ObjectLevelRecoveryMap 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 + SELECT 'The value for the parameter @ObjectLevelRecoveryMap 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 + SELECT 'The value for the parameter @ObjectLevelRecoveryMap is not supported.', 16, 4 END ---------------------------------------------------------------------------------------------------- @@ -2764,7 +2745,7 @@ BEGIN IF @RetainDays IS NOT NULL AND @BackupSoftware <> 'LITESPEED' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @RetainDays is not supported.', 16, 1 + SELECT 'The value for the parameter @RetainDays is not supported.', 16, 2 END ---------------------------------------------------------------------------------------------------- @@ -3847,7 +3828,7 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),3)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),6)) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',@CurrentNumberOfFiles) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',CAST(@CurrentNumberOfFiles AS nvarchar(max))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3))) @@ -4850,7 +4831,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 22:14:11 //-- + --// Version: 2026-07-04 11:58:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5675,6 +5656,12 @@ BEGIN SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 1 END + IF @LockTimeout > 86400 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 2 + END + ---------------------------------------------------------------------------------------------------- IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL @@ -6806,7 +6793,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-03 22:14:11 //-- + --// Version: 2026-07-04 11:58:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7857,6 +7844,12 @@ BEGIN SELECT 'The value for the parameter @Delay is not supported.', 16, 1 END + IF @Delay >= 86400 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Delay is not supported.', 16, 2 + END + ---------------------------------------------------------------------------------------------------- IF @LockTimeout < 0 @@ -7865,6 +7858,12 @@ BEGIN SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 1 END + IF @LockTimeout > 86400 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 2 + END + ---------------------------------------------------------------------------------------------------- IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL From 14c3296a0e348a62459921631d797d39872c97c4 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 4 Jul 2026 13:44:09 +0200 Subject: [PATCH 062/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 42 ++++++++++++++--------------- DatabaseIntegrityCheck.sql | 4 +-- IndexOptimize.sql | 4 +-- MaintenanceSolution.sql | 54 +++++++++++++++++++------------------- 5 files changed, 53 insertions(+), 53 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 38d945bf..5b80f1fa 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-04 11:58:45 //-- + --// Version: 2026-07-04 13:43:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 079b5637..bb07f338 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 11:58:45 //-- + --// Version: 2026-07-04 13:43:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -890,25 +890,25 @@ BEGIN 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 + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 2 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 + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 3 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 + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 4 END IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) BEGIN 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 + SELECT 'The value for the parameter @MirrorDirectory is not supported. Mirrored backup to disk is only available in Enterprise and Developer Edition.', 16, 5 END ---------------------------------------------------------------------------------------------------- @@ -1197,25 +1197,25 @@ BEGIN IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN 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 + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.', 16, 3 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, [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 + 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, 4 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))) AND (SELECT COUNT(*) FROM (SELECT @FileExtensionFull AS FileExtension UNION SELECT @FileExtensionDiff UNION SELECT @FileExtensionLog) FileExtension) <> 3 BEGIN 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 and the file extensions are not unique.', 16, 6 + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory and the file extensions are not unique.', 16, 5 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, [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 + 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, 6 END ---------------------------------------------------------------------------------------------------- @@ -1836,7 +1836,7 @@ BEGIN 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 + SELECT 'The value for the parameter @URL is not supported.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -1844,19 +1844,19 @@ BEGIN 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 + SELECT 'The value for the parameter @Credential is not supported.', 16, 1 END IF @URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) IN('SHARED ACCESS SIGNATURE','MANAGED IDENTITY','S3 ACCESS KEY')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Credential is not supported.', 16, 3 + SELECT 'The value for the parameter @Credential is not supported.', 16, 2 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 + SELECT 'The value for the parameter @Credential is not supported.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -1898,13 +1898,13 @@ BEGIN 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 + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 3 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 + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 4 END ---------------------------------------------------------------------------------------------------- @@ -1934,19 +1934,19 @@ BEGIN IF @MinModificationLevel <= 0 OR @MinModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinModificationLevel is not supported.', 16, 2 + SELECT 'The value for the parameter @MinModificationLevel is not supported.', 16, 1 END IF @MinModificationLevel IS NOT NULL AND @ChangeBackupType = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 3 + SELECT 'The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 2 END IF @MinModificationLevel IS NOT NULL AND @BackupType <> 'DIFF' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @MinModificationLevel can only be used for differential backups.', 16, 4 + SELECT 'The parameter @MinModificationLevel can only be used for differential backups.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -1968,7 +1968,7 @@ BEGIN IF @MinLogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinLogSizeSinceLastLogBackup is not supported.', 16, 2 + SELECT 'The value for the parameter @MinLogSizeSinceLastLogBackup is not supported.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -1976,7 +1976,7 @@ BEGIN IF @MinTimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinTimeSinceLastLogBackup is not supported.', 16, 2 + SELECT 'The value for the parameter @MinTimeSinceLastLogBackup is not supported.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -2376,7 +2376,7 @@ BEGIN 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, 3 + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 2 END ---------------------------------------------------------------------------------------------------- diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index fe9e01d4..ac6e3ec5 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 11:58:45 //-- + --// Version: 2026-07-04 13:43:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -710,7 +710,7 @@ BEGIN 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 + 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')) diff --git a/IndexOptimize.sql b/IndexOptimize.sql index e9863cc3..6fe43495 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 11:58:45 //-- + --// Version: 2026-07-04 13:43:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -970,7 +970,7 @@ BEGIN IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 3 + SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 2 END ---------------------------------------------------------------------------------------------------- diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index d53f7930..21cbfa5d 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: 2026-07-04 11:58:45 +Version: 2026-07-04 13:43:07 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 11:58:45 //-- + --// Version: 2026-07-04 13:43:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 11:58:45 //-- + --// Version: 2026-07-04 13:43:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1289,25 +1289,25 @@ BEGIN 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 + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 2 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 + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 3 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 + SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 4 END IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) BEGIN 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 + SELECT 'The value for the parameter @MirrorDirectory is not supported. Mirrored backup to disk is only available in Enterprise and Developer Edition.', 16, 5 END ---------------------------------------------------------------------------------------------------- @@ -1596,25 +1596,25 @@ BEGIN IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN 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 + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.', 16, 3 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, [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 + 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, 4 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))) AND (SELECT COUNT(*) FROM (SELECT @FileExtensionFull AS FileExtension UNION SELECT @FileExtensionDiff UNION SELECT @FileExtensionLog) FileExtension) <> 3 BEGIN 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 and the file extensions are not unique.', 16, 6 + SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory and the file extensions are not unique.', 16, 5 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, [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 + 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, 6 END ---------------------------------------------------------------------------------------------------- @@ -2235,7 +2235,7 @@ BEGIN 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 + SELECT 'The value for the parameter @URL is not supported.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -2243,19 +2243,19 @@ BEGIN 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 + SELECT 'The value for the parameter @Credential is not supported.', 16, 1 END IF @URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) IN('SHARED ACCESS SIGNATURE','MANAGED IDENTITY','S3 ACCESS KEY')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Credential is not supported.', 16, 3 + SELECT 'The value for the parameter @Credential is not supported.', 16, 2 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 + SELECT 'The value for the parameter @Credential is not supported.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -2297,13 +2297,13 @@ BEGIN 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 + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 3 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 + SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 4 END ---------------------------------------------------------------------------------------------------- @@ -2333,19 +2333,19 @@ BEGIN IF @MinModificationLevel <= 0 OR @MinModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinModificationLevel is not supported.', 16, 2 + SELECT 'The value for the parameter @MinModificationLevel is not supported.', 16, 1 END IF @MinModificationLevel IS NOT NULL AND @ChangeBackupType = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 3 + SELECT 'The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 2 END IF @MinModificationLevel IS NOT NULL AND @BackupType <> 'DIFF' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @MinModificationLevel can only be used for differential backups.', 16, 4 + SELECT 'The parameter @MinModificationLevel can only be used for differential backups.', 16, 3 END ---------------------------------------------------------------------------------------------------- @@ -2367,7 +2367,7 @@ BEGIN IF @MinLogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinLogSizeSinceLastLogBackup is not supported.', 16, 2 + SELECT 'The value for the parameter @MinLogSizeSinceLastLogBackup is not supported.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -2375,7 +2375,7 @@ BEGIN IF @MinTimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinTimeSinceLastLogBackup is not supported.', 16, 2 + SELECT 'The value for the parameter @MinTimeSinceLastLogBackup is not supported.', 16, 1 END ---------------------------------------------------------------------------------------------------- @@ -2775,7 +2775,7 @@ BEGIN 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, 3 + SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 2 END ---------------------------------------------------------------------------------------------------- @@ -4831,7 +4831,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 11:58:45 //-- + --// Version: 2026-07-04 13:43:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5501,7 +5501,7 @@ BEGIN 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 + 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')) @@ -6793,7 +6793,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 11:58:45 //-- + --// Version: 2026-07-04 13:43:07 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7707,7 +7707,7 @@ BEGIN IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 3 + SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 2 END ---------------------------------------------------------------------------------------------------- From 31a759d398ed37d527a83b8f6d22547d881011ef Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 4 Jul 2026 14:17:02 +0200 Subject: [PATCH 063/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 3 ++- DatabaseIntegrityCheck.sql | 3 ++- IndexOptimize.sql | 7 +++++-- MaintenanceSolution.sql | 17 +++++++++++------ 5 files changed, 21 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 5b80f1fa..e5de4b2d 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-04 13:43:07 //-- + --// Version: 2026-07-04 14:16:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index bb07f338..56cd6229 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 13:43:07 //-- + --// Version: 2026-07-04 14:16:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4287,6 +4287,7 @@ BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + SET @ReturnCode = @Error RAISERROR(@EmptyLine,10,1) WITH NOWAIT END diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index ac6e3ec5..be565029 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 13:43:07 //-- + --// Version: 2026-07-04 14:16:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1870,6 +1870,7 @@ BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + SET @ReturnCode = @Error RAISERROR(@EmptyLine,10,1) WITH NOWAIT END diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 6fe43495..b1085444 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 13:43:07 //-- + --// Version: 2026-07-04 14:16:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1629,6 +1629,8 @@ BEGIN BEGIN SET @DatabaseMessage = 'The user ' + QUOTENAME(@ExecuteAsUser) + ' does not exist in the database ' + QUOTENAME(@CurrentDatabaseName) + '.' RAISERROR('%s',16,1,@DatabaseMessage) WITH NOWAIT + SET @Error = @@ERROR + SET @ReturnCode = @Error RAISERROR(@EmptyLine,10,1) WITH NOWAIT END @@ -2680,8 +2682,9 @@ BEGIN BEGIN 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 + SET @ReturnCode = @Error + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END -- Update that the database is completed diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 21cbfa5d..22161f05 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: 2026-07-04 13:43:07 +Version: 2026-07-04 14:16:17 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 13:43:07 //-- + --// Version: 2026-07-04 14:16:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 13:43:07 //-- + --// Version: 2026-07-04 14:16:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4686,6 +4686,7 @@ BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + SET @ReturnCode = @Error RAISERROR(@EmptyLine,10,1) WITH NOWAIT END @@ -4831,7 +4832,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 13:43:07 //-- + --// Version: 2026-07-04 14:16:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6661,6 +6662,7 @@ BEGIN SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT SET @Error = @@ERROR + SET @ReturnCode = @Error RAISERROR(@EmptyLine,10,1) WITH NOWAIT END @@ -6793,7 +6795,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 13:43:07 //-- + --// Version: 2026-07-04 14:16:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8366,6 +8368,8 @@ BEGIN BEGIN SET @DatabaseMessage = 'The user ' + QUOTENAME(@ExecuteAsUser) + ' does not exist in the database ' + QUOTENAME(@CurrentDatabaseName) + '.' RAISERROR('%s',16,1,@DatabaseMessage) WITH NOWAIT + SET @Error = @@ERROR + SET @ReturnCode = @Error RAISERROR(@EmptyLine,10,1) WITH NOWAIT END @@ -9417,8 +9421,9 @@ BEGIN BEGIN 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 + SET @ReturnCode = @Error + RAISERROR(@EmptyLine,10,1) WITH NOWAIT END -- Update that the database is completed From 76c8ef1284d6df37507a33cd419f0c5e23ec9a66 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 4 Jul 2026 14:39:53 +0200 Subject: [PATCH 064/177] Add files via upload --- CommandExecute.sql | 6 +++--- DatabaseBackup.sql | 4 ++-- DatabaseIntegrityCheck.sql | 4 +--- IndexOptimize.sql | 4 +--- MaintenanceSolution.sql | 20 ++++++++------------ 5 files changed, 15 insertions(+), 23 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index e5de4b2d..9b70283b 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-04 14:16:17 //-- + --// Version: 2026-07-04 14:39:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -226,9 +226,9 @@ BEGIN BEGIN INSERT INTO dbo.CommandLog (DatabaseName, SchemaName, ObjectName, ObjectType, IndexName, IndexType, StatisticsName, PartitionNumber, ExtendedInfo, CommandType, Command, StartTime) VALUES (@DatabaseName, @SchemaName, @ObjectName, @ObjectType, @IndexName, @IndexType, @StatisticsName, @PartitionNumber, @ExtendedInfo, @CommandType, @CommandMasked, @StartTime) - END - SET @ID = SCOPE_IDENTITY() + SET @ID = SCOPE_IDENTITY() + END ---------------------------------------------------------------------------------------------------- --// Execute command //-- diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 56cd6229..97d550fc 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 14:16:17 //-- + --// Version: 2026-07-04 14:39:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1407,7 +1407,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @BufferCount <= 0 OR @BufferCount > 2147483647 + IF @BufferCount <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @BufferCount is not supported.', 16, 1 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index be565029..e2df8a43 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 14:16:17 //-- + --// Version: 2026-07-04 14:39:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1587,7 +1587,6 @@ BEGIN BEGIN SET @ErrorMessage = 'The following file groups do not exist: ' + @ErrorMessage + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR RAISERROR(@EmptyLine,10,1) WITH NOWAIT END @@ -1755,7 +1754,6 @@ BEGIN BEGIN SET @ErrorMessage = 'The following objects do not exist: ' + @ErrorMessage + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR RAISERROR(@EmptyLine,10,1) WITH NOWAIT END diff --git a/IndexOptimize.sql b/IndexOptimize.sql index b1085444..b238df45 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 14:16:17 //-- + --// Version: 2026-07-04 14:39:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2038,7 +2038,6 @@ BEGIN BEGIN SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + @ErrorMessage + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR RAISERROR(@EmptyLine,10,1) WITH NOWAIT END @@ -2055,7 +2054,6 @@ BEGIN BEGIN SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + @ErrorMessage + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR RAISERROR(@EmptyLine,10,1) WITH NOWAIT END END diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 22161f05..c7569c41 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: 2026-07-04 14:16:17 +Version: 2026-07-04 14:39:16 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 14:16:17 //-- + --// Version: 2026-07-04 14:39:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -321,9 +321,9 @@ BEGIN BEGIN INSERT INTO dbo.CommandLog (DatabaseName, SchemaName, ObjectName, ObjectType, IndexName, IndexType, StatisticsName, PartitionNumber, ExtendedInfo, CommandType, Command, StartTime) VALUES (@DatabaseName, @SchemaName, @ObjectName, @ObjectType, @IndexName, @IndexType, @StatisticsName, @PartitionNumber, @ExtendedInfo, @CommandType, @CommandMasked, @StartTime) - END - SET @ID = SCOPE_IDENTITY() + SET @ID = SCOPE_IDENTITY() + END ---------------------------------------------------------------------------------------------------- --// Execute command //-- @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 14:16:17 //-- + --// Version: 2026-07-04 14:39:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1806,7 +1806,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @BufferCount <= 0 OR @BufferCount > 2147483647 + IF @BufferCount <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @BufferCount is not supported.', 16, 1 @@ -4832,7 +4832,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 14:16:17 //-- + --// Version: 2026-07-04 14:39:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6379,7 +6379,6 @@ BEGIN BEGIN SET @ErrorMessage = 'The following file groups do not exist: ' + @ErrorMessage + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR RAISERROR(@EmptyLine,10,1) WITH NOWAIT END @@ -6547,7 +6546,6 @@ BEGIN BEGIN SET @ErrorMessage = 'The following objects do not exist: ' + @ErrorMessage + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR RAISERROR(@EmptyLine,10,1) WITH NOWAIT END @@ -6795,7 +6793,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 14:16:17 //-- + --// Version: 2026-07-04 14:39:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8777,7 +8775,6 @@ BEGIN BEGIN SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + @ErrorMessage + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR RAISERROR(@EmptyLine,10,1) WITH NOWAIT END @@ -8794,7 +8791,6 @@ BEGIN BEGIN SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + @ErrorMessage + '.' RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT - SET @Error = @@ERROR RAISERROR(@EmptyLine,10,1) WITH NOWAIT END END From cff3163793c27bb445c24eff13b73331ca4798cc Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 4 Jul 2026 20:58:55 +0200 Subject: [PATCH 065/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 30 +++++++++---------- DatabaseIntegrityCheck.sql | 14 ++++----- IndexOptimize.sql | 12 ++++---- MaintenanceSolution.sql | 60 +++++++++++++++++++------------------- 5 files changed, 59 insertions(+), 59 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 9b70283b..86017283 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-04 14:39:16 //-- + --// Version: 2026-07-04 20:57:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 97d550fc..a31323c0 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 14:39:16 //-- + --// Version: 2026-07-04 20:57:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -870,7 +870,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 'Mirrored backup is not supported when backing up to NUL', 16, 6 + SELECT 'Mirrored backup is not supported when backing up to NUL.', 16, 6 END IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND @BackupSoftware IS NOT NULL @@ -1165,13 +1165,13 @@ BEGIN 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 + 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 + 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') @@ -1282,7 +1282,7 @@ BEGIN IF @CompressionAlgorithm IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm is only supported with SQL Server native backup', 16, 5 + SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm is only supported with SQL Server native backup.', 16, 5 END ---------------------------------------------------------------------------------------------------- @@ -1338,7 +1338,7 @@ BEGIN 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 + 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') @@ -1384,13 +1384,13 @@ BEGIN 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 + 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 + 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 @@ -1402,7 +1402,7 @@ BEGIN 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 + SELECT 'The value for the parameter @BlockSize is not supported. This parameter is not supported with Data Domain Boost.', 16, 5 END ---------------------------------------------------------------------------------------------------- @@ -2650,17 +2650,17 @@ BEGIN DatabaseName FROM @tmpDatabases tmpDatabases WHERE Selected = 1 - AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName = tmpDatabases.DatabaseName AND QueueID = @QueueID) + AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName COLLATE DATABASE_DEFAULT = 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) + AND NOT EXISTS (SELECT * FROM @tmpDatabases tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT AND Selected = 1) UPDATE QueueDatabase SET DatabaseOrder = tmpDatabases.[Order] FROM dbo.QueueDatabase QueueDatabase - INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT = tmpDatabases.DatabaseName WHERE QueueID = @QueueID END @@ -2713,7 +2713,7 @@ BEGIN 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) + @CurrentDatabaseNameFS = (SELECT DatabaseNameFS FROM @tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT) FROM (SELECT TOP 1 DatabaseStartTime, DatabaseEndTime, SessionID, @@ -2876,7 +2876,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentInStandby = 1) BEGIN - SELECT @CurrentLastLogBackup = log_backup_time, + SELECT @CurrentLastLogBackup = NULLIF(log_backup_time,'1900-01-01'), @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb FROM sys.dm_db_log_stats (DB_ID(@CurrentDatabaseName)) END @@ -3031,7 +3031,7 @@ BEGIN IF @CurrentBackupType = 'LOG' BEGIN - SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),NULLIF(@CurrentLastLogBackup,'1900-01-01'),120),'N/A') + SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),@CurrentLastLogBackup,120),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Log size since last log backup (MB): ' + ISNULL(CAST(@CurrentLogSizeSinceLastLogBackup AS nvarchar(max)),'N/A') diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index e2df8a43..db8ee91f 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 14:39:16 //-- + --// Version: 2026-07-04 20:57:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1265,17 +1265,17 @@ BEGIN DatabaseName FROM @tmpDatabases tmpDatabases WHERE Selected = 1 - AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName = tmpDatabases.DatabaseName AND QueueID = @QueueID) + AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName COLLATE DATABASE_DEFAULT = 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) + AND NOT EXISTS (SELECT * FROM @tmpDatabases tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT AND Selected = 1) UPDATE QueueDatabase SET DatabaseOrder = tmpDatabases.[Order] FROM dbo.QueueDatabase QueueDatabase - INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT = tmpDatabases.DatabaseName WHERE QueueID = @QueueID END @@ -1306,7 +1306,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- WHILE (1 = 1) - BEGIN + BEGIN -- Start of database loop IF @DatabasesInParallel = 'Y' BEGIN @@ -1353,7 +1353,7 @@ BEGIN IF @@ROWCOUNT = 0 BEGIN - BREAK + BREAK END SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' @@ -1921,7 +1921,7 @@ BEGIN DELETE FROM @tmpFileGroups DELETE FROM @tmpObjects - END + END -- End of database loop ---------------------------------------------------------------------------------------------------- --// Log completing information //-- diff --git a/IndexOptimize.sql b/IndexOptimize.sql index b238df45..df7669dd 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 14:39:16 //-- + --// Version: 2026-07-04 20:57:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1412,17 +1412,17 @@ BEGIN DatabaseName FROM @tmpDatabases tmpDatabases WHERE Selected = 1 - AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName = tmpDatabases.DatabaseName AND QueueID = @QueueID) + AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName COLLATE DATABASE_DEFAULT = 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) + AND NOT EXISTS (SELECT * FROM @tmpDatabases tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT AND Selected = 1) UPDATE QueueDatabase SET DatabaseOrder = tmpDatabases.[Order] FROM dbo.QueueDatabase QueueDatabase - INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT = tmpDatabases.DatabaseName WHERE QueueID = @QueueID END @@ -1453,7 +1453,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- WHILE (1 = 1) - BEGIN + BEGIN -- Start of database loop IF @DatabasesInParallel = 'Y' BEGIN @@ -2734,7 +2734,7 @@ BEGIN DELETE FROM @tmpIndexStatisticsProperties DELETE FROM @tmpResumableOperations - END + END -- End of database loop ---------------------------------------------------------------------------------------------------- --// Log completing information //-- diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index c7569c41..2a48b62b 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: 2026-07-04 14:39:16 +Version: 2026-07-04 20:57:51 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 14:39:16 //-- + --// Version: 2026-07-04 20:57:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 14:39:16 //-- + --// Version: 2026-07-04 20:57:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1269,7 +1269,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 'Mirrored backup is not supported when backing up to NUL', 16, 6 + SELECT 'Mirrored backup is not supported when backing up to NUL.', 16, 6 END IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND @BackupSoftware IS NOT NULL @@ -1564,13 +1564,13 @@ BEGIN 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 + 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 + 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') @@ -1681,7 +1681,7 @@ BEGIN IF @CompressionAlgorithm IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm is only supported with SQL Server native backup', 16, 5 + SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm is only supported with SQL Server native backup.', 16, 5 END ---------------------------------------------------------------------------------------------------- @@ -1737,7 +1737,7 @@ BEGIN 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 + 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') @@ -1783,13 +1783,13 @@ BEGIN 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 + 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 + 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 @@ -1801,7 +1801,7 @@ BEGIN 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 + SELECT 'The value for the parameter @BlockSize is not supported. This parameter is not supported with Data Domain Boost.', 16, 5 END ---------------------------------------------------------------------------------------------------- @@ -3049,17 +3049,17 @@ BEGIN DatabaseName FROM @tmpDatabases tmpDatabases WHERE Selected = 1 - AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName = tmpDatabases.DatabaseName AND QueueID = @QueueID) + AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName COLLATE DATABASE_DEFAULT = 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) + AND NOT EXISTS (SELECT * FROM @tmpDatabases tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT AND Selected = 1) UPDATE QueueDatabase SET DatabaseOrder = tmpDatabases.[Order] FROM dbo.QueueDatabase QueueDatabase - INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT = tmpDatabases.DatabaseName WHERE QueueID = @QueueID END @@ -3112,7 +3112,7 @@ BEGIN 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) + @CurrentDatabaseNameFS = (SELECT DatabaseNameFS FROM @tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT) FROM (SELECT TOP 1 DatabaseStartTime, DatabaseEndTime, SessionID, @@ -3275,7 +3275,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentInStandby = 1) BEGIN - SELECT @CurrentLastLogBackup = log_backup_time, + SELECT @CurrentLastLogBackup = NULLIF(log_backup_time,'1900-01-01'), @CurrentLogSizeSinceLastLogBackup = log_since_last_log_backup_mb FROM sys.dm_db_log_stats (DB_ID(@CurrentDatabaseName)) END @@ -3430,7 +3430,7 @@ BEGIN IF @CurrentBackupType = 'LOG' BEGIN - SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),NULLIF(@CurrentLastLogBackup,'1900-01-01'),120),'N/A') + SET @DatabaseMessage = 'Last log backup: ' + ISNULL(CONVERT(nvarchar(19),@CurrentLastLogBackup,120),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT SET @DatabaseMessage = 'Log size since last log backup (MB): ' + ISNULL(CAST(@CurrentLogSizeSinceLastLogBackup AS nvarchar(max)),'N/A') @@ -4832,7 +4832,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 14:39:16 //-- + --// Version: 2026-07-04 20:57:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6057,17 +6057,17 @@ BEGIN DatabaseName FROM @tmpDatabases tmpDatabases WHERE Selected = 1 - AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName = tmpDatabases.DatabaseName AND QueueID = @QueueID) + AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName COLLATE DATABASE_DEFAULT = 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) + AND NOT EXISTS (SELECT * FROM @tmpDatabases tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT AND Selected = 1) UPDATE QueueDatabase SET DatabaseOrder = tmpDatabases.[Order] FROM dbo.QueueDatabase QueueDatabase - INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT = tmpDatabases.DatabaseName WHERE QueueID = @QueueID END @@ -6098,7 +6098,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- WHILE (1 = 1) - BEGIN + BEGIN -- Start of database loop IF @DatabasesInParallel = 'Y' BEGIN @@ -6145,7 +6145,7 @@ BEGIN IF @@ROWCOUNT = 0 BEGIN - BREAK + BREAK END SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' @@ -6713,7 +6713,7 @@ BEGIN DELETE FROM @tmpFileGroups DELETE FROM @tmpObjects - END + END -- End of database loop ---------------------------------------------------------------------------------------------------- --// Log completing information //-- @@ -6793,7 +6793,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 14:39:16 //-- + --// Version: 2026-07-04 20:57:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8149,17 +8149,17 @@ BEGIN DatabaseName FROM @tmpDatabases tmpDatabases WHERE Selected = 1 - AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName = tmpDatabases.DatabaseName AND QueueID = @QueueID) + AND NOT EXISTS (SELECT * FROM dbo.QueueDatabase WHERE DatabaseName COLLATE DATABASE_DEFAULT = 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) + AND NOT EXISTS (SELECT * FROM @tmpDatabases tmpDatabases WHERE DatabaseName = QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT AND Selected = 1) UPDATE QueueDatabase SET DatabaseOrder = tmpDatabases.[Order] FROM dbo.QueueDatabase QueueDatabase - INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName = tmpDatabases.DatabaseName + INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT = tmpDatabases.DatabaseName WHERE QueueID = @QueueID END @@ -8190,7 +8190,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- WHILE (1 = 1) - BEGIN + BEGIN -- Start of database loop IF @DatabasesInParallel = 'Y' BEGIN @@ -9471,7 +9471,7 @@ BEGIN DELETE FROM @tmpIndexStatisticsProperties DELETE FROM @tmpResumableOperations - END + END -- End of database loop ---------------------------------------------------------------------------------------------------- --// Log completing information //-- From c1c6ebcac35976a5e8b479c14f1d2c6cf586f9f9 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 7 Jul 2026 20:45:19 +0200 Subject: [PATCH 066/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 9 ++++++++- MaintenanceSolution.sql | 17 ++++++++++++----- 5 files changed, 23 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 86017283..ee9c6785 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-04 20:57:51 //-- + --// Version: 2026-07-07 20:44:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index a31323c0..379bb9b5 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 20:57:51 //-- + --// Version: 2026-07-07 20:44:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index db8ee91f..7ffddeff 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 20:57:51 //-- + --// Version: 2026-07-07 20:44:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index df7669dd..fb2d40aa 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 20:57:51 //-- + --// Version: 2026-07-07 20:44:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1684,12 +1684,19 @@ BEGIN BEGIN SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' END + + IF @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) + BEGIN + SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.partition_id = dm_db_partition_stats.partition_id' + END SET @CurrentCommand += ' WHERE objects.[type] = ''U''' + ' AND tables.is_external = 0' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,5,6,7)' + ' AND indexes.is_disabled = 0' + ' AND indexes.is_hypothetical = 0' + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= ' + CAST(@MinNumberOfPages AS nvarchar(max)) ELSE '' END + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= ' + CAST(@MaxNumberOfPages AS nvarchar(max)) ELSE '' END INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation, PartitionID, PartitionNumber) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 2a48b62b..c3183b8f 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: 2026-07-04 20:57:51 +Version: 2026-07-07 20:44:09 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 20:57:51 //-- + --// Version: 2026-07-07 20:44:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 20:57:51 //-- + --// Version: 2026-07-07 20:44:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4832,7 +4832,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 20:57:51 //-- + --// Version: 2026-07-07 20:44:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6793,7 +6793,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-04 20:57:51 //-- + --// Version: 2026-07-07 20:44:09 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8421,12 +8421,19 @@ BEGIN BEGIN SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' END + + IF @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) + BEGIN + SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.partition_id = dm_db_partition_stats.partition_id' + END SET @CurrentCommand += ' WHERE objects.[type] = ''U''' + ' AND tables.is_external = 0' + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + ' AND indexes.[type] IN(1,2,5,6,7)' + ' AND indexes.is_disabled = 0' + ' AND indexes.is_hypothetical = 0' + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= ' + CAST(@MinNumberOfPages AS nvarchar(max)) ELSE '' END + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= ' + CAST(@MaxNumberOfPages AS nvarchar(max)) ELSE '' END INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation, PartitionID, PartitionNumber) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand From 5b153681603b5a56dbb075e5f0558c57f6571b05 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 11 Jul 2026 19:18:30 +0200 Subject: [PATCH 067/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 130 ++++++++++-------- DatabaseIntegrityCheck.sql | 66 ++++++---- IndexOptimize.sql | 63 +++++---- MaintenanceSolution.sql | 263 ++++++++++++++++++++----------------- 5 files changed, 291 insertions(+), 233 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index ee9c6785..149f2073 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-07 20:44:09 //-- + --// Version: 2026-07-11 19:11:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 379bb9b5..bb85e1e5 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -93,7 +93,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-07 20:44:09 //-- + --// Version: 2026-07-11 19:11:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -279,20 +279,34 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) - DECLARE @Version numeric(18,10) = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4) + '.' + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),2) AS numeric(18,10)) + DECLARE @ProductVersion nvarchar(max) = CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + DECLARE @ProductMajorVersion nvarchar(max) = CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar(max)) + DECLARE @ProductMinorVersion nvarchar(max) = CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar(max)) + DECLARE @ProductUpdateType nvarchar(max) = CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + DECLARE @EngineEdition int = CAST(SERVERPROPERTY('EngineEdition') AS int) + DECLARE @EditionID bigint = CAST(SERVERPROPERTY('EditionID') AS bigint) + DECLARE @Edition nvarchar(max) = CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + DECLARE @IsHadrEnabled bit = CAST(SERVERPROPERTY('IsHadrEnabled') AS bit) + DECLARE @IsClustered bit = CAST(SERVERPROPERTY('IsClustered') AS bit) + DECLARE @ServerName nvarchar(max) = CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + DECLARE @InstanceName nvarchar(max) = CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max)) + DECLARE @MachineName nvarchar(max) = CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)) + DECLARE @InstanceDefaultBackupPath nvarchar(max) = CAST(SERVERPROPERTY('InstanceDefaultBackupPath') AS nvarchar(max)) - IF SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' + DECLARE @Version numeric(18,10) = CAST(PARSENAME(@ProductVersion,4) + '.' + PARSENAME(@ProductVersion,3) + PARSENAME(@ProductVersion,2) AS numeric(18,10)) + + IF @EngineEdition = 8 AND @ProductVersion = '12.0.2000.8' AND @ProductUpdateType = 'CU' BEGIN SET @Version = 16.01000 END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SELECT @HostPlatform = host_platform FROM sys.dm_os_host_info END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) @@ -301,7 +315,7 @@ BEGIN END END - DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- @@ -386,28 +400,28 @@ BEGIN SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + SET @StartMessage = 'Server: ' + @ServerName RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + SET @StartMessage = 'Version: ' + @ProductVersion RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + SET @StartMessage = 'Edition: ' + @Edition RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - IF SERVERPROPERTY('EngineEdition') = 8 + IF @EngineEdition = 8 BEGIN - SET @StartMessage = 'Update type: ' + CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + SET @StartMessage = 'Update type: ' + @ProductUpdateType RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -544,7 +558,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF SERVERPROPERTY('IsHadrEnabled') = 1 + IF @IsHadrEnabled = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName) SELECT name AS AvailabilityGroupName @@ -613,7 +627,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -698,7 +712,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 SERVERPROPERTY('IsHadrEnabled') = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @IsHadrEnabled = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 @@ -751,9 +765,9 @@ BEGIN IF @Directory IS NULL AND @URL IS NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN - IF @Version >= 15 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous') + IF @Version >= 15 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous') BEGIN - SET @DefaultDirectory = CAST(SERVERPROPERTY('InstanceDefaultBackupPath') AS nvarchar(max)) + SET @DefaultDirectory = @InstanceDefaultBackupPath END ELSE BEGIN @@ -855,7 +869,7 @@ BEGIN 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') + IF (@Directory IS NOT NULL AND @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 @@ -893,7 +907,7 @@ BEGIN SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 2 END - IF @MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8 + IF @MirrorDirectory IS NOT NULL AND @EngineEdition = 8 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 3 @@ -905,7 +919,7 @@ BEGIN SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 4 END - IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) + IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND @EngineEdition <> 3) BEGIN 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, 5 @@ -1120,7 +1134,7 @@ BEGIN --// Get default compression algorithm //-- ---------------------------------------------------------------------------------------------------- - IF @CompressionAlgorithm IS NULL AND @BackupSoftware IS NULL AND (@Version >= 16 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @CompressionAlgorithm IS NULL AND @BackupSoftware IS NULL AND (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN SELECT @CompressionAlgorithm = CASE WHEN @BackupSoftware IS NULL AND EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression algorithm' AND value_in_use IN (0, 1)) THEN 'MS_XPRESS' WHEN @BackupSoftware IS NULL AND EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression algorithm' AND value_in_use = 2) THEN 'QAT_DEFLATE' @@ -1131,7 +1145,7 @@ BEGIN --// Get default compression level //-- ---------------------------------------------------------------------------------------------------- - IF @CompressionLevel IS NULL AND @BackupSoftware IS NULL AND (@Version >= 17 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @CompressionLevel IS NULL AND @BackupSoftware IS NULL AND (@Version >= 17 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN SET @CompressionLevel = 'LOW' END @@ -1148,7 +1162,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF SERVERPROPERTY('EngineEdition') = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') + IF @EngineEdition = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.', 16, 1 @@ -1200,19 +1214,19 @@ BEGIN SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.', 16, 3 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))) + IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN 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, 4 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))) AND (SELECT COUNT(*) FROM (SELECT @FileExtensionFull AS FileExtension UNION SELECT @FileExtensionDiff UNION SELECT @FileExtensionLog) FileExtension) <> 3 + IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) AND (SELECT COUNT(*) FROM (SELECT @FileExtensionFull AS FileExtension UNION SELECT @FileExtensionDiff UNION SELECT @FileExtensionLog) FileExtension) <> 3 BEGIN 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 and the file extensions are not unique.', 16, 5 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))) + IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN 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, 6 @@ -1235,7 +1249,7 @@ BEGIN END IF @Compress = 'Y' AND @BackupSoftware IS NULL - AND NOT (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, -1785266663)) + AND NOT (@EngineEdition IN (3, 8) OR @EditionID IN (-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @Compress is not supported. Backup compression is not supported in this edition of SQL Server.', 16, 2 @@ -1261,19 +1275,19 @@ BEGIN SELECT 'The value for the parameter @CompressionAlgorithm is not supported. The allowed values are MS_XPRESS, QAT_DEFLATE and ZSTD.', 16, 1 END - IF @CompressionAlgorithm IS NOT NULL AND NOT (@Version >= 16 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @CompressionAlgorithm IS NOT NULL AND NOT (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Specifying the compression algorithm is only supported in SQL Server 2022 and later.', 16, 2 END - IF @CompressionAlgorithm = 'QAT_DEFLATE' AND NOT (SERVERPROPERTY('EngineEdition') IN(2, 3)) + IF @CompressionAlgorithm = 'QAT_DEFLATE' AND NOT (@EngineEdition IN(2, 3)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to QAT_DEFLATE is only supported in Standard and Enterprise Edition.', 16, 3 END - IF @CompressionAlgorithm = 'ZSTD' AND NOT (@Version >= 17 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @CompressionAlgorithm = 'ZSTD' AND NOT (@Version >= 17 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to ZSTD is only supported in SQL Server 2025 and later.', 16, 4 @@ -1299,7 +1313,7 @@ BEGIN SELECT 'The value for the parameter @CompressionLevel is not supported. The supported values are LOW, MEDIUM and HIGH.', 16, 2 END - IF @CompressionLevel IS NOT NULL AND NOT (@Version >= 17 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @CompressionLevel IS NOT NULL AND NOT (@Version >= 17 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @CompressionLevel is not supported. Setting the compression level is only supported in SQL Server 2025 and later.', 16, 3 @@ -1655,7 +1669,7 @@ BEGIN SELECT 'The value for the parameter @Encrypt is not supported.', 16, 1 END - IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (SERVERPROPERTY('EngineEdition') IN(3, 8) OR SERVERPROPERTY('EditionID') IN(-1534726760, -1785266663)) + IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@EngineEdition IN(3, 8) OR @EditionID IN(-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @Encrypt is not supported.', 16, 2 @@ -2115,7 +2129,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) + IF (@IsHadrEnabled = 1 AND @AvailabilityGroupFileName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 1 @@ -2373,7 +2387,7 @@ BEGIN SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 END - IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 + IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 2 @@ -2387,7 +2401,7 @@ BEGIN SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 END - IF @DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5 + IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 2 @@ -2449,10 +2463,10 @@ BEGIN --// Check @@SERVERNAME //-- ---------------------------------------------------------------------------------------------------- - IF UPPER(@@SERVERNAME) <> UPPER(CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF UPPER(@@SERVERNAME) <> UPPER(@ServerName) AND @IsHadrEnabled = 1 BEGIN 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 + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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 ---------------------------------------------------------------------------------------------------- @@ -2487,7 +2501,7 @@ BEGIN --// Check Availability Group cluster name //-- ---------------------------------------------------------------------------------------------------- - IF SERVERPROPERTY('IsHadrEnabled') = 1 + IF @IsHadrEnabled = 1 BEGIN SELECT @Cluster = NULLIF(cluster_name,'') FROM sys.dm_hadr_cluster @@ -2785,10 +2799,10 @@ 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 < 15.04043 AND NOT (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) AND @Credential IS NULL THEN 65537 + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version < 15.04043 AND NOT (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND @Credential IS NULL THEN 65537 END - IF SERVERPROPERTY('IsHadrEnabled') = 1 + IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id FROM sys.databases databases @@ -2815,12 +2829,12 @@ BEGIN WHERE group_id = @CurrentAvailabilityGroupID END - IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + IF @IsHadrEnabled = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) END - IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + IF @IsHadrEnabled = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id @@ -2944,7 +2958,7 @@ BEGIN OR (@CurrentBackupType = 'DIFF' AND @CopyOnly = 'N' AND @Version >= 17) OR (@CurrentBackupType = 'FULL' AND @CopyOnly = 'Y') OR (@CurrentBackupType = 'LOG' AND @CopyOnly = 'N')) - AND SERVERPROPERTY('EngineEdition') = 3 + AND @EngineEdition = 3 BEGIN SET @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 END @@ -3093,7 +3107,7 @@ BEGIN 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}','') + IF @InstanceName IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}','') IF @@SERVICENAME IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}','') IF @Description IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}','') IF @BackupSetName IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@BackupSetName,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupSetName}','') @@ -3244,8 +3258,8 @@ BEGIN -- Directory structure - replace tokens with real values SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}',@DirectorySeparator) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}',CASE WHEN SERVERPROPERTY('EngineEdition') = 8 AND CHARINDEX('.',CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) > 0 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,'{ServerName}',CASE WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) > 0 THEN LEFT(@ServerName,CHARINDEX('.',@ServerName) - 1) ELSE @MachineName END) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}',ISNULL(@InstanceName,'')) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}',ISNULL(@@SERVICENAME,'')) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}',ISNULL(@Cluster,'')) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}',ISNULL(@CurrentAvailabilityGroup,'')) @@ -3265,8 +3279,8 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),3)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),6)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4))) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3))) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MajorVersion}',@ProductMajorVersion) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MinorVersion}',@ProductMinorVersion) END IF @DirectoryStructureCase IS NOT NULL @@ -3303,7 +3317,7 @@ BEGIN 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 @InstanceName IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}','') IF @@SERVICENAME IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}','') IF @Description IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}','') IF @BackupSetName IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@BackupSetName,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{BackupSetName}','') @@ -3409,8 +3423,8 @@ BEGIN END -- File name - replace tokens with real values - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServerName}',CASE WHEN SERVERPROPERTY('EngineEdition') = 8 AND CHARINDEX('.',CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) > 0 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,'{ServerName}',CASE WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) > 0 THEN LEFT(@ServerName,CHARINDEX('.',@ServerName) - 1) ELSE @MachineName END) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}',ISNULL(@InstanceName,'')) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}',ISNULL(@@SERVICENAME,'')) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}',ISNULL(@Cluster,'')) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{AvailabilityGroupName}',ISNULL(@CurrentAvailabilityGroup,'')) @@ -3431,8 +3445,8 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),6)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',CAST(@CurrentNumberOfFiles AS nvarchar(max))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4))) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3))) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',@ProductMajorVersion) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MinorVersion}',@ProductMinorVersion) SELECT @CurrentMaxFilePathLength = CASE WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) @@ -3799,7 +3813,7 @@ BEGIN IF @Checksum = 'Y' SET @CurrentCommand += 'CHECKSUM' IF @Checksum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' - SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND (@CurrentMaxTransferSize >= 65537 OR (@Version >= 15.04043 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))))) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END + SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND (@CurrentMaxTransferSize >= 65537 OR (@Version >= 15.04043 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))))) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END IF @Compress = 'Y' AND @CompressionAlgorithm IS NOT NULL BEGIN @@ -4002,7 +4016,7 @@ BEGIN IF @DataDomainBoostNoOutputTable = 'Y' SET @CurrentCommand += 'INSERT INTO @DataDomainBoostOutput ([Message]) ' SET @CurrentCommand += 'EXECUTE @ReturnCode = dbo.emc_run_backup ''' - SET @CurrentCommand += ' -c ' + CASE WHEN @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL THEN REPLACE(@Cluster,'''','''''') ELSE REPLACE(CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)),'''','''''') END + SET @CurrentCommand += ' -c ' + CASE WHEN @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL THEN REPLACE(@Cluster,'''','''''') ELSE REPLACE(@MachineName,'''','''''') END SET @CurrentCommand += ' -l ' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'full' @@ -4033,8 +4047,8 @@ BEGIN IF @CopyOnly = 'Y' SET @CurrentCommand += ' -a "NSR_COPY_ONLY=TRUE"' IF @BackupSetName IS NOT NULL SET @CurrentCommand += ' -N "' + REPLACE(@BackupSetName,'''','''''') + '"' - IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand += ' "MSSQL' - IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand += ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max)) + IF @InstanceName IS NULL SET @CurrentCommand += ' "MSSQL' + IF @InstanceName IS NOT NULL SET @CurrentCommand += ' "MSSQL$' + @InstanceName SET @CurrentCommand += ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' SET @CurrentCommand += '''' diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 7ffddeff..c4a66c70 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-07 20:44:09 //-- + --// Version: 2026-07-11 19:11:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -184,20 +184,28 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) - DECLARE @Version numeric(18,10) = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4) + '.' + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),2) AS numeric(18,10)) + DECLARE @ProductVersion nvarchar(max) = CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + DECLARE @ProductUpdateType nvarchar(max) = CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + DECLARE @EngineEdition int = CAST(SERVERPROPERTY('EngineEdition') AS int) + DECLARE @Edition nvarchar(max) = CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + DECLARE @IsHadrEnabled bit = CAST(SERVERPROPERTY('IsHadrEnabled') AS bit) + DECLARE @IsClustered bit = CAST(SERVERPROPERTY('IsClustered') AS bit) + DECLARE @ServerName nvarchar(max) = CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) - IF SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' + DECLARE @Version numeric(18,10) = CAST(PARSENAME(@ProductVersion,4) + '.' + PARSENAME(@ProductVersion,3) + PARSENAME(@ProductVersion,2) AS numeric(18,10)) + + IF @EngineEdition = 8 AND @ProductVersion = '12.0.2000.8' AND @ProductUpdateType = 'CU' BEGIN SET @Version = 16.01000 END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SELECT @HostPlatform = host_platform FROM sys.dm_os_host_info END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) @@ -206,7 +214,7 @@ BEGIN END END - DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- @@ -238,28 +246,28 @@ BEGIN SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + SET @StartMessage = 'Server: ' + @ServerName RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + SET @StartMessage = 'Version: ' + @ProductVersion RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + SET @StartMessage = 'Edition: ' + @Edition RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - IF SERVERPROPERTY('EngineEdition') = 8 + IF @EngineEdition = 8 BEGIN - SET @StartMessage = 'Update type: ' + CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + SET @StartMessage = 'Update type: ' + @ProductUpdateType RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -390,7 +398,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF SERVERPROPERTY('IsHadrEnabled') = 1 + IF @IsHadrEnabled = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName) SELECT name AS AvailabilityGroupName @@ -459,7 +467,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -544,7 +552,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 SERVERPROPERTY('IsHadrEnabled') = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @IsHadrEnabled = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 @@ -895,7 +903,7 @@ BEGIN 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 >= 14.03029 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 14.03029 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) 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 @@ -913,7 +921,7 @@ BEGIN 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 + IF @DatabaseOrder IS NOT NULL AND @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 @@ -927,7 +935,7 @@ BEGIN SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 END - IF @DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5 + IF @DatabasesInParallel = 'Y' AND @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 @@ -1039,10 +1047,10 @@ BEGIN --// Check @@SERVERNAME //-- ---------------------------------------------------------------------------------------------------- - IF UPPER(@@SERVERNAME) <> UPPER(CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF UPPER(@@SERVERNAME) <> UPPER(@ServerName) AND @IsHadrEnabled = 1 BEGIN 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 + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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 ---------------------------------------------------------------------------------------------------- @@ -1391,7 +1399,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - IF SERVERPROPERTY('IsHadrEnabled') = 1 + IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id FROM sys.databases databases @@ -1413,12 +1421,12 @@ BEGIN WHERE group_id = @CurrentAvailabilityGroupID END - IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL AND @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' + IF @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('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + IF @IsHadrEnabled = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id @@ -1433,7 +1441,7 @@ BEGIN WHERE dm_hadr_availability_replica_states.replica_id = @CurrentDistributedAvailabilityGroupReplicaID END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring database_mirroring @@ -1490,7 +1498,7 @@ BEGIN IF @CurrentDatabaseState IN('ONLINE','EMERGENCY') AND NOT (@CurrentUserAccess = 'SINGLE_USER') - AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR SERVERPROPERTY('EngineEdition') = 3) + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR @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') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') @@ -1500,7 +1508,7 @@ BEGIN -- Check database IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKDB') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentDatabaseContext = CASE WHEN SERVERPROPERTY('EngineEdition') = 5 THEN @CurrentDatabaseName ELSE 'master' END + SET @CurrentDatabaseContext = CASE WHEN @EngineEdition = 5 THEN @CurrentDatabaseName ELSE 'master' END SET @CurrentCommandType = 'DBCC_CHECKDB' @@ -1670,7 +1678,7 @@ BEGIN -- 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 @CurrentDatabaseContext = CASE WHEN SERVERPROPERTY('EngineEdition') = 5 THEN @CurrentDatabaseName ELSE 'master' END + SET @CurrentDatabaseContext = CASE WHEN @EngineEdition = 5 THEN @CurrentDatabaseName ELSE 'master' END SET @CurrentCommandType = 'DBCC_CHECKALLOC' @@ -1845,7 +1853,7 @@ BEGIN -- Check catalog IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentDatabaseContext = CASE WHEN SERVERPROPERTY('EngineEdition') = 5 THEN @CurrentDatabaseName ELSE 'master' END + SET @CurrentDatabaseContext = CASE WHEN @EngineEdition = 5 THEN @CurrentDatabaseName ELSE 'master' END SET @CurrentCommandType = 'DBCC_CHECKCATALOG' diff --git a/IndexOptimize.sql b/IndexOptimize.sql index fb2d40aa..506d88fa 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-07 20:44:09 //-- + --// Version: 2026-07-11 19:11:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -291,20 +291,27 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) - DECLARE @Version numeric(18,10) = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4) + '.' + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),2) AS numeric(18,10)) + DECLARE @ProductVersion nvarchar(max) = CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + DECLARE @ProductUpdateType nvarchar(max) = CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + DECLARE @EngineEdition int = CAST(SERVERPROPERTY('EngineEdition') AS int) + DECLARE @Edition nvarchar(max) = CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + DECLARE @IsHadrEnabled bit = CAST(SERVERPROPERTY('IsHadrEnabled') AS bit) + DECLARE @ServerName nvarchar(max) = CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) - IF SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' + DECLARE @Version numeric(18,10) = CAST(PARSENAME(@ProductVersion,4) + '.' + PARSENAME(@ProductVersion,3) + PARSENAME(@ProductVersion,2) AS numeric(18,10)) + + IF @EngineEdition = 8 AND @ProductVersion = '12.0.2000.8' AND @ProductUpdateType = 'CU' BEGIN SET @Version = 16.01000 END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SELECT @HostPlatform = host_platform FROM sys.dm_os_host_info END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) @@ -313,7 +320,7 @@ BEGIN END END - DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- @@ -360,28 +367,28 @@ BEGIN SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + SET @StartMessage = 'Server: ' + @ServerName RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + SET @StartMessage = 'Version: ' + @ProductVersion RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + SET @StartMessage = 'Edition: ' + @Edition RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - IF SERVERPROPERTY('EngineEdition') = 8 + IF @EngineEdition = 8 BEGIN - SET @StartMessage = 'Update type: ' + CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + SET @StartMessage = 'Update type: ' + @ProductUpdateType RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -512,7 +519,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF SERVERPROPERTY('IsHadrEnabled') = 1 + IF @IsHadrEnabled = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName) SELECT name AS AvailabilityGroupName @@ -580,7 +587,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -665,7 +672,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 SERVERPROPERTY('IsHadrEnabled') = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @IsHadrEnabled = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 @@ -1041,7 +1048,7 @@ BEGIN SELECT 'The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3 END - IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.03006 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.03006 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 4 @@ -1151,7 +1158,7 @@ BEGIN SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 END - IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 + IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 2 @@ -1165,7 +1172,7 @@ BEGIN SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 END - IF @DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5 + IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 2 @@ -1538,7 +1545,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - IF SERVERPROPERTY('IsHadrEnabled') = 1 + IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id FROM sys.databases databases @@ -1558,7 +1565,7 @@ BEGIN WHERE group_id = @CurrentAvailabilityGroupID END - IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + IF @IsHadrEnabled = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id @@ -1573,7 +1580,7 @@ BEGIN WHERE dm_hadr_availability_replica_states.replica_id = @CurrentDistributedAvailabilityGroupReplicaID END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring database_mirroring @@ -1813,7 +1820,7 @@ BEGIN + ', 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] = indexes.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] = indexes.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] = indexes.[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] = indexes.object_id AND columns.is_filestream = 1) THEN 1 ELSE 0 END AS IsFileStream' - + ', ' + CASE WHEN (@Version >= 16 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' + + ', ' + CASE WHEN (@Version >= 16 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' + ', 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 OR index_columns.is_included_column = 1) 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.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND types.[name] = ''timestamp'') THEN 1 ELSE 0 END AS IsTimestamp' + ' FROM sys.indexes indexes' @@ -2201,16 +2208,16 @@ BEGIN INSERT INTO @CurrentActionsAllowed ([Action]) VALUES ('INDEX_REBUILD_OFFLINE') END - IF SERVERPROPERTY('EngineEdition') IN (3, 5, 8) + IF @EngineEdition IN (3, 5, 8) AND NOT (@CurrentOnReadOnlyFileGroup = 1) AND NOT (@CurrentIsMemoryOptimized = 1) AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1) AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1) AND NOT (@CurrentIndexType = 3) AND NOT (@CurrentIndexType = 4) - AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) - AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) - AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND NOT (@Version >= 17 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) BEGIN INSERT INTO @CurrentActionsAllowed ([Action]) VALUES ('INDEX_REBUILD_ONLINE') @@ -2553,7 +2560,7 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) - IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max)) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index c3183b8f..6919f63f 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: 2026-07-07 20:44:09 +Version: 2026-07-11 19:11:40 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-07 20:44:09 //-- + --// Version: 2026-07-11 19:11:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -492,7 +492,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-07 20:44:09 //-- + --// Version: 2026-07-11 19:11:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -678,20 +678,34 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) - DECLARE @Version numeric(18,10) = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4) + '.' + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),2) AS numeric(18,10)) + DECLARE @ProductVersion nvarchar(max) = CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + DECLARE @ProductMajorVersion nvarchar(max) = CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar(max)) + DECLARE @ProductMinorVersion nvarchar(max) = CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar(max)) + DECLARE @ProductUpdateType nvarchar(max) = CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + DECLARE @EngineEdition int = CAST(SERVERPROPERTY('EngineEdition') AS int) + DECLARE @EditionID bigint = CAST(SERVERPROPERTY('EditionID') AS bigint) + DECLARE @Edition nvarchar(max) = CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + DECLARE @IsHadrEnabled bit = CAST(SERVERPROPERTY('IsHadrEnabled') AS bit) + DECLARE @IsClustered bit = CAST(SERVERPROPERTY('IsClustered') AS bit) + DECLARE @ServerName nvarchar(max) = CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + DECLARE @InstanceName nvarchar(max) = CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max)) + DECLARE @MachineName nvarchar(max) = CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)) + DECLARE @InstanceDefaultBackupPath nvarchar(max) = CAST(SERVERPROPERTY('InstanceDefaultBackupPath') AS nvarchar(max)) - IF SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' + DECLARE @Version numeric(18,10) = CAST(PARSENAME(@ProductVersion,4) + '.' + PARSENAME(@ProductVersion,3) + PARSENAME(@ProductVersion,2) AS numeric(18,10)) + + IF @EngineEdition = 8 AND @ProductVersion = '12.0.2000.8' AND @ProductUpdateType = 'CU' BEGIN SET @Version = 16.01000 END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SELECT @HostPlatform = host_platform FROM sys.dm_os_host_info END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) @@ -700,7 +714,7 @@ BEGIN END END - DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- @@ -785,28 +799,28 @@ BEGIN SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + SET @StartMessage = 'Server: ' + @ServerName RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + SET @StartMessage = 'Version: ' + @ProductVersion RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + SET @StartMessage = 'Edition: ' + @Edition RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - IF SERVERPROPERTY('EngineEdition') = 8 + IF @EngineEdition = 8 BEGIN - SET @StartMessage = 'Update type: ' + CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + SET @StartMessage = 'Update type: ' + @ProductUpdateType RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -943,7 +957,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF SERVERPROPERTY('IsHadrEnabled') = 1 + IF @IsHadrEnabled = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName) SELECT name AS AvailabilityGroupName @@ -1012,7 +1026,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -1097,7 +1111,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 SERVERPROPERTY('IsHadrEnabled') = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @IsHadrEnabled = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 @@ -1150,9 +1164,9 @@ BEGIN IF @Directory IS NULL AND @URL IS NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN - IF @Version >= 15 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous') + IF @Version >= 15 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous') BEGIN - SET @DefaultDirectory = CAST(SERVERPROPERTY('InstanceDefaultBackupPath') AS nvarchar(max)) + SET @DefaultDirectory = @InstanceDefaultBackupPath END ELSE BEGIN @@ -1254,7 +1268,7 @@ BEGIN 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') + IF (@Directory IS NOT NULL AND @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 @@ -1292,7 +1306,7 @@ BEGIN SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 2 END - IF @MirrorDirectory IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 8 + IF @MirrorDirectory IS NOT NULL AND @EngineEdition = 8 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 3 @@ -1304,7 +1318,7 @@ BEGIN SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 4 END - IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND SERVERPROPERTY('EngineEdition') <> 3) + IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND @EngineEdition <> 3) BEGIN 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, 5 @@ -1519,7 +1533,7 @@ BEGIN --// Get default compression algorithm //-- ---------------------------------------------------------------------------------------------------- - IF @CompressionAlgorithm IS NULL AND @BackupSoftware IS NULL AND (@Version >= 16 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @CompressionAlgorithm IS NULL AND @BackupSoftware IS NULL AND (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN SELECT @CompressionAlgorithm = CASE WHEN @BackupSoftware IS NULL AND EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression algorithm' AND value_in_use IN (0, 1)) THEN 'MS_XPRESS' WHEN @BackupSoftware IS NULL AND EXISTS(SELECT * FROM sys.configurations WHERE name = 'backup compression algorithm' AND value_in_use = 2) THEN 'QAT_DEFLATE' @@ -1530,7 +1544,7 @@ BEGIN --// Get default compression level //-- ---------------------------------------------------------------------------------------------------- - IF @CompressionLevel IS NULL AND @BackupSoftware IS NULL AND (@Version >= 17 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @CompressionLevel IS NULL AND @BackupSoftware IS NULL AND (@Version >= 17 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN SET @CompressionLevel = 'LOW' END @@ -1547,7 +1561,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF SERVERPROPERTY('EngineEdition') = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') + IF @EngineEdition = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.', 16, 1 @@ -1599,19 +1613,19 @@ BEGIN SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.', 16, 3 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))) + IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN 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, 4 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))) AND (SELECT COUNT(*) FROM (SELECT @FileExtensionFull AS FileExtension UNION SELECT @FileExtensionDiff UNION SELECT @FileExtensionLog) FileExtension) <> 3 + IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) AND (SELECT COUNT(*) FROM (SELECT @FileExtensionFull AS FileExtension UNION SELECT @FileExtensionDiff UNION SELECT @FileExtensionLog) FileExtension) <> 3 BEGIN 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 and the file extensions are not unique.', 16, 5 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))) + IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN 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, 6 @@ -1634,7 +1648,7 @@ BEGIN END IF @Compress = 'Y' AND @BackupSoftware IS NULL - AND NOT (SERVERPROPERTY('EngineEdition') IN (3, 8) OR SERVERPROPERTY('EditionID') IN (-1534726760, -1785266663)) + AND NOT (@EngineEdition IN (3, 8) OR @EditionID IN (-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @Compress is not supported. Backup compression is not supported in this edition of SQL Server.', 16, 2 @@ -1660,19 +1674,19 @@ BEGIN SELECT 'The value for the parameter @CompressionAlgorithm is not supported. The allowed values are MS_XPRESS, QAT_DEFLATE and ZSTD.', 16, 1 END - IF @CompressionAlgorithm IS NOT NULL AND NOT (@Version >= 16 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @CompressionAlgorithm IS NOT NULL AND NOT (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Specifying the compression algorithm is only supported in SQL Server 2022 and later.', 16, 2 END - IF @CompressionAlgorithm = 'QAT_DEFLATE' AND NOT (SERVERPROPERTY('EngineEdition') IN(2, 3)) + IF @CompressionAlgorithm = 'QAT_DEFLATE' AND NOT (@EngineEdition IN(2, 3)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to QAT_DEFLATE is only supported in Standard and Enterprise Edition.', 16, 3 END - IF @CompressionAlgorithm = 'ZSTD' AND NOT (@Version >= 17 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @CompressionAlgorithm = 'ZSTD' AND NOT (@Version >= 17 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to ZSTD is only supported in SQL Server 2025 and later.', 16, 4 @@ -1698,7 +1712,7 @@ BEGIN SELECT 'The value for the parameter @CompressionLevel is not supported. The supported values are LOW, MEDIUM and HIGH.', 16, 2 END - IF @CompressionLevel IS NOT NULL AND NOT (@Version >= 17 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @CompressionLevel IS NOT NULL AND NOT (@Version >= 17 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @CompressionLevel is not supported. Setting the compression level is only supported in SQL Server 2025 and later.', 16, 3 @@ -2054,7 +2068,7 @@ BEGIN SELECT 'The value for the parameter @Encrypt is not supported.', 16, 1 END - IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (SERVERPROPERTY('EngineEdition') IN(3, 8) OR SERVERPROPERTY('EditionID') IN(-1534726760, -1785266663)) + IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@EngineEdition IN(3, 8) OR @EditionID IN(-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @Encrypt is not supported.', 16, 2 @@ -2514,7 +2528,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF (SERVERPROPERTY('IsHadrEnabled') = 1 AND @AvailabilityGroupFileName IS NULL) + IF (@IsHadrEnabled = 1 AND @AvailabilityGroupFileName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 1 @@ -2772,7 +2786,7 @@ BEGIN SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 END - IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 + IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 2 @@ -2786,7 +2800,7 @@ BEGIN SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 END - IF @DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5 + IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 2 @@ -2848,10 +2862,10 @@ BEGIN --// Check @@SERVERNAME //-- ---------------------------------------------------------------------------------------------------- - IF UPPER(@@SERVERNAME) <> UPPER(CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF UPPER(@@SERVERNAME) <> UPPER(@ServerName) AND @IsHadrEnabled = 1 BEGIN 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 + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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 ---------------------------------------------------------------------------------------------------- @@ -2886,7 +2900,7 @@ BEGIN --// Check Availability Group cluster name //-- ---------------------------------------------------------------------------------------------------- - IF SERVERPROPERTY('IsHadrEnabled') = 1 + IF @IsHadrEnabled = 1 BEGIN SELECT @Cluster = NULLIF(cluster_name,'') FROM sys.dm_hadr_cluster @@ -3184,10 +3198,10 @@ 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 < 15.04043 AND NOT (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) AND @Credential IS NULL THEN 65537 + WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version < 15.04043 AND NOT (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND @Credential IS NULL THEN 65537 END - IF SERVERPROPERTY('IsHadrEnabled') = 1 + IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id FROM sys.databases databases @@ -3214,12 +3228,12 @@ BEGIN WHERE group_id = @CurrentAvailabilityGroupID END - IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + IF @IsHadrEnabled = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) END - IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + IF @IsHadrEnabled = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id @@ -3343,7 +3357,7 @@ BEGIN OR (@CurrentBackupType = 'DIFF' AND @CopyOnly = 'N' AND @Version >= 17) OR (@CurrentBackupType = 'FULL' AND @CopyOnly = 'Y') OR (@CurrentBackupType = 'LOG' AND @CopyOnly = 'N')) - AND SERVERPROPERTY('EngineEdition') = 3 + AND @EngineEdition = 3 BEGIN SET @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 END @@ -3492,7 +3506,7 @@ BEGIN 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}','') + IF @InstanceName IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}','') IF @@SERVICENAME IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}','') IF @Description IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}','') IF @BackupSetName IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@BackupSetName,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupSetName}','') @@ -3643,8 +3657,8 @@ BEGIN -- Directory structure - replace tokens with real values SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}',@DirectorySeparator) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}',CASE WHEN SERVERPROPERTY('EngineEdition') = 8 AND CHARINDEX('.',CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) > 0 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,'{ServerName}',CASE WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) > 0 THEN LEFT(@ServerName,CHARINDEX('.',@ServerName) - 1) ELSE @MachineName END) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}',ISNULL(@InstanceName,'')) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}',ISNULL(@@SERVICENAME,'')) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}',ISNULL(@Cluster,'')) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{AvailabilityGroupName}',ISNULL(@CurrentAvailabilityGroup,'')) @@ -3664,8 +3678,8 @@ BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Second}',RIGHT('0' + CAST(DATEPART(SECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),2)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Millisecond}',RIGHT('00' + CAST(DATEPART(MILLISECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),3)) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),6)) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4))) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3))) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MajorVersion}',@ProductMajorVersion) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{MinorVersion}',@ProductMinorVersion) END IF @DirectoryStructureCase IS NOT NULL @@ -3702,7 +3716,7 @@ BEGIN 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 @InstanceName IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}','') IF @@SERVICENAME IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}','') IF @Description IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}','') IF @BackupSetName IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@BackupSetName,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{BackupSetName}','') @@ -3808,8 +3822,8 @@ BEGIN END -- File name - replace tokens with real values - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServerName}',CASE WHEN SERVERPROPERTY('EngineEdition') = 8 AND CHARINDEX('.',CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) > 0 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,'{ServerName}',CASE WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) > 0 THEN LEFT(@ServerName,CHARINDEX('.',@ServerName) - 1) ELSE @MachineName END) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}',ISNULL(@InstanceName,'')) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}',ISNULL(@@SERVICENAME,'')) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}',ISNULL(@Cluster,'')) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{AvailabilityGroupName}',ISNULL(@CurrentAvailabilityGroup,'')) @@ -3830,8 +3844,8 @@ BEGIN SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Microsecond}',RIGHT('00000' + CAST(DATEPART(MICROSECOND,CASE WHEN @TokenTimezone = 'UTC' THEN @CurrentDateUTC ELSE @CurrentDate END) AS nvarchar(max)),6)) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{NumberOfFiles}',CAST(@CurrentNumberOfFiles AS nvarchar(max))) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{FileExtension}',@CurrentFileExtension) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMajorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4))) - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MinorVersion}',ISNULL(CAST(SERVERPROPERTY('ProductMinorVersion') AS nvarchar(max)),PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3))) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MajorVersion}',@ProductMajorVersion) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{MinorVersion}',@ProductMinorVersion) SELECT @CurrentMaxFilePathLength = CASE WHEN EXISTS (SELECT * FROM @CurrentDirectories) THEN (SELECT MAX(LEN(DirectoryPath + @DirectorySeparator)) FROM @CurrentDirectories) @@ -4198,7 +4212,7 @@ BEGIN IF @Checksum = 'Y' SET @CurrentCommand += 'CHECKSUM' IF @Checksum = 'N' SET @CurrentCommand += 'NO_CHECKSUM' - SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND (@CurrentMaxTransferSize >= 65537 OR (@Version >= 15.04043 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))))) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END + SET @CurrentCommand += CASE WHEN @Compress = 'Y' AND (@CurrentIsEncrypted = 0 OR (@CurrentIsEncrypted = 1 AND (@CurrentMaxTransferSize >= 65537 OR (@Version >= 15.04043 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))))) THEN ', COMPRESSION' ELSE ', NO_COMPRESSION' END IF @Compress = 'Y' AND @CompressionAlgorithm IS NOT NULL BEGIN @@ -4401,7 +4415,7 @@ BEGIN IF @DataDomainBoostNoOutputTable = 'Y' SET @CurrentCommand += 'INSERT INTO @DataDomainBoostOutput ([Message]) ' SET @CurrentCommand += 'EXECUTE @ReturnCode = dbo.emc_run_backup ''' - SET @CurrentCommand += ' -c ' + CASE WHEN @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL THEN REPLACE(@Cluster,'''','''''') ELSE REPLACE(CAST(SERVERPROPERTY('MachineName') AS nvarchar(max)),'''','''''') END + SET @CurrentCommand += ' -c ' + CASE WHEN @Cluster IS NOT NULL AND @CurrentAvailabilityGroup IS NOT NULL THEN REPLACE(@Cluster,'''','''''') ELSE REPLACE(@MachineName,'''','''''') END SET @CurrentCommand += ' -l ' + CASE WHEN @CurrentBackupType = 'FULL' THEN 'full' @@ -4432,8 +4446,8 @@ BEGIN IF @CopyOnly = 'Y' SET @CurrentCommand += ' -a "NSR_COPY_ONLY=TRUE"' IF @BackupSetName IS NOT NULL SET @CurrentCommand += ' -N "' + REPLACE(@BackupSetName,'''','''''') + '"' - IF SERVERPROPERTY('InstanceName') IS NULL SET @CurrentCommand += ' "MSSQL' - IF SERVERPROPERTY('InstanceName') IS NOT NULL SET @CurrentCommand += ' "MSSQL$' + CAST(SERVERPROPERTY('InstanceName') AS nvarchar(max)) + IF @InstanceName IS NULL SET @CurrentCommand += ' "MSSQL' + IF @InstanceName IS NOT NULL SET @CurrentCommand += ' "MSSQL$' + @InstanceName SET @CurrentCommand += ':' + REPLACE(REPLACE(@CurrentDatabaseName,'''',''''''),'.','\.') + '"' SET @CurrentCommand += '''' @@ -4832,7 +4846,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-07 20:44:09 //-- + --// Version: 2026-07-11 19:11:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4976,20 +4990,28 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) - DECLARE @Version numeric(18,10) = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4) + '.' + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),2) AS numeric(18,10)) + DECLARE @ProductVersion nvarchar(max) = CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + DECLARE @ProductUpdateType nvarchar(max) = CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + DECLARE @EngineEdition int = CAST(SERVERPROPERTY('EngineEdition') AS int) + DECLARE @Edition nvarchar(max) = CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + DECLARE @IsHadrEnabled bit = CAST(SERVERPROPERTY('IsHadrEnabled') AS bit) + DECLARE @IsClustered bit = CAST(SERVERPROPERTY('IsClustered') AS bit) + DECLARE @ServerName nvarchar(max) = CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + + DECLARE @Version numeric(18,10) = CAST(PARSENAME(@ProductVersion,4) + '.' + PARSENAME(@ProductVersion,3) + PARSENAME(@ProductVersion,2) AS numeric(18,10)) - IF SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' + IF @EngineEdition = 8 AND @ProductVersion = '12.0.2000.8' AND @ProductUpdateType = 'CU' BEGIN SET @Version = 16.01000 END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SELECT @HostPlatform = host_platform FROM sys.dm_os_host_info END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) @@ -4998,7 +5020,7 @@ BEGIN END END - DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- @@ -5030,28 +5052,28 @@ BEGIN SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + SET @StartMessage = 'Server: ' + @ServerName RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + SET @StartMessage = 'Version: ' + @ProductVersion RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + SET @StartMessage = 'Edition: ' + @Edition RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - IF SERVERPROPERTY('EngineEdition') = 8 + IF @EngineEdition = 8 BEGIN - SET @StartMessage = 'Update type: ' + CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + SET @StartMessage = 'Update type: ' + @ProductUpdateType RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -5182,7 +5204,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF SERVERPROPERTY('IsHadrEnabled') = 1 + IF @IsHadrEnabled = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName) SELECT name AS AvailabilityGroupName @@ -5251,7 +5273,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -5336,7 +5358,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 SERVERPROPERTY('IsHadrEnabled') = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @IsHadrEnabled = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 @@ -5687,7 +5709,7 @@ BEGIN 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 >= 14.03029 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 14.03029 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) 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 @@ -5705,7 +5727,7 @@ BEGIN 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 + IF @DatabaseOrder IS NOT NULL AND @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 @@ -5719,7 +5741,7 @@ BEGIN SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 END - IF @DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5 + IF @DatabasesInParallel = 'Y' AND @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 @@ -5831,10 +5853,10 @@ BEGIN --// Check @@SERVERNAME //-- ---------------------------------------------------------------------------------------------------- - IF UPPER(@@SERVERNAME) <> UPPER(CAST(SERVERPROPERTY('ServerName') AS nvarchar(max))) AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF UPPER(@@SERVERNAME) <> UPPER(@ServerName) AND @IsHadrEnabled = 1 BEGIN 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 + SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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 ---------------------------------------------------------------------------------------------------- @@ -6183,7 +6205,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - IF SERVERPROPERTY('IsHadrEnabled') = 1 + IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id FROM sys.databases databases @@ -6205,12 +6227,12 @@ BEGIN WHERE group_id = @CurrentAvailabilityGroupID END - IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL AND @AvailabilityGroupReplicas = 'PREFERRED_BACKUP_REPLICA' + IF @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('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + IF @IsHadrEnabled = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id @@ -6225,7 +6247,7 @@ BEGIN WHERE dm_hadr_availability_replica_states.replica_id = @CurrentDistributedAvailabilityGroupReplicaID END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring database_mirroring @@ -6282,7 +6304,7 @@ BEGIN IF @CurrentDatabaseState IN('ONLINE','EMERGENCY') AND NOT (@CurrentUserAccess = 'SINGLE_USER') - AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR SERVERPROPERTY('EngineEdition') = 3) + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR @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') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') @@ -6292,7 +6314,7 @@ BEGIN -- Check database IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKDB') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentDatabaseContext = CASE WHEN SERVERPROPERTY('EngineEdition') = 5 THEN @CurrentDatabaseName ELSE 'master' END + SET @CurrentDatabaseContext = CASE WHEN @EngineEdition = 5 THEN @CurrentDatabaseName ELSE 'master' END SET @CurrentCommandType = 'DBCC_CHECKDB' @@ -6462,7 +6484,7 @@ BEGIN -- 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 @CurrentDatabaseContext = CASE WHEN SERVERPROPERTY('EngineEdition') = 5 THEN @CurrentDatabaseName ELSE 'master' END + SET @CurrentDatabaseContext = CASE WHEN @EngineEdition = 5 THEN @CurrentDatabaseName ELSE 'master' END SET @CurrentCommandType = 'DBCC_CHECKALLOC' @@ -6637,7 +6659,7 @@ BEGIN -- Check catalog IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKCATALOG') AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - SET @CurrentDatabaseContext = CASE WHEN SERVERPROPERTY('EngineEdition') = 5 THEN @CurrentDatabaseName ELSE 'master' END + SET @CurrentDatabaseContext = CASE WHEN @EngineEdition = 5 THEN @CurrentDatabaseName ELSE 'master' END SET @CurrentCommandType = 'DBCC_CHECKCATALOG' @@ -6793,7 +6815,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-07 20:44:09 //-- + --// Version: 2026-07-11 19:11:40 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7028,20 +7050,27 @@ BEGIN DECLARE @EmptyLine nvarchar(max) = CHAR(9) - DECLARE @Version numeric(18,10) = CAST(PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),4) + '.' + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),3) + PARSENAME(CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)),2) AS numeric(18,10)) + DECLARE @ProductVersion nvarchar(max) = CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + DECLARE @ProductUpdateType nvarchar(max) = CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + DECLARE @EngineEdition int = CAST(SERVERPROPERTY('EngineEdition') AS int) + DECLARE @Edition nvarchar(max) = CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + DECLARE @IsHadrEnabled bit = CAST(SERVERPROPERTY('IsHadrEnabled') AS bit) + DECLARE @ServerName nvarchar(max) = CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + + DECLARE @Version numeric(18,10) = CAST(PARSENAME(@ProductVersion,4) + '.' + PARSENAME(@ProductVersion,3) + PARSENAME(@ProductVersion,2) AS numeric(18,10)) - IF SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductVersion') = '12.0.2000.8' AND SERVERPROPERTY('ProductUpdateType') = 'CU' + IF @EngineEdition = 8 AND @ProductVersion = '12.0.2000.8' AND @ProductUpdateType = 'CU' BEGIN SET @Version = 16.01000 END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SELECT @HostPlatform = host_platform FROM sys.dm_os_host_info END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) @@ -7050,7 +7079,7 @@ BEGIN END END - DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- --// Log initial information //-- @@ -7097,28 +7126,28 @@ BEGIN SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Server: ' + CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + SET @StartMessage = 'Server: ' + @ServerName RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Version: ' + CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + SET @StartMessage = 'Version: ' + @ProductVersion RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Edition: ' + CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + SET @StartMessage = 'Edition: ' + @Edition RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - IF SERVERPROPERTY('EngineEdition') = 8 + IF @EngineEdition = 8 BEGIN - SET @StartMessage = 'Update type: ' + CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + SET @StartMessage = 'Update type: ' + @ProductUpdateType RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -7249,7 +7278,7 @@ BEGIN FROM Databases4 OPTION (MAXRECURSION 0) - IF SERVERPROPERTY('IsHadrEnabled') = 1 + IF @IsHadrEnabled = 1 BEGIN INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName) SELECT name AS AvailabilityGroupName @@ -7317,7 +7346,7 @@ BEGIN --// Select availability groups //-- ---------------------------------------------------------------------------------------------------- - IF @AvailabilityGroups IS NOT NULL AND SERVERPROPERTY('IsHadrEnabled') = 1 + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 1 BEGIN SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') @@ -7402,7 +7431,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 SERVERPROPERTY('IsHadrEnabled') = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @IsHadrEnabled = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 @@ -7778,7 +7807,7 @@ BEGIN SELECT 'The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3 END - IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.03006 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.03006 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 4 @@ -7888,7 +7917,7 @@ BEGIN SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 END - IF @DatabaseOrder IS NOT NULL AND SERVERPROPERTY('EngineEdition') = 5 + IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 2 @@ -7902,7 +7931,7 @@ BEGIN SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 END - IF @DatabasesInParallel = 'Y' AND SERVERPROPERTY('EngineEdition') = 5 + IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 2 @@ -8275,7 +8304,7 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - IF SERVERPROPERTY('IsHadrEnabled') = 1 + IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id FROM sys.databases databases @@ -8295,7 +8324,7 @@ BEGIN WHERE group_id = @CurrentAvailabilityGroupID END - IF SERVERPROPERTY('IsHadrEnabled') = 1 AND @CurrentAvailabilityGroup IS NOT NULL + IF @IsHadrEnabled = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id @@ -8310,7 +8339,7 @@ BEGIN WHERE dm_hadr_availability_replica_states.replica_id = @CurrentDistributedAvailabilityGroupReplicaID END - IF SERVERPROPERTY('EngineEdition') <> 5 + IF @EngineEdition <> 5 BEGIN SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) FROM sys.database_mirroring database_mirroring @@ -8550,7 +8579,7 @@ BEGIN + ', 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] = indexes.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] = indexes.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] = indexes.[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] = indexes.object_id AND columns.is_filestream = 1) THEN 1 ELSE 0 END AS IsFileStream' - + ', ' + CASE WHEN (@Version >= 16 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' + + ', ' + CASE WHEN (@Version >= 16 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' + ', 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 OR index_columns.is_included_column = 1) 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.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND types.[name] = ''timestamp'') THEN 1 ELSE 0 END AS IsTimestamp' + ' FROM sys.indexes indexes' @@ -8938,16 +8967,16 @@ BEGIN INSERT INTO @CurrentActionsAllowed ([Action]) VALUES ('INDEX_REBUILD_OFFLINE') END - IF SERVERPROPERTY('EngineEdition') IN (3, 5, 8) + IF @EngineEdition IN (3, 5, 8) AND NOT (@CurrentOnReadOnlyFileGroup = 1) AND NOT (@CurrentIsMemoryOptimized = 1) AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1) AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1) AND NOT (@CurrentIndexType = 3) AND NOT (@CurrentIndexType = 4) - AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) - AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND NOT (@Version >= 15 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) - AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND NOT (@Version >= 17 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) BEGIN INSERT INTO @CurrentActionsAllowed ([Action]) VALUES ('INDEX_REBUILD_ONLINE') @@ -9290,7 +9319,7 @@ BEGIN IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' SET @CurrentCommand += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) - IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR SERVERPROPERTY('EngineEdition') = 5 OR (SERVERPROPERTY('EngineEdition') = 8 AND SERVERPROPERTY('ProductUpdateType') = 'Continuous')) + IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max)) From 914054697f3798d9243badac9d7eccad7ffcbee7 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 12 Jul 2026 10:10:13 +0200 Subject: [PATCH 068/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 29 ++++++++++++++++++++++++++++- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 37 ++++++++++++++++++++++++++++++++----- 5 files changed, 63 insertions(+), 9 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 149f2073..5a4de7ef 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-11 19:11:40 //-- + --// Version: 2026-07-12 10:00:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index bb85e1e5..7d301b62 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -73,6 +73,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @Format nvarchar(max) = 'N', @ObjectLevelRecoveryMap nvarchar(max) = 'N', @ExcludeLogShippedFromLogBackup nvarchar(max) = 'Y', +@ExcludeSeedingFromLogBackup nvarchar(max) = 'N', @DirectoryCheck nvarchar(max) = 'Y', @BackupOptions nvarchar(max) = NULL, @Stats int = NULL, @@ -93,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-11 19:11:40 //-- + --// Version: 2026-07-12 10:00:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -172,6 +173,7 @@ BEGIN DECLARE @CurrentIsPreferredBackupReplica bit DECLARE @CurrentDatabaseMirroringRole nvarchar(max) DECLARE @CurrentLogShippingRole nvarchar(max) + DECLARE @CurrentIsSeeding bit DECLARE @CurrentBackupOperationSupportedOnSecondaryReplicas bit DECLARE @CurrentBackupSetID int @@ -385,6 +387,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 += ', @ExcludeSeedingFromLogBackup = ' + ISNULL('''' + REPLACE(@ExcludeSeedingFromLogBackup,'''','''''') + '''','NULL') SET @Parameters += ', @DirectoryCheck = ' + ISNULL('''' + REPLACE(@DirectoryCheck,'''','''''') + '''','NULL') SET @Parameters += ', @BackupOptions = ' + ISNULL('''' + REPLACE(@BackupOptions,'''','''''') + '''','NULL') SET @Parameters += ', @Stats = ' + ISNULL(CAST(@Stats AS nvarchar(max)),'NULL') @@ -2319,6 +2322,20 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @ExcludeSeedingFromLogBackup NOT IN('Y','N') OR @ExcludeSeedingFromLogBackup IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ExcludeSeedingFromLogBackup is not supported.', 16, 1 + END + + IF @ExcludeSeedingFromLogBackup = 'Y' AND @BackupType <> 'LOG' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameter @ExcludeSeedingFromLogBackup can only be used for log backups.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF @DirectoryCheck NOT IN('Y','N') OR @DirectoryCheck IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -2834,6 +2851,11 @@ BEGIN SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) END + IF @IsHadrEnabled = 1 AND @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SELECT @CurrentIsSeeding = CASE WHEN EXISTS (SELECT * FROM sys.dm_hadr_physical_seeding_stats dm_hadr_physical_seeding_stats WHERE dm_hadr_physical_seeding_stats.local_database_name = @CurrentDatabaseName AND dm_hadr_physical_seeding_stats.role_desc IN('Source','Forwarder') AND dm_hadr_physical_seeding_stats.end_time_utc IS NULL) THEN 1 ELSE 0 END + END + IF @IsHadrEnabled = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], @@ -2993,6 +3015,9 @@ BEGIN SET @DatabaseMessage = 'Is backup operation supported on secondary replicas: ' + CASE WHEN @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 THEN 'Yes' WHEN @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 THEN 'No' ELSE 'N/A' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END + + SET @DatabaseMessage = 'Is seeding: ' + CASE WHEN @CurrentIsSeeding = 1 THEN 'Yes' WHEN @CurrentIsSeeding = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END IF @CurrentDistributedAvailabilityGroup IS NOT NULL @@ -3066,6 +3091,7 @@ BEGIN AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND @AllowNonCopyOnlyBackupsOnForwarder = 'N' AND NOT (@CurrentBackupType = 'FULL' AND @CopyOnly = 'Y')) AND NOT ((@CurrentLogShippingRole = 'PRIMARY' AND @CurrentLogShippingRole IS NOT NULL) AND @CurrentBackupType = 'LOG' AND @ExcludeLogShippedFromLogBackup = 'Y') + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupType = 'LOG' AND @ExcludeSeedingFromLogBackup = 'Y' AND @CurrentIsSeeding = 1) AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') AND NOT (@CurrentBackupType = 'LOG' AND @MinLogSizeSinceLastLogBackup IS NOT NULL AND @MinTimeSinceLastLogBackup IS NOT NULL AND NOT(@CurrentLogSizeSinceLastLogBackup >= @MinLogSizeSinceLastLogBackup OR @CurrentLogSizeSinceLastLogBackup IS NULL OR DATEDIFF(SECOND,@CurrentLastLogBackup,SYSDATETIME()) >= @MinTimeSinceLastLogBackup OR @CurrentLastLogBackup IS NULL)) @@ -4365,6 +4391,7 @@ BEGIN SET @CurrentDistributedAvailabilityGroupRole = NULL SET @CurrentDatabaseMirroringRole = NULL SET @CurrentLogShippingRole = NULL + SET @CurrentIsSeeding = NULL SET @CurrentBackupOperationSupportedOnSecondaryReplicas = NULL SET @CurrentLastLogBackup = NULL SET @CurrentLogSizeSinceLastLogBackup = NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index c4a66c70..519ea4d8 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-11 19:11:40 //-- + --// Version: 2026-07-12 10:00:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 506d88fa..cf968f63 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-11 19:11:40 //-- + --// Version: 2026-07-12 10:00:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 6919f63f..d7e783dc 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: 2026-07-11 19:11:40 +Version: 2026-07-12 10:00:16 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-11 19:11:40 //-- + --// Version: 2026-07-12 10:00:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -472,6 +472,7 @@ ALTER PROCEDURE [dbo].[DatabaseBackup] @Format nvarchar(max) = 'N', @ObjectLevelRecoveryMap nvarchar(max) = 'N', @ExcludeLogShippedFromLogBackup nvarchar(max) = 'Y', +@ExcludeSeedingFromLogBackup nvarchar(max) = 'N', @DirectoryCheck nvarchar(max) = 'Y', @BackupOptions nvarchar(max) = NULL, @Stats int = NULL, @@ -492,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-11 19:11:40 //-- + --// Version: 2026-07-12 10:00:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -571,6 +572,7 @@ BEGIN DECLARE @CurrentIsPreferredBackupReplica bit DECLARE @CurrentDatabaseMirroringRole nvarchar(max) DECLARE @CurrentLogShippingRole nvarchar(max) + DECLARE @CurrentIsSeeding bit DECLARE @CurrentBackupOperationSupportedOnSecondaryReplicas bit DECLARE @CurrentBackupSetID int @@ -784,6 +786,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 += ', @ExcludeSeedingFromLogBackup = ' + ISNULL('''' + REPLACE(@ExcludeSeedingFromLogBackup,'''','''''') + '''','NULL') SET @Parameters += ', @DirectoryCheck = ' + ISNULL('''' + REPLACE(@DirectoryCheck,'''','''''') + '''','NULL') SET @Parameters += ', @BackupOptions = ' + ISNULL('''' + REPLACE(@BackupOptions,'''','''''') + '''','NULL') SET @Parameters += ', @Stats = ' + ISNULL(CAST(@Stats AS nvarchar(max)),'NULL') @@ -2718,6 +2721,20 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @ExcludeSeedingFromLogBackup NOT IN('Y','N') OR @ExcludeSeedingFromLogBackup IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @ExcludeSeedingFromLogBackup is not supported.', 16, 1 + END + + IF @ExcludeSeedingFromLogBackup = 'Y' AND @BackupType <> 'LOG' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The parameter @ExcludeSeedingFromLogBackup can only be used for log backups.', 16, 2 + END + + ---------------------------------------------------------------------------------------------------- + IF @DirectoryCheck NOT IN('Y','N') OR @DirectoryCheck IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -3233,6 +3250,11 @@ BEGIN SELECT @CurrentIsPreferredBackupReplica = sys.fn_hadr_backup_is_preferred_replica(@CurrentDatabaseName) END + IF @IsHadrEnabled = 1 AND @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SELECT @CurrentIsSeeding = CASE WHEN EXISTS (SELECT * FROM sys.dm_hadr_physical_seeding_stats dm_hadr_physical_seeding_stats WHERE dm_hadr_physical_seeding_stats.local_database_name = @CurrentDatabaseName AND dm_hadr_physical_seeding_stats.role_desc IN('Source','Forwarder') AND dm_hadr_physical_seeding_stats.end_time_utc IS NULL) THEN 1 ELSE 0 END + END + IF @IsHadrEnabled = 1 AND @CurrentAvailabilityGroup IS NOT NULL BEGIN SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], @@ -3392,6 +3414,9 @@ BEGIN SET @DatabaseMessage = 'Is backup operation supported on secondary replicas: ' + CASE WHEN @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 THEN 'Yes' WHEN @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 THEN 'No' ELSE 'N/A' END RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END + + SET @DatabaseMessage = 'Is seeding: ' + CASE WHEN @CurrentIsSeeding = 1 THEN 'Yes' WHEN @CurrentIsSeeding = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END IF @CurrentDistributedAvailabilityGroup IS NOT NULL @@ -3465,6 +3490,7 @@ BEGIN AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND @AllowNonCopyOnlyBackupsOnForwarder = 'N' AND NOT (@CurrentBackupType = 'FULL' AND @CopyOnly = 'Y')) AND NOT ((@CurrentLogShippingRole = 'PRIMARY' AND @CurrentLogShippingRole IS NOT NULL) AND @CurrentBackupType = 'LOG' AND @ExcludeLogShippedFromLogBackup = 'Y') + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupType = 'LOG' AND @ExcludeSeedingFromLogBackup = 'Y' AND @CurrentIsSeeding = 1) AND NOT (@CurrentIsReadOnly = 1 AND @Updateability = 'READ_WRITE') AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') AND NOT (@CurrentBackupType = 'LOG' AND @MinLogSizeSinceLastLogBackup IS NOT NULL AND @MinTimeSinceLastLogBackup IS NOT NULL AND NOT(@CurrentLogSizeSinceLastLogBackup >= @MinLogSizeSinceLastLogBackup OR @CurrentLogSizeSinceLastLogBackup IS NULL OR DATEDIFF(SECOND,@CurrentLastLogBackup,SYSDATETIME()) >= @MinTimeSinceLastLogBackup OR @CurrentLastLogBackup IS NULL)) @@ -4764,6 +4790,7 @@ BEGIN SET @CurrentDistributedAvailabilityGroupRole = NULL SET @CurrentDatabaseMirroringRole = NULL SET @CurrentLogShippingRole = NULL + SET @CurrentIsSeeding = NULL SET @CurrentBackupOperationSupportedOnSecondaryReplicas = NULL SET @CurrentLastLogBackup = NULL SET @CurrentLogSizeSinceLastLogBackup = NULL @@ -4846,7 +4873,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-11 19:11:40 //-- + --// Version: 2026-07-12 10:00:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6815,7 +6842,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-11 19:11:40 //-- + --// Version: 2026-07-12 10:00:16 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 8a91faeee93a1cf444bb92388cb3f58f1893f0b7 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 14 Jul 2026 22:08:56 +0200 Subject: [PATCH 069/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 4 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 591 ++++++++++++++++++------------------ MaintenanceSolution.sql | 601 +++++++++++++++++++------------------ 5 files changed, 607 insertions(+), 593 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 5a4de7ef..8b876309 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-12 10:00:16 //-- + --// Version: 2026-07-14 22:07:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 7d301b62..6922876c 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-12 10:00:16 //-- + --// Version: 2026-07-14 22:07:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2904,7 +2904,7 @@ BEGIN BEGIN SET @CurrentBackupType = 'DIFF' END - IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @MinModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) + IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / NULLIF(@CurrentAllocatedExtentPageCount, 0) * 100 >= @MinModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) BEGIN SET @CurrentBackupType = 'FULL' END diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 519ea4d8..5d7d8df5 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-12 10:00:16 //-- + --// Version: 2026-07-14 22:07:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index cf968f63..1315c0c5 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-12 10:00:16 //-- + --// Version: 2026-07-14 22:07:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -141,10 +141,8 @@ BEGIN DECLARE @CurrentIndexExists bit DECLARE @CurrentStatisticsExists bit DECLARE @CurrentIsImageText bit - DECLARE @CurrentIsNewLOB bit DECLARE @CurrentIsFileStream bit DECLARE @CurrentHasClusteredColumnstore bit - DECLARE @CurrentHasNonClusteredColumnstore bit DECLARE @CurrentIsColumnstoreOrdered bit DECLARE @CurrentIsComputed bit DECLARE @CurrentIsClusteredIndexComputed bit @@ -201,10 +199,8 @@ BEGIN AllowPageLocks bit, HasFilter bit, IsImageText bit, - IsNewLOB bit, IsFileStream bit, HasClusteredColumnstore bit, - HasNonClusteredColumnstore bit, IsColumnstoreOrdered bit, IsComputed bit, IsClusteredIndexComputed bit, @@ -224,28 +220,53 @@ BEGIN Completed bit DEFAULT 0, PRIMARY KEY (Selected, Completed, [Order], ID)) - DECLARE @tmpObjectProperties TABLE (ObjectID int NOT NULL, - HasClusteredColumnstore bit, - HasNonClusteredColumnstore bit, - IsClusteredIndexComputed bit, - PRIMARY KEY (ObjectID)) - - DECLARE @tmpIndexProperties TABLE (ObjectID int NOT NULL, - IndexID int NOT NULL, - IsImageText bit, - IsNewLOB bit, - IsFileStream bit, - IsColumnstoreOrdered bit, - IsComputed bit, - IsTimestamp bit, - PRIMARY KEY (ObjectID, IndexID)) - - DECLARE @tmpIndexStatisticsProperties TABLE (ObjectID int NOT NULL, - StatisticsID int NOT NULL, - StatisticsName nvarchar(128), - [NoRecompute] bit, - IsIncremental bit, - PRIMARY KEY (ObjectID, StatisticsID)) + DROP TABLE IF EXISTS #SelectedIndexes + + CREATE TABLE #SelectedIndexes (DatabaseName nvarchar(max) COLLATE DATABASE_DEFAULT, + SchemaName nvarchar(max) COLLATE DATABASE_DEFAULT, + ObjectName nvarchar(max) COLLATE DATABASE_DEFAULT, + IndexName nvarchar(max) COLLATE DATABASE_DEFAULT, + StartPosition int, + Selected bit) + + DROP TABLE IF EXISTS #Objects + + CREATE TABLE #Objects (ObjectID int NOT NULL, + SchemaID int, + SchemaName nvarchar(128) COLLATE DATABASE_DEFAULT, + ObjectName nvarchar(128) COLLATE DATABASE_DEFAULT, + ObjectType nvarchar(2) COLLATE DATABASE_DEFAULT, + IsMemoryOptimized bit, + HasClusteredColumnstore bit, + IsClusteredIndexComputed bit, + IsClusteredIndexDisabled bit, + PRIMARY KEY (ObjectID)) + + DROP TABLE IF EXISTS #Indexes + + CREATE TABLE #Indexes (ObjectID int NOT NULL, + IndexID int NOT NULL, + IndexName nvarchar(128) COLLATE DATABASE_DEFAULT, + IndexType int, + DataSpaceID int, + AllowPageLocks bit, + HasFilter bit, + IsImageText bit, + IsFileStream bit, + IsColumnstoreOrdered bit, + IsComputed bit, + IsTimestamp bit, + PRIMARY KEY (ObjectID, IndexID)) + + DROP TABLE IF EXISTS #Stats + + CREATE TABLE #Stats (ObjectID int NOT NULL, + StatisticsID int NOT NULL, + StatisticsName nvarchar(128) COLLATE DATABASE_DEFAULT, + [NoRecompute] bit, + IsIncremental bit, + IsIndex bit, + PRIMARY KEY (ObjectID, StatisticsID)) DECLARE @tmpResumableOperations TABLE (ObjectID int NOT NULL, IndexID int NOT NULL, @@ -298,6 +319,8 @@ BEGIN DECLARE @IsHadrEnabled bit = CAST(SERVERPROPERTY('IsHadrEnabled') AS bit) DECLARE @ServerName nvarchar(max) = CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + DECLARE @Collation nvarchar(128) = CAST(DATABASEPROPERTYEX(DB_NAME(),'Collation') AS nvarchar(128)) + DECLARE @Version numeric(18,10) = CAST(PARSENAME(@ProductVersion,4) + '.' + PARSENAME(@ProductVersion,3) + PARSENAME(@ProductVersion,2) AS numeric(18,10)) IF @EngineEdition = 8 AND @ProductVersion = '12.0.2000.8' AND @ProductUpdateType = 'CU' @@ -744,6 +767,10 @@ BEGIN FROM Indexes4 OPTION (MAXRECURSION 0) + INSERT INTO #SelectedIndexes (DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected) + SELECT DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected + FROM @SelectedIndexes + ---------------------------------------------------------------------------------------------------- --// Select actions //-- ---------------------------------------------------------------------------------------------------- @@ -1652,6 +1679,99 @@ BEGIN IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN + -- Select objects + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT objects.[object_id] AS ObjectID' + + ', objects.[schema_id] AS SchemaID' + + ', schemas.[name] AS SchemaName' + + ', objects.[name] AS ObjectName' + + ', RTRIM(objects.[type]) AS ObjectType' + + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') THEN 'CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 5) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS HasClusteredColumnstore' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') AND @Resumable = 'Y' THEN '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.indexes indexes2 ON index_columns.object_id = indexes2.object_id AND index_columns.index_id = indexes2.index_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND indexes2.[type] = 1 AND index_columns.object_id = objects.object_id) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsClusteredIndexComputed' + + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 1 AND is_disabled = 1) THEN 1 ELSE 0 END AS IsClusteredIndexDisabled' + + ' 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 (tables.is_external = 0 OR tables.is_external IS NULL)' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + IF @Indexes IS NOT NULL AND EXISTS(SELECT * FROM @SelectedIndexes WHERE Selected = 1) AND NOT EXISTS(SELECT * FROM @SelectedIndexes WHERE Selected = 1 AND DatabaseName = '%' AND SchemaName = '%' AND ObjectName = '%') + BEGIN + SET @CurrentCommand += ' AND EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes WHERE @ParamDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND schemas.[name] LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND objects.[name] LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND SelectedIndexes.Selected = 1)' + END + + INSERT INTO #Objects (ObjectID, SchemaID, SchemaName, ObjectName, ObjectType, IsMemoryOptimized, HasClusteredColumnstore, IsClusteredIndexComputed, IsClusteredIndexDisabled) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max)', @ParamDatabaseName = @CurrentDatabaseName + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select indexes + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT indexes.[object_id] AS ObjectID' + + ', indexes.index_id AS IndexID' + + ', indexes.[name] AS IndexName' + + ', indexes.[type] AS IndexType' + + ', indexes.data_space_id AS DataSpaceID' + + ', indexes.allow_page_locks AS AllowPageLocks' + + ', indexes.has_filter AS HasFilter' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') THEN '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] = indexes.object_id AND types.name IN(''image'',''text'',''ntext'')) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsImageText' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') THEN 'CASE WHEN indexes.[type] = 1 AND EXISTS(SELECT * FROM sys.columns columns WHERE columns.[object_id] = indexes.object_id AND columns.is_filestream = 1) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsFileStream' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') AND (@Version >= 16 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsColumnstoreOrdered' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') AND @Resumable = 'Y' THEN '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 OR index_columns.is_included_column = 1) 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' ELSE 'NULL' END + ' AS IsComputed' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') AND @Resumable = 'Y' THEN '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.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND types.[name] = ''timestamp'') THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsTimestamp' + + ' FROM sys.indexes indexes' + + ' INNER JOIN #Objects Objects ON indexes.[object_id] = Objects.ObjectID' + + ' AND indexes.[type] IN(1,2,3,4,5,6,7)' + + ' AND indexes.is_disabled = 0' + + ' AND indexes.is_hypothetical = 0' + + INSERT INTO #Indexes (ObjectID, IndexID, IndexName, IndexType, DataSpaceID, AllowPageLocks, HasFilter, IsImageText, IsFileStream, IsColumnstoreOrdered, IsComputed, IsTimestamp) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select statistics + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT stats.[object_id] AS ObjectID' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental AS IsIncremental' + + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id) THEN 1 ELSE 0 END AS IsIndex' + + ' FROM sys.stats stats' + + ' INNER JOIN #Objects Objects ON stats.[object_id] = Objects.ObjectID' + + INSERT INTO #Stats (ObjectID, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, IsIndex) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select paused resumable index operations + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT index_resumable_operations.object_id AS ObjectID' + + ', index_resumable_operations.index_id AS IndexID' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'index_resumable_operations.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END + + ' FROM sys.index_resumable_operations index_resumable_operations' + + ' WHERE index_resumable_operations.state_desc = ''PAUSED''' + + INSERT INTO @tmpResumableOperations (ObjectID, IndexID, PartitionNumber) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') BEGIN -- Check if there are read-only filegroups in the database @@ -1664,48 +1784,53 @@ BEGIN SET @ReturnCode = @Error END - -- Select indexes on tables + -- Select clustered, nonclustered and hash indexes 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' - + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' - + ', indexes.index_id AS IndexID' - + ', indexes.[name] AS IndexName' - + ', indexes.[type] AS IndexType' - + ', indexes.allow_page_locks AS AllowPageLocks' - + ', indexes.has_filter AS HasFilter' - + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', 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' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Indexes.IndexID AS IndexID' + + ', Indexes.IndexName AS IndexName' + + ', Indexes.IndexType AS IndexType' + + ', Indexes.AllowPageLocks AS AllowPageLocks' + + ', Indexes.HasFilter AS HasFilter' + + ', Indexes.IsImageText AS IsImageText' + + ', Indexes.IsFileStream AS IsFileStream' + + ', Objects.HasClusteredColumnstore AS HasClusteredColumnstore' + + ', Indexes.IsColumnstoreOrdered AS IsColumnstoreOrdered' + + ', Indexes.IsComputed AS IsComputed' + + ', Objects.IsClusteredIndexComputed AS IsClusteredIndexComputed' + + ', Indexes.IsTimestamp AS IsTimestamp' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON Indexes.DataSpaceID = 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.ObjectID AND indexes2.[index_id] = Indexes.IndexID' + 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.DataSpaceID = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND Indexes.ObjectID = indexes2.[object_id] AND Indexes.IndexID = indexes2.index_id) THEN 1' + + ' WHEN Indexes.IndexType = 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.ObjectID) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + ', 0 AS ResumableIndexOperation' + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.StatisticsID AS StatisticsID' ELSE ', NULL AS StatisticsID' END + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.StatisticsName AS StatisticsName' ELSE ', NULL AS StatisticsName' END + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.[NoRecompute] AS NoRecompute' ELSE ', NULL AS NoRecompute' END + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.IsIncremental AS IsIncremental' ELSE ', NULL AS IsIncremental' END + ', ' + 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 - + ' 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.tables tables ON objects.[object_id] = tables.[object_id]' + + ' FROM #Indexes Indexes' + + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ' INNER JOIN #Stats Stats ON Indexes.ObjectID = Stats.ObjectID AND Indexes.IndexID = Stats.StatisticsID' ELSE '' END IF @PartitionLevel = 'Y' BEGIN - SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' + SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON Indexes.ObjectID = partitions.[object_id] AND Indexes.IndexID = partitions.index_id' END - IF @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) BEGIN SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.partition_id = dm_db_partition_stats.partition_id' END - SET @CurrentCommand += ' WHERE objects.[type] = ''U''' - + ' AND tables.is_external = 0' - + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END - + ' AND indexes.[type] IN(1,2,5,6,7)' - + ' AND indexes.is_disabled = 0' - + ' AND indexes.is_hypothetical = 0' + SET @CurrentCommand += ' WHERE Objects.ObjectType IN(''U'',''V'')' + + ' AND Indexes.IndexType IN(1,2,7)' + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= ' + CAST(@MinNumberOfPages AS nvarchar(max)) ELSE '' END + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= ' + CAST(@MaxNumberOfPages AS nvarchar(max)) ELSE '' END - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation, PartitionID, PartitionNumber) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -1713,34 +1838,35 @@ BEGIN SET @ReturnCode = @Error END - -- Select special indexes (XML and spatial) + -- Select XML and spatial indexes 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' - + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' - + ', indexes.index_id AS IndexID' - + ', indexes.[name] AS IndexName' - + ', indexes.[type] AS IndexType' - + ', indexes.allow_page_locks AS AllowPageLocks' - + ', indexes.has_filter AS HasFilter' - + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', 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) 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 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Indexes.IndexID AS IndexID' + + ', Indexes.IndexName AS IndexName' + + ', Indexes.IndexType AS IndexType' + + ', Indexes.AllowPageLocks AS AllowPageLocks' + + ', Indexes.HasFilter AS HasFilter' + + ', Indexes.IsImageText AS IsImageText' + + ', Indexes.IsFileStream AS IsFileStream' + + ', Objects.HasClusteredColumnstore AS HasClusteredColumnstore' + + ', Indexes.IsColumnstoreOrdered AS IsColumnstoreOrdered' + + ', Indexes.IsComputed AS IsComputed' + + ', Objects.IsClusteredIndexComputed AS IsClusteredIndexComputed' + + ', Indexes.IsTimestamp AS IsTimestamp' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON Indexes.DataSpaceID = 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.ObjectID AND indexes2.[index_id] = Indexes.IndexID) THEN 1' + + ' WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.filegroups filegroups ON Indexes.DataSpaceID = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND Indexes.ObjectID = indexes2.[object_id] AND Indexes.IndexID = indexes2.index_id) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + ', 0 AS ResumableIndexOperation' - + ' 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.tables tables ON objects.[object_id] = tables.[object_id]' - + ' WHERE objects.[type] = ''U''' - + ' AND tables.is_external = 0' - + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END - + ' AND indexes.[type] IN(3,4)' - + ' AND indexes.is_disabled = 0' - + ' AND indexes.is_hypothetical = 0' - - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation) + + ' FROM #Indexes Indexes' + + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + + ' WHERE Objects.ObjectType = ''U''' + + ' AND Indexes.IndexType IN(3,4)' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -1748,92 +1874,52 @@ BEGIN SET @ReturnCode = @Error END - -- Select indexes on views + -- Select columnstore indexes 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 IsMemoryOptimized' - + ', indexes.index_id AS IndexID' - + ', indexes.[name] AS IndexName' - + ', indexes.[type] AS IndexType' - + ', indexes.allow_page_locks AS AllowPageLocks' - + ', indexes.has_filter AS HasFilter' - + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', 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' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Indexes.IndexID AS IndexID' + + ', Indexes.IndexName AS IndexName' + + ', Indexes.IndexType AS IndexType' + + ', Indexes.AllowPageLocks AS AllowPageLocks' + + ', Indexes.HasFilter AS HasFilter' + + ', Indexes.IsImageText AS IsImageText' + + ', Indexes.IsFileStream AS IsFileStream' + + ', Objects.HasClusteredColumnstore AS HasClusteredColumnstore' + + ', Indexes.IsColumnstoreOrdered AS IsColumnstoreOrdered' + + ', Indexes.IsComputed AS IsComputed' + + ', Objects.IsClusteredIndexComputed AS IsClusteredIndexComputed' + + ', Indexes.IsTimestamp AS IsTimestamp' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON Indexes.DataSpaceID = 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.ObjectID AND indexes2.[index_id] = Indexes.IndexID' + 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.DataSpaceID = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND Indexes.ObjectID = indexes2.[object_id] AND Indexes.IndexID = indexes2.index_id) THEN 1' + + ' WHEN Indexes.IndexType = 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.ObjectID) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + ', 0 AS ResumableIndexOperation' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental AS IsIncremental' + + ', NULL AS StatisticsID' + + ', NULL AS StatisticsName' + + ', NULL AS NoRecompute' + + ', NULL 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 - + ' 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.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' + + ' FROM #Indexes Indexes' + + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' IF @PartitionLevel = 'Y' BEGIN - SET @CurrentCommand += ' LEFT OUTER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' + SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON Indexes.ObjectID = partitions.[object_id] AND Indexes.IndexID = partitions.index_id' END - SET @CurrentCommand += ' WHERE objects.[type] = ''V''' - + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END - + ' AND indexes.[type] IN(1,2)' - + ' AND indexes.is_disabled = 0' - + ' AND indexes.is_hypothetical = 0' - - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand - SET @Error = @@ERROR - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - END - - -- Select object properties - SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT objects.[object_id] AS ObjectID' - + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 5) THEN 1 ELSE 0 END AS HasClusteredColumnstore' - + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 6) THEN 1 ELSE 0 END AS HasNonClusteredColumnstore' - + ', 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.indexes indexes2 ON index_columns.object_id = indexes2.object_id AND index_columns.index_id = indexes2.index_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND indexes2.[type] = 1 AND index_columns.object_id = objects.object_id) THEN 1 ELSE 0 END AS IsClusteredIndexComputed' - + ' FROM sys.objects objects' - + ' LEFT OUTER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' - + ' WHERE objects.[type] IN(''U'',''V'')' - + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' - + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END - - INSERT INTO @tmpObjectProperties (ObjectID, HasClusteredColumnstore, HasNonClusteredColumnstore, IsClusteredIndexComputed) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand - SET @Error = @@ERROR - IF @Error <> 0 + IF @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) BEGIN - SET @ReturnCode = @Error + SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.partition_id = dm_db_partition_stats.partition_id' END + SET @CurrentCommand += ' WHERE Objects.ObjectType = ''U''' + + ' AND Indexes.IndexType IN(5,6)' + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= ' + CAST(@MinNumberOfPages AS nvarchar(max)) ELSE '' END + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= ' + CAST(@MaxNumberOfPages AS nvarchar(max)) ELSE '' END - -- Select index properties - SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT indexes.[object_id] AS ObjectID' - + ', indexes.index_id AS IndexID' - + ', 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] = indexes.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] = indexes.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] = indexes.[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] = indexes.object_id AND columns.is_filestream = 1) THEN 1 ELSE 0 END AS IsFileStream' - + ', ' + CASE WHEN (@Version >= 16 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' - + ', 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 OR index_columns.is_included_column = 1) 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.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND types.[name] = ''timestamp'') THEN 1 ELSE 0 END AS IsTimestamp' - + ' FROM sys.indexes indexes' - + ' INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id]' - + ' LEFT OUTER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' - + ' WHERE objects.[type] IN(''U'',''V'')' - + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' - + 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' - - INSERT INTO @tmpIndexProperties (ObjectID, IndexID, IsImageText, IsNewLOB, IsFileStream, IsColumnstoreOrdered, IsComputed, IsTimestamp) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -1841,81 +1927,60 @@ BEGIN SET @ReturnCode = @Error END - -- Select paused resumable index operations - SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT index_resumable_operations.object_id AS ObjectID' - + ', index_resumable_operations.index_id AS IndexID' - + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'index_resumable_operations.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END - + ' FROM sys.index_resumable_operations index_resumable_operations' - + ' WHERE index_resumable_operations.state_desc = ''PAUSED''' - - INSERT INTO @tmpResumableOperations (ObjectID, IndexID, PartitionNumber) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand - SET @Error = @@ERROR - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - END END - IF @UpdateStatistics IN('ALL','INDEX') + IF @UpdateStatistics IN('ALL','COLUMNS') BEGIN - -- Select statistics on indexes on tables + -- Select non-incremental column level statistics SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT stats.[object_id] AS ObjectID' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental AS IsIncremental' - + ' FROM sys.stats stats' - + ' INNER JOIN sys.indexes indexes ON stats.[object_id] = indexes.[object_id] AND stats.stats_id = indexes.index_id' - + ' INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id]' - + ' INNER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' - + ' WHERE objects.[type] = ''U''' - + ' AND tables.is_external = 0' - + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END - + ' AND indexes.[type] IN(1,2,5,6,7)' - + ' AND indexes.is_disabled = 0' - + ' AND indexes.is_hypothetical = 0' - - INSERT INTO @tmpIndexStatisticsProperties (ObjectID, StatisticsID, StatisticsName, [NoRecompute], IsIncremental) + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Stats.StatisticsID AS StatisticsID' + + ', Stats.StatisticsName AS StatisticsName' + + ', Stats.[NoRecompute] AS NoRecompute' + + ', Stats.IsIncremental AS IsIncremental' + + ', NULL AS PartitionNumber' + + ' FROM #Stats Stats' + + ' INNER JOIN #Objects Objects ON Stats.ObjectID = Objects.ObjectID' + + ' WHERE Stats.IsIndex = 0' + + ' AND Stats.IsIncremental = 0' + + ' AND Objects.IsClusteredIndexDisabled = 0' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 BEGIN SET @ReturnCode = @Error END - END - IF @UpdateStatistics IN('ALL','COLUMNS') - BEGIN - -- Select column level statistics + -- Select incremental column level statistics 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' - + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental AS IsIncremental' - + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'dm_db_incremental_stats_properties.partition_number' ELSE 'NULL' END + ' AS PartitionNumber' - + ' 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]' + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Stats.StatisticsID AS StatisticsID' + + ', Stats.StatisticsName AS StatisticsName' + + ', Stats.[NoRecompute] AS NoRecompute' + + ', Stats.IsIncremental AS IsIncremental' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_number' ELSE 'NULL' END + ' AS PartitionNumber' + + ' FROM #Stats Stats' + + ' INNER JOIN #Objects Objects ON Stats.ObjectID = Objects.ObjectID' IF @PartitionLevel = 'Y' BEGIN - SET @CurrentCommand += ' OUTER APPLY sys.dm_db_incremental_stats_properties(stats.object_id, stats.stats_id) dm_db_incremental_stats_properties' + SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON partitions.[object_id] = Stats.ObjectID AND partitions.index_id IN (0, 1)' END - SET @CurrentCommand += ' WHERE objects.[type] IN(''U'',''V'')' - + ' AND (tables.is_memory_optimized = 0 OR tables.is_memory_optimized IS NULL)' - + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' - + 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)' - + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes2 WHERE indexes2.[object_id] = stats.[object_id] AND indexes2.type = 1 AND indexes2.is_disabled = 1)' + SET @CurrentCommand += ' WHERE Objects.IsMemoryOptimized = 0' + + ' AND Stats.IsIndex = 0' + + ' AND Stats.IsIncremental = 1' + + ' AND Objects.IsClusteredIndexDisabled = 0' INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand @@ -1924,61 +1989,8 @@ BEGIN BEGIN SET @ReturnCode = @Error END - - -- Select column level statistics for memory optimized tables - 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' - + ', tables.is_memory_optimized AS IsMemoryOptimized' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental AS IsIncremental' - + ' 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]' - + ' INNER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' - + ' WHERE objects.[type] = ''U''' - + ' AND tables.is_memory_optimized = 1' - + 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)' - - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand - SET @Error = @@ERROR - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - END END - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.StatisticsID = tmpIndexStatisticsProperties.StatisticsID, - tmpIndexesStatistics.StatisticsName = tmpIndexStatisticsProperties.StatisticsName, - tmpIndexesStatistics.[NoRecompute] = tmpIndexStatisticsProperties.[NoRecompute], - tmpIndexesStatistics.IsIncremental = tmpIndexStatisticsProperties.IsIncremental - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @tmpIndexStatisticsProperties tmpIndexStatisticsProperties ON tmpIndexesStatistics.ObjectID = tmpIndexStatisticsProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexStatisticsProperties.StatisticsID - OPTION (RECOMPILE) - - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.IsImageText = tmpIndexProperties.IsImageText, - tmpIndexesStatistics.IsNewLOB = tmpIndexProperties.IsNewLOB, - tmpIndexesStatistics.IsFileStream = tmpIndexProperties.IsFileStream, - tmpIndexesStatistics.HasClusteredColumnstore = tmpObjectProperties.HasClusteredColumnstore, - tmpIndexesStatistics.HasNonClusteredColumnstore = tmpObjectProperties.HasNonClusteredColumnstore, - tmpIndexesStatistics.IsClusteredIndexComputed = tmpObjectProperties.IsClusteredIndexComputed, - tmpIndexesStatistics.IsColumnstoreOrdered = tmpIndexProperties.IsColumnstoreOrdered, - tmpIndexesStatistics.IsComputed = tmpIndexProperties.IsComputed, - tmpIndexesStatistics.IsTimestamp = tmpIndexProperties.IsTimestamp - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @tmpObjectProperties tmpObjectProperties ON tmpIndexesStatistics.ObjectID = tmpObjectProperties.ObjectID - INNER JOIN @tmpIndexProperties tmpIndexProperties ON tmpIndexesStatistics.ObjectID = tmpIndexProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexProperties.IndexID - OPTION (RECOMPILE) - UPDATE tmpIndexesStatistics SET tmpIndexesStatistics.ResumableIndexOperation = 1 FROM @tmpIndexesStatistics tmpIndexesStatistics @@ -2088,10 +2100,8 @@ BEGIN @CurrentAllowPageLocks = AllowPageLocks, @CurrentHasFilter = HasFilter, @CurrentIsImageText = IsImageText, - @CurrentIsNewLOB = IsNewLOB, @CurrentIsFileStream = IsFileStream, @CurrentHasClusteredColumnstore = HasClusteredColumnstore, - @CurrentHasNonClusteredColumnstore = HasNonClusteredColumnstore, @CurrentIsColumnstoreOrdered = IsColumnstoreOrdered, @CurrentIsComputed = IsComputed, @CurrentIsClusteredIndexComputed = IsClusteredIndexComputed, @@ -2211,13 +2221,13 @@ BEGIN IF @EngineEdition IN (3, 5, 8) AND NOT (@CurrentOnReadOnlyFileGroup = 1) AND NOT (@CurrentIsMemoryOptimized = 1) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1 AND @CurrentIsImageText IS NOT NULL) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1 AND @CurrentIsFileStream IS NOT NULL) AND NOT (@CurrentIndexType = 3) AND NOT (@CurrentIndexType = 4) AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @CurrentHasClusteredColumnstore IS NOT NULL AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND @CurrentIsColumnstoreOrdered IS NOT NULL AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) BEGIN INSERT INTO @CurrentActionsAllowed ([Action]) VALUES ('INDEX_REBUILD_ONLINE') @@ -2269,15 +2279,13 @@ BEGIN BEGIN 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 @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasNonClusteredColumnstore: ' + CASE WHEN @CurrentHasNonClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasNonClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Resumable = 'Y' SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Resumable = 'Y' AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Resumable = 'Y' SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsImageText IS NOT NULL SET @CurrentComment += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsFileStream IS NOT NULL SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentHasClusteredColumnstore IS NOT NULL AND @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsColumnstoreOrdered IS NOT NULL AND @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsComputed IS NOT NULL SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsClusteredIndexComputed IS NOT NULL AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsTimestamp IS NOT NULL SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 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(max)),'N/A') + ', ' @@ -2363,10 +2371,10 @@ BEGIN IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 AND @CurrentHasClusteredColumnstore = 0 THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END + SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL) 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 @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 AND @CurrentHasClusteredColumnstore = 0) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL)) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max)) @@ -2655,10 +2663,8 @@ BEGIN SET @CurrentIndexExists = NULL SET @CurrentStatisticsExists = NULL SET @CurrentIsImageText = NULL - SET @CurrentIsNewLOB = NULL SET @CurrentIsFileStream = NULL SET @CurrentHasClusteredColumnstore = NULL - SET @CurrentHasNonClusteredColumnstore = NULL SET @CurrentIsColumnstoreOrdered = NULL SET @CurrentIsComputed = NULL SET @CurrentIsClusteredIndexComputed = NULL @@ -2743,9 +2749,10 @@ BEGIN SET @CurrentCommand = NULL DELETE FROM @tmpIndexesStatistics - DELETE FROM @tmpObjectProperties - DELETE FROM @tmpIndexProperties - DELETE FROM @tmpIndexStatisticsProperties + + TRUNCATE TABLE #Objects + TRUNCATE TABLE #Indexes + TRUNCATE TABLE #Stats DELETE FROM @tmpResumableOperations END -- End of database loop diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index d7e783dc..027c61d9 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: 2026-07-12 10:00:16 +Version: 2026-07-14 22:07:20 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-12 10:00:16 //-- + --// Version: 2026-07-14 22:07:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-12 10:00:16 //-- + --// Version: 2026-07-14 22:07:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3303,7 +3303,7 @@ BEGIN BEGIN SET @CurrentBackupType = 'DIFF' END - IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / @CurrentAllocatedExtentPageCount * 100 >= @MinModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) + IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / NULLIF(@CurrentAllocatedExtentPageCount, 0) * 100 >= @MinModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) BEGIN SET @CurrentBackupType = 'FULL' END @@ -4873,7 +4873,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-12 10:00:16 //-- + --// Version: 2026-07-14 22:07:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6842,7 +6842,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-12 10:00:16 //-- + --// Version: 2026-07-14 22:07:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6927,10 +6927,8 @@ BEGIN DECLARE @CurrentIndexExists bit DECLARE @CurrentStatisticsExists bit DECLARE @CurrentIsImageText bit - DECLARE @CurrentIsNewLOB bit DECLARE @CurrentIsFileStream bit DECLARE @CurrentHasClusteredColumnstore bit - DECLARE @CurrentHasNonClusteredColumnstore bit DECLARE @CurrentIsColumnstoreOrdered bit DECLARE @CurrentIsComputed bit DECLARE @CurrentIsClusteredIndexComputed bit @@ -6987,10 +6985,8 @@ BEGIN AllowPageLocks bit, HasFilter bit, IsImageText bit, - IsNewLOB bit, IsFileStream bit, HasClusteredColumnstore bit, - HasNonClusteredColumnstore bit, IsColumnstoreOrdered bit, IsComputed bit, IsClusteredIndexComputed bit, @@ -7010,28 +7006,53 @@ BEGIN Completed bit DEFAULT 0, PRIMARY KEY (Selected, Completed, [Order], ID)) - DECLARE @tmpObjectProperties TABLE (ObjectID int NOT NULL, - HasClusteredColumnstore bit, - HasNonClusteredColumnstore bit, - IsClusteredIndexComputed bit, - PRIMARY KEY (ObjectID)) - - DECLARE @tmpIndexProperties TABLE (ObjectID int NOT NULL, - IndexID int NOT NULL, - IsImageText bit, - IsNewLOB bit, - IsFileStream bit, - IsColumnstoreOrdered bit, - IsComputed bit, - IsTimestamp bit, - PRIMARY KEY (ObjectID, IndexID)) - - DECLARE @tmpIndexStatisticsProperties TABLE (ObjectID int NOT NULL, - StatisticsID int NOT NULL, - StatisticsName nvarchar(128), - [NoRecompute] bit, - IsIncremental bit, - PRIMARY KEY (ObjectID, StatisticsID)) + DROP TABLE IF EXISTS #SelectedIndexes + + CREATE TABLE #SelectedIndexes (DatabaseName nvarchar(max) COLLATE DATABASE_DEFAULT, + SchemaName nvarchar(max) COLLATE DATABASE_DEFAULT, + ObjectName nvarchar(max) COLLATE DATABASE_DEFAULT, + IndexName nvarchar(max) COLLATE DATABASE_DEFAULT, + StartPosition int, + Selected bit) + + DROP TABLE IF EXISTS #Objects + + CREATE TABLE #Objects (ObjectID int NOT NULL, + SchemaID int, + SchemaName nvarchar(128) COLLATE DATABASE_DEFAULT, + ObjectName nvarchar(128) COLLATE DATABASE_DEFAULT, + ObjectType nvarchar(2) COLLATE DATABASE_DEFAULT, + IsMemoryOptimized bit, + HasClusteredColumnstore bit, + IsClusteredIndexComputed bit, + IsClusteredIndexDisabled bit, + PRIMARY KEY (ObjectID)) + + DROP TABLE IF EXISTS #Indexes + + CREATE TABLE #Indexes (ObjectID int NOT NULL, + IndexID int NOT NULL, + IndexName nvarchar(128) COLLATE DATABASE_DEFAULT, + IndexType int, + DataSpaceID int, + AllowPageLocks bit, + HasFilter bit, + IsImageText bit, + IsFileStream bit, + IsColumnstoreOrdered bit, + IsComputed bit, + IsTimestamp bit, + PRIMARY KEY (ObjectID, IndexID)) + + DROP TABLE IF EXISTS #Stats + + CREATE TABLE #Stats (ObjectID int NOT NULL, + StatisticsID int NOT NULL, + StatisticsName nvarchar(128) COLLATE DATABASE_DEFAULT, + [NoRecompute] bit, + IsIncremental bit, + IsIndex bit, + PRIMARY KEY (ObjectID, StatisticsID)) DECLARE @tmpResumableOperations TABLE (ObjectID int NOT NULL, IndexID int NOT NULL, @@ -7084,6 +7105,8 @@ BEGIN DECLARE @IsHadrEnabled bit = CAST(SERVERPROPERTY('IsHadrEnabled') AS bit) DECLARE @ServerName nvarchar(max) = CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + DECLARE @Collation nvarchar(128) = CAST(DATABASEPROPERTYEX(DB_NAME(),'Collation') AS nvarchar(128)) + DECLARE @Version numeric(18,10) = CAST(PARSENAME(@ProductVersion,4) + '.' + PARSENAME(@ProductVersion,3) + PARSENAME(@ProductVersion,2) AS numeric(18,10)) IF @EngineEdition = 8 AND @ProductVersion = '12.0.2000.8' AND @ProductUpdateType = 'CU' @@ -7530,6 +7553,10 @@ BEGIN FROM Indexes4 OPTION (MAXRECURSION 0) + INSERT INTO #SelectedIndexes (DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected) + SELECT DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected + FROM @SelectedIndexes + ---------------------------------------------------------------------------------------------------- --// Select actions //-- ---------------------------------------------------------------------------------------------------- @@ -8438,6 +8465,99 @@ BEGIN IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN + -- Select objects + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT objects.[object_id] AS ObjectID' + + ', objects.[schema_id] AS SchemaID' + + ', schemas.[name] AS SchemaName' + + ', objects.[name] AS ObjectName' + + ', RTRIM(objects.[type]) AS ObjectType' + + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') THEN 'CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 5) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS HasClusteredColumnstore' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') AND @Resumable = 'Y' THEN '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.indexes indexes2 ON index_columns.object_id = indexes2.object_id AND index_columns.index_id = indexes2.index_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND indexes2.[type] = 1 AND index_columns.object_id = objects.object_id) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsClusteredIndexComputed' + + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 1 AND is_disabled = 1) THEN 1 ELSE 0 END AS IsClusteredIndexDisabled' + + ' 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 (tables.is_external = 0 OR tables.is_external IS NULL)' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + IF @Indexes IS NOT NULL AND EXISTS(SELECT * FROM @SelectedIndexes WHERE Selected = 1) AND NOT EXISTS(SELECT * FROM @SelectedIndexes WHERE Selected = 1 AND DatabaseName = '%' AND SchemaName = '%' AND ObjectName = '%') + BEGIN + SET @CurrentCommand += ' AND EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes WHERE @ParamDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND schemas.[name] LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND objects.[name] LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND SelectedIndexes.Selected = 1)' + END + + INSERT INTO #Objects (ObjectID, SchemaID, SchemaName, ObjectName, ObjectType, IsMemoryOptimized, HasClusteredColumnstore, IsClusteredIndexComputed, IsClusteredIndexDisabled) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max)', @ParamDatabaseName = @CurrentDatabaseName + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select indexes + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT indexes.[object_id] AS ObjectID' + + ', indexes.index_id AS IndexID' + + ', indexes.[name] AS IndexName' + + ', indexes.[type] AS IndexType' + + ', indexes.data_space_id AS DataSpaceID' + + ', indexes.allow_page_locks AS AllowPageLocks' + + ', indexes.has_filter AS HasFilter' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') THEN '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] = indexes.object_id AND types.name IN(''image'',''text'',''ntext'')) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsImageText' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') THEN 'CASE WHEN indexes.[type] = 1 AND EXISTS(SELECT * FROM sys.columns columns WHERE columns.[object_id] = indexes.object_id AND columns.is_filestream = 1) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsFileStream' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') AND (@Version >= 16 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsColumnstoreOrdered' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') AND @Resumable = 'Y' THEN '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 OR index_columns.is_included_column = 1) 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' ELSE 'NULL' END + ' AS IsComputed' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') AND @Resumable = 'Y' THEN '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.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND types.[name] = ''timestamp'') THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsTimestamp' + + ' FROM sys.indexes indexes' + + ' INNER JOIN #Objects Objects ON indexes.[object_id] = Objects.ObjectID' + + ' AND indexes.[type] IN(1,2,3,4,5,6,7)' + + ' AND indexes.is_disabled = 0' + + ' AND indexes.is_hypothetical = 0' + + INSERT INTO #Indexes (ObjectID, IndexID, IndexName, IndexType, DataSpaceID, AllowPageLocks, HasFilter, IsImageText, IsFileStream, IsColumnstoreOrdered, IsComputed, IsTimestamp) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select statistics + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT stats.[object_id] AS ObjectID' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental AS IsIncremental' + + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id) THEN 1 ELSE 0 END AS IsIndex' + + ' FROM sys.stats stats' + + ' INNER JOIN #Objects Objects ON stats.[object_id] = Objects.ObjectID' + + INSERT INTO #Stats (ObjectID, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, IsIndex) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select paused resumable index operations + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT index_resumable_operations.object_id AS ObjectID' + + ', index_resumable_operations.index_id AS IndexID' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'index_resumable_operations.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END + + ' FROM sys.index_resumable_operations index_resumable_operations' + + ' WHERE index_resumable_operations.state_desc = ''PAUSED''' + + INSERT INTO @tmpResumableOperations (ObjectID, IndexID, PartitionNumber) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') BEGIN -- Check if there are read-only filegroups in the database @@ -8450,48 +8570,53 @@ BEGIN SET @ReturnCode = @Error END - -- Select indexes on tables + -- Select clustered, nonclustered and hash indexes 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' - + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' - + ', indexes.index_id AS IndexID' - + ', indexes.[name] AS IndexName' - + ', indexes.[type] AS IndexType' - + ', indexes.allow_page_locks AS AllowPageLocks' - + ', indexes.has_filter AS HasFilter' - + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', 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' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Indexes.IndexID AS IndexID' + + ', Indexes.IndexName AS IndexName' + + ', Indexes.IndexType AS IndexType' + + ', Indexes.AllowPageLocks AS AllowPageLocks' + + ', Indexes.HasFilter AS HasFilter' + + ', Indexes.IsImageText AS IsImageText' + + ', Indexes.IsFileStream AS IsFileStream' + + ', Objects.HasClusteredColumnstore AS HasClusteredColumnstore' + + ', Indexes.IsColumnstoreOrdered AS IsColumnstoreOrdered' + + ', Indexes.IsComputed AS IsComputed' + + ', Objects.IsClusteredIndexComputed AS IsClusteredIndexComputed' + + ', Indexes.IsTimestamp AS IsTimestamp' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON Indexes.DataSpaceID = 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.ObjectID AND indexes2.[index_id] = Indexes.IndexID' + 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.DataSpaceID = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND Indexes.ObjectID = indexes2.[object_id] AND Indexes.IndexID = indexes2.index_id) THEN 1' + + ' WHEN Indexes.IndexType = 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.ObjectID) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + ', 0 AS ResumableIndexOperation' + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.StatisticsID AS StatisticsID' ELSE ', NULL AS StatisticsID' END + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.StatisticsName AS StatisticsName' ELSE ', NULL AS StatisticsName' END + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.[NoRecompute] AS NoRecompute' ELSE ', NULL AS NoRecompute' END + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.IsIncremental AS IsIncremental' ELSE ', NULL AS IsIncremental' END + ', ' + 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 - + ' 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.tables tables ON objects.[object_id] = tables.[object_id]' + + ' FROM #Indexes Indexes' + + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ' INNER JOIN #Stats Stats ON Indexes.ObjectID = Stats.ObjectID AND Indexes.IndexID = Stats.StatisticsID' ELSE '' END IF @PartitionLevel = 'Y' BEGIN - SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' + SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON Indexes.ObjectID = partitions.[object_id] AND Indexes.IndexID = partitions.index_id' END - IF @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) BEGIN SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.partition_id = dm_db_partition_stats.partition_id' END - SET @CurrentCommand += ' WHERE objects.[type] = ''U''' - + ' AND tables.is_external = 0' - + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END - + ' AND indexes.[type] IN(1,2,5,6,7)' - + ' AND indexes.is_disabled = 0' - + ' AND indexes.is_hypothetical = 0' + SET @CurrentCommand += ' WHERE Objects.ObjectType IN(''U'',''V'')' + + ' AND Indexes.IndexType IN(1,2,7)' + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= ' + CAST(@MinNumberOfPages AS nvarchar(max)) ELSE '' END + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= ' + CAST(@MaxNumberOfPages AS nvarchar(max)) ELSE '' END - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation, PartitionID, PartitionNumber) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -8499,34 +8624,35 @@ BEGIN SET @ReturnCode = @Error END - -- Select special indexes (XML and spatial) + -- Select XML and spatial indexes 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' - + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' - + ', indexes.index_id AS IndexID' - + ', indexes.[name] AS IndexName' - + ', indexes.[type] AS IndexType' - + ', indexes.allow_page_locks AS AllowPageLocks' - + ', indexes.has_filter AS HasFilter' - + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', 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) 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 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Indexes.IndexID AS IndexID' + + ', Indexes.IndexName AS IndexName' + + ', Indexes.IndexType AS IndexType' + + ', Indexes.AllowPageLocks AS AllowPageLocks' + + ', Indexes.HasFilter AS HasFilter' + + ', Indexes.IsImageText AS IsImageText' + + ', Indexes.IsFileStream AS IsFileStream' + + ', Objects.HasClusteredColumnstore AS HasClusteredColumnstore' + + ', Indexes.IsColumnstoreOrdered AS IsColumnstoreOrdered' + + ', Indexes.IsComputed AS IsComputed' + + ', Objects.IsClusteredIndexComputed AS IsClusteredIndexComputed' + + ', Indexes.IsTimestamp AS IsTimestamp' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON Indexes.DataSpaceID = 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.ObjectID AND indexes2.[index_id] = Indexes.IndexID) THEN 1' + + ' WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.filegroups filegroups ON Indexes.DataSpaceID = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND Indexes.ObjectID = indexes2.[object_id] AND Indexes.IndexID = indexes2.index_id) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + ', 0 AS ResumableIndexOperation' - + ' 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.tables tables ON objects.[object_id] = tables.[object_id]' - + ' WHERE objects.[type] = ''U''' - + ' AND tables.is_external = 0' - + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END - + ' AND indexes.[type] IN(3,4)' - + ' AND indexes.is_disabled = 0' - + ' AND indexes.is_hypothetical = 0' - - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation) + + ' FROM #Indexes Indexes' + + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + + ' WHERE Objects.ObjectType = ''U''' + + ' AND Indexes.IndexType IN(3,4)' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -8534,92 +8660,52 @@ BEGIN SET @ReturnCode = @Error END - -- Select indexes on views + -- Select columnstore indexes 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 IsMemoryOptimized' - + ', indexes.index_id AS IndexID' - + ', indexes.[name] AS IndexName' - + ', indexes.[type] AS IndexType' - + ', indexes.allow_page_locks AS AllowPageLocks' - + ', indexes.has_filter AS HasFilter' - + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', 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' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Indexes.IndexID AS IndexID' + + ', Indexes.IndexName AS IndexName' + + ', Indexes.IndexType AS IndexType' + + ', Indexes.AllowPageLocks AS AllowPageLocks' + + ', Indexes.HasFilter AS HasFilter' + + ', Indexes.IsImageText AS IsImageText' + + ', Indexes.IsFileStream AS IsFileStream' + + ', Objects.HasClusteredColumnstore AS HasClusteredColumnstore' + + ', Indexes.IsColumnstoreOrdered AS IsColumnstoreOrdered' + + ', Indexes.IsComputed AS IsComputed' + + ', Objects.IsClusteredIndexComputed AS IsClusteredIndexComputed' + + ', Indexes.IsTimestamp AS IsTimestamp' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON Indexes.DataSpaceID = 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.ObjectID AND indexes2.[index_id] = Indexes.IndexID' + 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.DataSpaceID = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND Indexes.ObjectID = indexes2.[object_id] AND Indexes.IndexID = indexes2.index_id) THEN 1' + + ' WHEN Indexes.IndexType = 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.ObjectID) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + ', 0 AS ResumableIndexOperation' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental AS IsIncremental' + + ', NULL AS StatisticsID' + + ', NULL AS StatisticsName' + + ', NULL AS NoRecompute' + + ', NULL 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 - + ' 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.stats stats ON indexes.[object_id] = stats.[object_id] AND indexes.[index_id] = stats.[stats_id]' + + ' FROM #Indexes Indexes' + + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' IF @PartitionLevel = 'Y' BEGIN - SET @CurrentCommand += ' LEFT OUTER JOIN sys.partitions partitions ON indexes.[object_id] = partitions.[object_id] AND indexes.index_id = partitions.index_id' + SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON Indexes.ObjectID = partitions.[object_id] AND Indexes.IndexID = partitions.index_id' END - SET @CurrentCommand += ' WHERE objects.[type] = ''V''' - + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END - + ' AND indexes.[type] IN(1,2)' - + ' AND indexes.is_disabled = 0' - + ' AND indexes.is_hypothetical = 0' - - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand - SET @Error = @@ERROR - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - END - - -- Select object properties - SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT objects.[object_id] AS ObjectID' - + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 5) THEN 1 ELSE 0 END AS HasClusteredColumnstore' - + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 6) THEN 1 ELSE 0 END AS HasNonClusteredColumnstore' - + ', 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.indexes indexes2 ON index_columns.object_id = indexes2.object_id AND index_columns.index_id = indexes2.index_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND indexes2.[type] = 1 AND index_columns.object_id = objects.object_id) THEN 1 ELSE 0 END AS IsClusteredIndexComputed' - + ' FROM sys.objects objects' - + ' LEFT OUTER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' - + ' WHERE objects.[type] IN(''U'',''V'')' - + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' - + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END - - INSERT INTO @tmpObjectProperties (ObjectID, HasClusteredColumnstore, HasNonClusteredColumnstore, IsClusteredIndexComputed) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand - SET @Error = @@ERROR - IF @Error <> 0 + IF @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) BEGIN - SET @ReturnCode = @Error + SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.partition_id = dm_db_partition_stats.partition_id' END + SET @CurrentCommand += ' WHERE Objects.ObjectType = ''U''' + + ' AND Indexes.IndexType IN(5,6)' + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= ' + CAST(@MinNumberOfPages AS nvarchar(max)) ELSE '' END + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= ' + CAST(@MaxNumberOfPages AS nvarchar(max)) ELSE '' END - -- Select index properties - SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT indexes.[object_id] AS ObjectID' - + ', indexes.index_id AS IndexID' - + ', 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] = indexes.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] = indexes.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] = indexes.[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] = indexes.object_id AND columns.is_filestream = 1) THEN 1 ELSE 0 END AS IsFileStream' - + ', ' + CASE WHEN (@Version >= 16 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE '0' END + ' AS IsColumnstoreOrdered' - + ', 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 OR index_columns.is_included_column = 1) 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.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND types.[name] = ''timestamp'') THEN 1 ELSE 0 END AS IsTimestamp' - + ' FROM sys.indexes indexes' - + ' INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id]' - + ' LEFT OUTER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' - + ' WHERE objects.[type] IN(''U'',''V'')' - + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' - + 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' - - INSERT INTO @tmpIndexProperties (ObjectID, IndexID, IsImageText, IsNewLOB, IsFileStream, IsColumnstoreOrdered, IsComputed, IsTimestamp) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -8627,81 +8713,60 @@ BEGIN SET @ReturnCode = @Error END - -- Select paused resumable index operations - SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT index_resumable_operations.object_id AS ObjectID' - + ', index_resumable_operations.index_id AS IndexID' - + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'index_resumable_operations.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END - + ' FROM sys.index_resumable_operations index_resumable_operations' - + ' WHERE index_resumable_operations.state_desc = ''PAUSED''' - - INSERT INTO @tmpResumableOperations (ObjectID, IndexID, PartitionNumber) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand - SET @Error = @@ERROR - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - END END - IF @UpdateStatistics IN('ALL','INDEX') + IF @UpdateStatistics IN('ALL','COLUMNS') BEGIN - -- Select statistics on indexes on tables + -- Select non-incremental column level statistics SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' - + ' SELECT stats.[object_id] AS ObjectID' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental AS IsIncremental' - + ' FROM sys.stats stats' - + ' INNER JOIN sys.indexes indexes ON stats.[object_id] = indexes.[object_id] AND stats.stats_id = indexes.index_id' - + ' INNER JOIN sys.objects objects ON indexes.[object_id] = objects.[object_id]' - + ' INNER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' - + ' WHERE objects.[type] = ''U''' - + ' AND tables.is_external = 0' - + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END - + ' AND indexes.[type] IN(1,2,5,6,7)' - + ' AND indexes.is_disabled = 0' - + ' AND indexes.is_hypothetical = 0' - - INSERT INTO @tmpIndexStatisticsProperties (ObjectID, StatisticsID, StatisticsName, [NoRecompute], IsIncremental) + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Stats.StatisticsID AS StatisticsID' + + ', Stats.StatisticsName AS StatisticsName' + + ', Stats.[NoRecompute] AS NoRecompute' + + ', Stats.IsIncremental AS IsIncremental' + + ', NULL AS PartitionNumber' + + ' FROM #Stats Stats' + + ' INNER JOIN #Objects Objects ON Stats.ObjectID = Objects.ObjectID' + + ' WHERE Stats.IsIndex = 0' + + ' AND Stats.IsIncremental = 0' + + ' AND Objects.IsClusteredIndexDisabled = 0' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 BEGIN SET @ReturnCode = @Error END - END - IF @UpdateStatistics IN('ALL','COLUMNS') - BEGIN - -- Select column level statistics + -- Select incremental column level statistics 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' - + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental AS IsIncremental' - + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'dm_db_incremental_stats_properties.partition_number' ELSE 'NULL' END + ' AS PartitionNumber' - + ' 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]' + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Stats.StatisticsID AS StatisticsID' + + ', Stats.StatisticsName AS StatisticsName' + + ', Stats.[NoRecompute] AS NoRecompute' + + ', Stats.IsIncremental AS IsIncremental' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_number' ELSE 'NULL' END + ' AS PartitionNumber' + + ' FROM #Stats Stats' + + ' INNER JOIN #Objects Objects ON Stats.ObjectID = Objects.ObjectID' IF @PartitionLevel = 'Y' BEGIN - SET @CurrentCommand += ' OUTER APPLY sys.dm_db_incremental_stats_properties(stats.object_id, stats.stats_id) dm_db_incremental_stats_properties' + SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON partitions.[object_id] = Stats.ObjectID AND partitions.index_id IN (0, 1)' END - SET @CurrentCommand += ' WHERE objects.[type] IN(''U'',''V'')' - + ' AND (tables.is_memory_optimized = 0 OR tables.is_memory_optimized IS NULL)' - + ' AND (tables.is_external = 0 OR tables.is_external IS NULL)' - + 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)' - + ' AND NOT EXISTS(SELECT * FROM sys.indexes indexes2 WHERE indexes2.[object_id] = stats.[object_id] AND indexes2.type = 1 AND indexes2.is_disabled = 1)' + SET @CurrentCommand += ' WHERE Objects.IsMemoryOptimized = 0' + + ' AND Stats.IsIndex = 0' + + ' AND Stats.IsIncremental = 1' + + ' AND Objects.IsClusteredIndexDisabled = 0' INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand @@ -8710,61 +8775,8 @@ BEGIN BEGIN SET @ReturnCode = @Error END - - -- Select column level statistics for memory optimized tables - 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' - + ', tables.is_memory_optimized AS IsMemoryOptimized' - + ', stats.stats_id AS StatisticsID' - + ', stats.name AS StatisticsName' - + ', stats.no_recompute AS NoRecompute' - + ', stats.is_incremental AS IsIncremental' - + ' 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]' - + ' INNER JOIN sys.tables tables ON objects.[object_id] = tables.[object_id]' - + ' WHERE objects.[type] = ''U''' - + ' AND tables.is_memory_optimized = 1' - + 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)' - - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand - SET @Error = @@ERROR - IF @Error <> 0 - BEGIN - SET @ReturnCode = @Error - END END - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.StatisticsID = tmpIndexStatisticsProperties.StatisticsID, - tmpIndexesStatistics.StatisticsName = tmpIndexStatisticsProperties.StatisticsName, - tmpIndexesStatistics.[NoRecompute] = tmpIndexStatisticsProperties.[NoRecompute], - tmpIndexesStatistics.IsIncremental = tmpIndexStatisticsProperties.IsIncremental - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @tmpIndexStatisticsProperties tmpIndexStatisticsProperties ON tmpIndexesStatistics.ObjectID = tmpIndexStatisticsProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexStatisticsProperties.StatisticsID - OPTION (RECOMPILE) - - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.IsImageText = tmpIndexProperties.IsImageText, - tmpIndexesStatistics.IsNewLOB = tmpIndexProperties.IsNewLOB, - tmpIndexesStatistics.IsFileStream = tmpIndexProperties.IsFileStream, - tmpIndexesStatistics.HasClusteredColumnstore = tmpObjectProperties.HasClusteredColumnstore, - tmpIndexesStatistics.HasNonClusteredColumnstore = tmpObjectProperties.HasNonClusteredColumnstore, - tmpIndexesStatistics.IsClusteredIndexComputed = tmpObjectProperties.IsClusteredIndexComputed, - tmpIndexesStatistics.IsColumnstoreOrdered = tmpIndexProperties.IsColumnstoreOrdered, - tmpIndexesStatistics.IsComputed = tmpIndexProperties.IsComputed, - tmpIndexesStatistics.IsTimestamp = tmpIndexProperties.IsTimestamp - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @tmpObjectProperties tmpObjectProperties ON tmpIndexesStatistics.ObjectID = tmpObjectProperties.ObjectID - INNER JOIN @tmpIndexProperties tmpIndexProperties ON tmpIndexesStatistics.ObjectID = tmpIndexProperties.ObjectID AND tmpIndexesStatistics.IndexID = tmpIndexProperties.IndexID - OPTION (RECOMPILE) - UPDATE tmpIndexesStatistics SET tmpIndexesStatistics.ResumableIndexOperation = 1 FROM @tmpIndexesStatistics tmpIndexesStatistics @@ -8874,10 +8886,8 @@ BEGIN @CurrentAllowPageLocks = AllowPageLocks, @CurrentHasFilter = HasFilter, @CurrentIsImageText = IsImageText, - @CurrentIsNewLOB = IsNewLOB, @CurrentIsFileStream = IsFileStream, @CurrentHasClusteredColumnstore = HasClusteredColumnstore, - @CurrentHasNonClusteredColumnstore = HasNonClusteredColumnstore, @CurrentIsColumnstoreOrdered = IsColumnstoreOrdered, @CurrentIsComputed = IsComputed, @CurrentIsClusteredIndexComputed = IsClusteredIndexComputed, @@ -8997,13 +9007,13 @@ BEGIN IF @EngineEdition IN (3, 5, 8) AND NOT (@CurrentOnReadOnlyFileGroup = 1) AND NOT (@CurrentIsMemoryOptimized = 1) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1 AND @CurrentIsImageText IS NOT NULL) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1 AND @CurrentIsFileStream IS NOT NULL) AND NOT (@CurrentIndexType = 3) AND NOT (@CurrentIndexType = 4) AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @CurrentHasClusteredColumnstore IS NOT NULL AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND @CurrentIsColumnstoreOrdered IS NOT NULL AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) BEGIN INSERT INTO @CurrentActionsAllowed ([Action]) VALUES ('INDEX_REBUILD_ONLINE') @@ -9055,15 +9065,13 @@ BEGIN BEGIN 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 @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasNonClusteredColumnstore: ' + CASE WHEN @CurrentHasNonClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasNonClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Resumable = 'Y' SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Resumable = 'Y' AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Resumable = 'Y' SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsImageText IS NOT NULL SET @CurrentComment += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsFileStream IS NOT NULL SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentHasClusteredColumnstore IS NOT NULL AND @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsColumnstoreOrdered IS NOT NULL AND @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsComputed IS NOT NULL SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsClusteredIndexComputed IS NOT NULL AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsTimestamp IS NOT NULL SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' IF @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 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(max)),'N/A') + ', ' @@ -9149,10 +9157,10 @@ BEGIN IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND @CurrentIsComputed = 0 AND @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 AND @CurrentHasClusteredColumnstore = 0 THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END + SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL) 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 @CurrentIsClusteredIndexComputed = 0 AND @CurrentIsTimestamp = 0 AND @CurrentHasFilter = 0 AND @CurrentHasClusteredColumnstore = 0) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL)) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) SELECT 'MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max)) @@ -9441,10 +9449,8 @@ BEGIN SET @CurrentIndexExists = NULL SET @CurrentStatisticsExists = NULL SET @CurrentIsImageText = NULL - SET @CurrentIsNewLOB = NULL SET @CurrentIsFileStream = NULL SET @CurrentHasClusteredColumnstore = NULL - SET @CurrentHasNonClusteredColumnstore = NULL SET @CurrentIsColumnstoreOrdered = NULL SET @CurrentIsComputed = NULL SET @CurrentIsClusteredIndexComputed = NULL @@ -9529,9 +9535,10 @@ BEGIN SET @CurrentCommand = NULL DELETE FROM @tmpIndexesStatistics - DELETE FROM @tmpObjectProperties - DELETE FROM @tmpIndexProperties - DELETE FROM @tmpIndexStatisticsProperties + + TRUNCATE TABLE #Objects + TRUNCATE TABLE #Indexes + TRUNCATE TABLE #Stats DELETE FROM @tmpResumableOperations END -- End of database loop From c7540aed6c038ba2e4788339459082f09db1a990 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 15 Jul 2026 14:59:59 +0200 Subject: [PATCH 070/177] 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 8b876309..326ca711 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-14 22:07:20 //-- + --// Version: 2026-07-15 14:58:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 6922876c..da34cbef 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-14 22:07:20 //-- + --// Version: 2026-07-15 14:58:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 5d7d8df5..d1713e06 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-14 22:07:20 //-- + --// Version: 2026-07-15 14:58:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 1315c0c5..015f5804 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-14 22:07:20 //-- + --// Version: 2026-07-15 14:58:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2058,7 +2058,7 @@ BEGIN 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) + AND NOT EXISTS (SELECT * FROM #Objects WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName) IF @ErrorMessage IS NOT NULL BEGIN @@ -2074,7 +2074,7 @@ BEGIN 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) + AND NOT EXISTS (SELECT * FROM #Indexes Indexes INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID WHERE Objects.SchemaName = SelectedIndexes.SchemaName AND Objects.ObjectName = SelectedIndexes.ObjectName AND Indexes.IndexName = SelectedIndexes.IndexName) IF @ErrorMessage IS NOT NULL BEGIN diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 027c61d9..93155792 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: 2026-07-14 22:07:20 +Version: 2026-07-15 14:58:49 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-14 22:07:20 //-- + --// Version: 2026-07-15 14:58:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-14 22:07:20 //-- + --// Version: 2026-07-15 14:58:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4873,7 +4873,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-14 22:07:20 //-- + --// Version: 2026-07-15 14:58:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6842,7 +6842,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-14 22:07:20 //-- + --// Version: 2026-07-15 14:58:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8844,7 +8844,7 @@ BEGIN 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) + AND NOT EXISTS (SELECT * FROM #Objects WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName) IF @ErrorMessage IS NOT NULL BEGIN @@ -8860,7 +8860,7 @@ BEGIN 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) + AND NOT EXISTS (SELECT * FROM #Indexes Indexes INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID WHERE Objects.SchemaName = SelectedIndexes.SchemaName AND Objects.ObjectName = SelectedIndexes.ObjectName AND Indexes.IndexName = SelectedIndexes.IndexName) IF @ErrorMessage IS NOT NULL BEGIN From 9d48c671d97e0804db60d78ed055ae69887ca9c8 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 15 Jul 2026 22:30:24 +0200 Subject: [PATCH 071/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 79 +++++++++++++++++++++++++--------- MaintenanceSolution.sql | 87 +++++++++++++++++++++++++++----------- 5 files changed, 125 insertions(+), 47 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 326ca711..dd3cdc54 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-15 14:58:49 //-- + --// Version: 2026-07-15 22:27:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index da34cbef..ff916995 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-15 14:58:49 //-- + --// Version: 2026-07-15 22:27:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index d1713e06..3d3ec9d0 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-15 14:58:49 //-- + --// Version: 2026-07-15 22:27:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 015f5804..de3ad939 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-15 14:58:49 //-- + --// Version: 2026-07-15 22:27:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -289,6 +289,13 @@ BEGIN StartPosition int, Selected bit) + DECLARE @IncrementalStatsProperties TABLE (ObjectID int, + StatisticsID int, + PartitionNumber int, + [Rows] bigint, + ModificationCounter bigint, + PRIMARY KEY (ObjectID, StatisticsID, PartitionNumber)) + DECLARE @Actions TABLE ([Action] nvarchar(max)) INSERT INTO @Actions([Action]) VALUES('INDEX_REBUILD_ONLINE') @@ -2447,67 +2454,98 @@ BEGIN GOTO NoAction END CATCH - -- Does the object or partition have rows? - IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) + -- Check non-incremental statistics properties + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND NOT (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1) BEGIN SET @CurrentCommand = '' + + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' + + BEGIN TRY + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + + GOTO NoAction + END CATCH + END + + -- Check incremental statistics properties + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 + AND NOT EXISTS (SELECT * FROM @IncrementalStatsProperties WHERE ObjectID = @CurrentObjectID AND StatisticsID = @CurrentStatisticsID) + BEGIN + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 - BEGIN - SET @CurrentCommand += 'SELECT @ParamObjectHasRows = CASE WHEN EXISTS (SELECT * FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id IN (0,1) AND partition_number = @ParamPartitionNumber AND row_count > 0) THEN 1 ELSE 0 END' - END - ELSE BEGIN - SET @CurrentCommand += 'SELECT @ParamObjectHasRows = CASE WHEN EXISTS (SELECT * FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id IN (0,1) AND row_count > 0) THEN 1 ELSE 0 END' + SET @CurrentCommand += 'SELECT object_id, stats_id, partition_number, [rows], modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID)' END BEGIN TRY - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamPartitionNumber int, @ParamObjectHasRows bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamObjectHasRows = @CurrentObjectHasRows OUTPUT + INSERT INTO @IncrementalStatsProperties (ObjectID, StatisticsID, PartitionNumber, [Rows], ModificationCounter) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamStatisticsID int', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The row count could not be checked.' ELSE '' END + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 SET @ReturnCode = ERROR_NUMBER() END + GOTO NoAction END CATCH END - -- Has the data in the statistics been modified since the statistics was last updated? - IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) + SELECT @CurrentRowCount = [Rows], + @CurrentModificationCounter = [ModificationCounter] + FROM @IncrementalStatsProperties + WHERE ObjectID = @CurrentObjectID + AND StatisticsID = @CurrentStatisticsID + AND PartitionNumber = @CurrentPartitionNumber + + -- Check partition statistics + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentModificationCounter IS NULL BEGIN SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 BEGIN - SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' + SET @CurrentCommand += 'SELECT @ParamObjectHasRows = CASE WHEN EXISTS (SELECT * FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id IN (0,1) AND partition_number = @ParamPartitionNumber AND row_count > 0) THEN 1 ELSE 0 END' END ELSE BEGIN - SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' + SET @CurrentCommand += 'SELECT @ParamObjectHasRows = CASE WHEN EXISTS (SELECT * FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id IN (0,1) AND row_count > 0) THEN 1 ELSE 0 END' END BEGIN TRY - 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 + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamPartitionNumber int, @ParamObjectHasRows bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamObjectHasRows = @CurrentObjectHasRows OUTPUT END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The row count 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 SET @ReturnCode = ERROR_NUMBER() END - GOTO NoAction END CATCH END @@ -2754,6 +2792,7 @@ BEGIN TRUNCATE TABLE #Indexes TRUNCATE TABLE #Stats DELETE FROM @tmpResumableOperations + DELETE FROM @IncrementalStatsProperties END -- End of database loop diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 93155792..5673be00 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: 2026-07-15 14:58:49 +Version: 2026-07-15 22:27:18 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-15 14:58:49 //-- + --// Version: 2026-07-15 22:27:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-15 14:58:49 //-- + --// Version: 2026-07-15 22:27:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4873,7 +4873,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-15 14:58:49 //-- + --// Version: 2026-07-15 22:27:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6842,7 +6842,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-15 14:58:49 //-- + --// Version: 2026-07-15 22:27:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7075,6 +7075,13 @@ BEGIN StartPosition int, Selected bit) + DECLARE @IncrementalStatsProperties TABLE (ObjectID int, + StatisticsID int, + PartitionNumber int, + [Rows] bigint, + ModificationCounter bigint, + PRIMARY KEY (ObjectID, StatisticsID, PartitionNumber)) + DECLARE @Actions TABLE ([Action] nvarchar(max)) INSERT INTO @Actions([Action]) VALUES('INDEX_REBUILD_ONLINE') @@ -9233,67 +9240,98 @@ BEGIN GOTO NoAction END CATCH - -- Does the object or partition have rows? - IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) + -- Check non-incremental statistics properties + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND NOT (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1) BEGIN SET @CurrentCommand = '' + + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' + + BEGIN TRY + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + + GOTO NoAction + END CATCH + END + + -- Check incremental statistics properties + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 + AND NOT EXISTS (SELECT * FROM @IncrementalStatsProperties WHERE ObjectID = @CurrentObjectID AND StatisticsID = @CurrentStatisticsID) + BEGIN + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 - BEGIN - SET @CurrentCommand += 'SELECT @ParamObjectHasRows = CASE WHEN EXISTS (SELECT * FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id IN (0,1) AND partition_number = @ParamPartitionNumber AND row_count > 0) THEN 1 ELSE 0 END' - END - ELSE BEGIN - SET @CurrentCommand += 'SELECT @ParamObjectHasRows = CASE WHEN EXISTS (SELECT * FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id IN (0,1) AND row_count > 0) THEN 1 ELSE 0 END' + SET @CurrentCommand += 'SELECT object_id, stats_id, partition_number, [rows], modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID)' END BEGIN TRY - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamPartitionNumber int, @ParamObjectHasRows bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamObjectHasRows = @CurrentObjectHasRows OUTPUT + INSERT INTO @IncrementalStatsProperties (ObjectID, StatisticsID, PartitionNumber, [Rows], ModificationCounter) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamStatisticsID int', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The row count could not be checked.' ELSE '' END + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 SET @ReturnCode = ERROR_NUMBER() END + GOTO NoAction END CATCH END - -- Has the data in the statistics been modified since the statistics was last updated? - IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) + SELECT @CurrentRowCount = [Rows], + @CurrentModificationCounter = [ModificationCounter] + FROM @IncrementalStatsProperties + WHERE ObjectID = @CurrentObjectID + AND StatisticsID = @CurrentStatisticsID + AND PartitionNumber = @CurrentPartitionNumber + + -- Check partition statistics + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentModificationCounter IS NULL BEGIN SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 BEGIN - SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID) WHERE partition_number = @ParamPartitionNumber' + SET @CurrentCommand += 'SELECT @ParamObjectHasRows = CASE WHEN EXISTS (SELECT * FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id IN (0,1) AND partition_number = @ParamPartitionNumber AND row_count > 0) THEN 1 ELSE 0 END' END ELSE BEGIN - SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' + SET @CurrentCommand += 'SELECT @ParamObjectHasRows = CASE WHEN EXISTS (SELECT * FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id IN (0,1) AND row_count > 0) THEN 1 ELSE 0 END' END BEGIN TRY - 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 + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamPartitionNumber int, @ParamObjectHasRows bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamObjectHasRows = @CurrentObjectHasRows OUTPUT END TRY BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The row count 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 SET @ReturnCode = ERROR_NUMBER() END - GOTO NoAction END CATCH END @@ -9540,6 +9578,7 @@ BEGIN TRUNCATE TABLE #Indexes TRUNCATE TABLE #Stats DELETE FROM @tmpResumableOperations + DELETE FROM @IncrementalStatsProperties END -- End of database loop From 29c88fd8c1f7005a62dc9997bc15d7b2c0a015ba Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 16 Jul 2026 23:41:13 +0200 Subject: [PATCH 072/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 295 ++++++++++++++++++++---------------- MaintenanceSolution.sql | 303 +++++++++++++++++++++---------------- 5 files changed, 337 insertions(+), 267 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index dd3cdc54..126de019 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-15 22:27:18 //-- + --// Version: 2026-07-16 23:38:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index ff916995..77a81295 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-15 22:27:18 //-- + --// Version: 2026-07-16 23:38:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 3d3ec9d0..fce51797 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-15 22:27:18 //-- + --// Version: 2026-07-16 23:38:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index de3ad939..c5dd456d 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-15 22:27:18 //-- + --// Version: 2026-07-16 23:38:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -137,6 +137,7 @@ BEGIN DECLARE @CurrentPartitionID bigint DECLARE @CurrentPartitionNumber int DECLARE @CurrentPartitionCount int + DECLARE @CurrentInRowDataPageCount bigint DECLARE @CurrentIsPartition bit DECLARE @CurrentIndexExists bit DECLARE @CurrentStatisticsExists bit @@ -214,11 +215,13 @@ BEGIN PartitionID bigint, PartitionNumber int, PartitionCount int, + InRowDataPageCount bigint, StartPosition int, [Order] int DEFAULT 0, Selected bit DEFAULT 0, Completed bit DEFAULT 0, - PRIMARY KEY (Selected, Completed, [Order], ID)) + PRIMARY KEY (Selected, Completed, [Order], ID), + INDEX IX_ObjectID_StatisticsID_PartitionNumber NONCLUSTERED (ObjectID, StatisticsID, PartitionNumber)) DROP TABLE IF EXISTS #SelectedIndexes @@ -1821,6 +1824,7 @@ BEGIN + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.IsIncremental AS IsIncremental' ELSE ', NULL AS IsIncremental' END + ', ' + 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' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ' INNER JOIN #Stats Stats ON Indexes.ObjectID = Stats.ObjectID AND Indexes.IndexID = Stats.StatisticsID' ELSE '' END @@ -1828,17 +1832,17 @@ BEGIN BEGIN SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON Indexes.ObjectID = partitions.[object_id] AND Indexes.IndexID = partitions.index_id' END - IF @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) + IF @PartitionLevel = 'Y' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) BEGIN - SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.partition_id = dm_db_partition_stats.partition_id' + SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.object_id = dm_db_partition_stats.object_id AND partitions.index_id = dm_db_partition_stats.index_id AND partitions.partition_number = dm_db_partition_stats.partition_number' END SET @CurrentCommand += ' WHERE Objects.ObjectType IN(''U'',''V'')' + ' AND Indexes.IndexType IN(1,2,7)' - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= ' + CAST(@MinNumberOfPages AS nvarchar(max)) ELSE '' END - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= ' + CAST(@MaxNumberOfPages AS nvarchar(max)) ELSE '' END + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages SET @Error = @@ERROR IF @Error <> 0 BEGIN @@ -1911,23 +1915,24 @@ BEGIN + ', NULL 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' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' IF @PartitionLevel = 'Y' BEGIN SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON Indexes.ObjectID = partitions.[object_id] AND Indexes.IndexID = partitions.index_id' END - IF @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) + IF @PartitionLevel = 'Y' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) BEGIN - SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.partition_id = dm_db_partition_stats.partition_id' + SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.object_id = dm_db_partition_stats.object_id AND partitions.index_id = dm_db_partition_stats.index_id AND partitions.partition_number = dm_db_partition_stats.partition_number' END SET @CurrentCommand += ' WHERE Objects.ObjectType = ''U''' + ' AND Indexes.IndexType IN(5,6)' - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= ' + CAST(@MinNumberOfPages AS nvarchar(max)) ELSE '' END - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= ' + CAST(@MaxNumberOfPages AS nvarchar(max)) ELSE '' END + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages SET @Error = @@ERROR IF @Error <> 0 BEGIN @@ -2121,7 +2126,8 @@ BEGIN @CurrentIsIncremental = IsIncremental, @CurrentPartitionID = PartitionID, @CurrentPartitionNumber = PartitionNumber, - @CurrentPartitionCount = PartitionCount + @CurrentPartitionCount = PartitionCount, + @CurrentInRowDataPageCount = InRowDataPageCount FROM @tmpIndexesStatistics WHERE Selected = 1 AND Completed = 0 @@ -2135,150 +2141,162 @@ BEGIN -- Is the index a partition? IF @CurrentPartitionNumber IS NULL OR @CurrentPartitionCount = 1 BEGIN SET @CurrentIsPartition = 0 END ELSE BEGIN SET @CurrentIsPartition = 1 END - -- Does the index exist? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) + IF ((@CurrentInRowDataPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (@CurrentInRowDataPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL)) OR @CurrentInRowDataPageCount IS NULL BEGIN - SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + -- Does the index exist? + IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) + BEGIN + SET @CurrentCommand = '' - 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' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - BEGIN TRY - 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 @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' - IF @CurrentIndexExists IS NULL - BEGIN - SET @CurrentIndexExists = 0 - GOTO NoAction - END - END TRY - BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 - SET @ReturnCode = ERROR_NUMBER() - END + BEGIN TRY + 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 - GOTO NoAction - END CATCH - END + IF @CurrentIndexExists IS NULL + BEGIN + SET @CurrentIndexExists = 0 + GOTO NoAction + END + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 - -- 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 @CurrentCommand = '' + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + GOTO NoAction + END CATCH + END - 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' + -- 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 @CurrentCommand = '' - BEGIN TRY - 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(max)) + ', ' + 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 @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + IF @CurrentPartitionNumber IS NULL BEGIN - SET @ReturnCode = ERROR_NUMBER() + 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, NULL, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + END + ELSE + BEGIN + SET @CurrentCommand += 'SELECT @ParamFragmentationLevel = avg_fragmentation_in_percent, @ParamPageCount = 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' END - GOTO NoAction - END CATCH - END + BEGIN TRY + 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(max)) + ', ' + 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 - -- Select fragmentation group - IF @CurrentIndexID IS NOT NULL AND @CurrentOnReadOnlyFileGroup = 0 AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentFragmentationGroup = CASE - WHEN @CurrentFragmentationLevel >= @FragmentationLevel2 THEN 'High' - WHEN @CurrentFragmentationLevel >= @FragmentationLevel1 AND @CurrentFragmentationLevel < @FragmentationLevel2 THEN 'Medium' - WHEN @CurrentFragmentationLevel < @FragmentationLevel1 THEN 'Low' - END - END + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END - -- Which actions are allowed? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - IF NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) - AND NOT (@CurrentAllowPageLocks = 0) - BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REORGANIZE') + GOTO NoAction + END CATCH END - IF NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) + + -- Select fragmentation group + IF @CurrentIndexID IS NOT NULL AND @CurrentOnReadOnlyFileGroup = 0 AND EXISTS(SELECT * FROM @ActionsPreferred) BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REBUILD_OFFLINE') + SET @CurrentFragmentationGroup = CASE + WHEN @CurrentFragmentationLevel >= @FragmentationLevel2 THEN 'High' + WHEN @CurrentFragmentationLevel >= @FragmentationLevel1 AND @CurrentFragmentationLevel < @FragmentationLevel2 THEN 'Medium' + WHEN @CurrentFragmentationLevel < @FragmentationLevel1 THEN 'Low' + END END - IF @EngineEdition IN (3, 5, 8) - AND NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1 AND @CurrentIsImageText IS NOT NULL) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1 AND @CurrentIsFileStream IS NOT NULL) - AND NOT (@CurrentIndexType = 3) - AND NOT (@CurrentIndexType = 4) - AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @CurrentHasClusteredColumnstore IS NOT NULL AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND @CurrentIsColumnstoreOrdered IS NOT NULL AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + + -- Which actions are allowed? + IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REBUILD_ONLINE') + IF NOT (@CurrentOnReadOnlyFileGroup = 1) + AND NOT (@CurrentIsMemoryOptimized = 1) + AND NOT (@CurrentAllowPageLocks = 0) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REORGANIZE') + END + IF NOT (@CurrentOnReadOnlyFileGroup = 1) + AND NOT (@CurrentIsMemoryOptimized = 1) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REBUILD_OFFLINE') + END + IF @EngineEdition IN (3, 5, 8) + AND NOT (@CurrentOnReadOnlyFileGroup = 1) + AND NOT (@CurrentIsMemoryOptimized = 1) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1 AND @CurrentIsImageText IS NOT NULL) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1 AND @CurrentIsFileStream IS NOT NULL) + AND NOT (@CurrentIndexType = 3) + AND NOT (@CurrentIndexType = 4) + AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @CurrentHasClusteredColumnstore IS NOT NULL AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND @CurrentIsColumnstoreOrdered IS NOT NULL AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REBUILD_ONLINE') + END END - END - -- Decide action - IF @CurrentIndexID IS NOT NULL - 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) + -- Decide action + IF @CurrentIndexID IS NOT NULL + AND EXISTS(SELECT * FROM @ActionsPreferred) + AND (@CurrentPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) + AND (@CurrentPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL) + AND @CurrentResumableIndexOperation = 0 BEGIN - SELECT @CurrentAction = [Action] - FROM @ActionsPreferred - WHERE FragmentationGroup = @CurrentFragmentationGroup - AND [Priority] = (SELECT MIN([Priority]) - FROM @ActionsPreferred - WHERE FragmentationGroup = @CurrentFragmentationGroup - AND [Action] IN (SELECT [Action] FROM @CurrentActionsAllowed)) + IF EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) + BEGIN + SELECT @CurrentAction = [Action] + FROM @ActionsPreferred + WHERE FragmentationGroup = @CurrentFragmentationGroup + AND [Priority] = (SELECT MIN([Priority]) + FROM @ActionsPreferred + WHERE FragmentationGroup = @CurrentFragmentationGroup + AND [Action] IN (SELECT [Action] FROM @CurrentActionsAllowed)) + END + ELSE + BEGIN + SELECT @CurrentAction = [Action] + FROM @ActionsPreferred + WHERE [Priority] = (SELECT MIN([Priority]) + FROM @ActionsPreferred + WHERE [Action] IN (SELECT [Action] FROM @CurrentActionsAllowed)) + END END - ELSE + + IF @CurrentResumableIndexOperation = 1 BEGIN - SELECT @CurrentAction = [Action] - FROM @ActionsPreferred - WHERE [Priority] = (SELECT MIN([Priority]) - FROM @ActionsPreferred - WHERE [Action] IN (SELECT [Action] FROM @CurrentActionsAllowed)) + SET @CurrentAction = 'INDEX_REBUILD_ONLINE' END - END - IF @CurrentResumableIndexOperation = 1 - BEGIN - SET @CurrentAction = 'INDEX_REBUILD_ONLINE' - END + SET @CurrentMaxDOP = @MaxDOP - SET @CurrentMaxDOP = @MaxDOP + -- Workaround for limitation in SQL Server, http://support.microsoft.com/kb/2292737 + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentIndexType IN (1, 2) AND @CurrentAllowPageLocks = 0 + BEGIN + SET @CurrentMaxDOP = 1 + END - -- Workaround for limitation in SQL Server, http://support.microsoft.com/kb/2292737 - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentIndexType IN (1, 2) AND @CurrentAllowPageLocks = 0 - BEGIN - SET @CurrentMaxDOP = 1 END -- Create index comment @@ -2672,6 +2690,22 @@ BEGIN AND [Order] = @CurrentIxOrder AND ID = @CurrentIxID + -- Update that statistics on remaining partitions are completed where no update is needed + IF (NOT EXISTS(SELECT * FROM @ActionsPreferred) OR @CurrentIndexID IS NULL) AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentStatisticsID IS NOT NULL + BEGIN + UPDATE tmpIndexesStatistics + SET Completed = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @IncrementalStatsProperties IncrementalStatsProperties ON tmpIndexesStatistics.ObjectID = IncrementalStatsProperties.ObjectID AND tmpIndexesStatistics.StatisticsID = IncrementalStatsProperties.StatisticsID AND tmpIndexesStatistics.PartitionNumber = IncrementalStatsProperties.PartitionNumber + WHERE tmpIndexesStatistics.ObjectID = @CurrentObjectID + AND tmpIndexesStatistics.StatisticsID = @CurrentStatisticsID + AND tmpIndexesStatistics.Selected = 1 + AND tmpIndexesStatistics.Completed = 0 + AND IncrementalStatsProperties.ModificationCounter IS NOT NULL + AND ((@OnlyModifiedStatistics = 'Y' AND NOT (IncrementalStatsProperties.ModificationCounter > 0)) + OR (@StatisticsModificationLevel IS NOT NULL AND NOT ((IncrementalStatsProperties.ModificationCounter * 1. / NULLIF(IncrementalStatsProperties.[Rows],0)) * 100 >= @StatisticsModificationLevel OR (IncrementalStatsProperties.ModificationCounter > 0 AND IncrementalStatsProperties.ModificationCounter >= SQRT(IncrementalStatsProperties.[Rows] * 1000))))) + END + -- Clear variables SET @CurrentDatabaseContext = NULL @@ -2697,6 +2731,7 @@ BEGIN SET @CurrentPartitionID = NULL SET @CurrentPartitionNumber = NULL SET @CurrentPartitionCount = NULL + SET @CurrentInRowDataPageCount = NULL SET @CurrentIsPartition = NULL SET @CurrentIndexExists = NULL SET @CurrentStatisticsExists = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 5673be00..920def78 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: 2026-07-15 22:27:18 +Version: 2026-07-16 23:38:29 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-15 22:27:18 //-- + --// Version: 2026-07-16 23:38:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-15 22:27:18 //-- + --// Version: 2026-07-16 23:38:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4873,7 +4873,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-15 22:27:18 //-- + --// Version: 2026-07-16 23:38:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6842,7 +6842,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-15 22:27:18 //-- + --// Version: 2026-07-16 23:38:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6923,6 +6923,7 @@ BEGIN DECLARE @CurrentPartitionID bigint DECLARE @CurrentPartitionNumber int DECLARE @CurrentPartitionCount int + DECLARE @CurrentInRowDataPageCount bigint DECLARE @CurrentIsPartition bit DECLARE @CurrentIndexExists bit DECLARE @CurrentStatisticsExists bit @@ -7000,11 +7001,13 @@ BEGIN PartitionID bigint, PartitionNumber int, PartitionCount int, + InRowDataPageCount bigint, StartPosition int, [Order] int DEFAULT 0, Selected bit DEFAULT 0, Completed bit DEFAULT 0, - PRIMARY KEY (Selected, Completed, [Order], ID)) + PRIMARY KEY (Selected, Completed, [Order], ID), + INDEX IX_ObjectID_StatisticsID_PartitionNumber NONCLUSTERED (ObjectID, StatisticsID, PartitionNumber)) DROP TABLE IF EXISTS #SelectedIndexes @@ -8607,6 +8610,7 @@ BEGIN + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.IsIncremental AS IsIncremental' ELSE ', NULL AS IsIncremental' END + ', ' + 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' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ' INNER JOIN #Stats Stats ON Indexes.ObjectID = Stats.ObjectID AND Indexes.IndexID = Stats.StatisticsID' ELSE '' END @@ -8614,17 +8618,17 @@ BEGIN BEGIN SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON Indexes.ObjectID = partitions.[object_id] AND Indexes.IndexID = partitions.index_id' END - IF @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) + IF @PartitionLevel = 'Y' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) BEGIN - SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.partition_id = dm_db_partition_stats.partition_id' + SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.object_id = dm_db_partition_stats.object_id AND partitions.index_id = dm_db_partition_stats.index_id AND partitions.partition_number = dm_db_partition_stats.partition_number' END SET @CurrentCommand += ' WHERE Objects.ObjectType IN(''U'',''V'')' + ' AND Indexes.IndexType IN(1,2,7)' - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= ' + CAST(@MinNumberOfPages AS nvarchar(max)) ELSE '' END - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= ' + CAST(@MaxNumberOfPages AS nvarchar(max)) ELSE '' END + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages SET @Error = @@ERROR IF @Error <> 0 BEGIN @@ -8697,23 +8701,24 @@ BEGIN + ', NULL 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' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' IF @PartitionLevel = 'Y' BEGIN SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON Indexes.ObjectID = partitions.[object_id] AND Indexes.IndexID = partitions.index_id' END - IF @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) + IF @PartitionLevel = 'Y' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) BEGIN - SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.partition_id = dm_db_partition_stats.partition_id' + SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.object_id = dm_db_partition_stats.object_id AND partitions.index_id = dm_db_partition_stats.index_id AND partitions.partition_number = dm_db_partition_stats.partition_number' END SET @CurrentCommand += ' WHERE Objects.ObjectType = ''U''' + ' AND Indexes.IndexType IN(5,6)' - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= ' + CAST(@MinNumberOfPages AS nvarchar(max)) ELSE '' END - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= ' + CAST(@MaxNumberOfPages AS nvarchar(max)) ELSE '' END + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber) - EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages SET @Error = @@ERROR IF @Error <> 0 BEGIN @@ -8907,7 +8912,8 @@ BEGIN @CurrentIsIncremental = IsIncremental, @CurrentPartitionID = PartitionID, @CurrentPartitionNumber = PartitionNumber, - @CurrentPartitionCount = PartitionCount + @CurrentPartitionCount = PartitionCount, + @CurrentInRowDataPageCount = InRowDataPageCount FROM @tmpIndexesStatistics WHERE Selected = 1 AND Completed = 0 @@ -8921,150 +8927,162 @@ BEGIN -- Is the index a partition? IF @CurrentPartitionNumber IS NULL OR @CurrentPartitionCount = 1 BEGIN SET @CurrentIsPartition = 0 END ELSE BEGIN SET @CurrentIsPartition = 1 END - -- Does the index exist? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) + IF ((@CurrentInRowDataPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (@CurrentInRowDataPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL)) OR @CurrentInRowDataPageCount IS NULL BEGIN - SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - - 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' + -- Does the index exist? + IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) + BEGIN + SET @CurrentCommand = '' - BEGIN TRY - 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 @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - IF @CurrentIndexExists IS NULL - BEGIN - SET @CurrentIndexExists = 0 - GOTO NoAction - END - END TRY - BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @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' - IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) - BEGIN - SET @ReturnCode = ERROR_NUMBER() - END + BEGIN TRY + 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 - GOTO NoAction - END CATCH - END + IF @CurrentIndexExists IS NULL + BEGIN + SET @CurrentIndexExists = 0 + GOTO NoAction + END + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 - -- 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 @CurrentCommand = '' + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + GOTO NoAction + END CATCH + END - 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' + -- 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 @CurrentCommand = '' - BEGIN TRY - 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(max)) + ', ' + 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 @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + IF @CurrentPartitionNumber IS NULL BEGIN - SET @ReturnCode = ERROR_NUMBER() + 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, NULL, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + END + ELSE + BEGIN + SET @CurrentCommand += 'SELECT @ParamFragmentationLevel = avg_fragmentation_in_percent, @ParamPageCount = 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' END - GOTO NoAction - END CATCH - END + BEGIN TRY + 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(max)) + ', ' + 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 - -- Select fragmentation group - IF @CurrentIndexID IS NOT NULL AND @CurrentOnReadOnlyFileGroup = 0 AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentFragmentationGroup = CASE - WHEN @CurrentFragmentationLevel >= @FragmentationLevel2 THEN 'High' - WHEN @CurrentFragmentationLevel >= @FragmentationLevel1 AND @CurrentFragmentationLevel < @FragmentationLevel2 THEN 'Medium' - WHEN @CurrentFragmentationLevel < @FragmentationLevel1 THEN 'Low' - END - END + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END - -- Which actions are allowed? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - IF NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) - AND NOT (@CurrentAllowPageLocks = 0) - BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REORGANIZE') + GOTO NoAction + END CATCH END - IF NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) + + -- Select fragmentation group + IF @CurrentIndexID IS NOT NULL AND @CurrentOnReadOnlyFileGroup = 0 AND EXISTS(SELECT * FROM @ActionsPreferred) BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REBUILD_OFFLINE') + SET @CurrentFragmentationGroup = CASE + WHEN @CurrentFragmentationLevel >= @FragmentationLevel2 THEN 'High' + WHEN @CurrentFragmentationLevel >= @FragmentationLevel1 AND @CurrentFragmentationLevel < @FragmentationLevel2 THEN 'Medium' + WHEN @CurrentFragmentationLevel < @FragmentationLevel1 THEN 'Low' + END END - IF @EngineEdition IN (3, 5, 8) - AND NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1 AND @CurrentIsImageText IS NOT NULL) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1 AND @CurrentIsFileStream IS NOT NULL) - AND NOT (@CurrentIndexType = 3) - AND NOT (@CurrentIndexType = 4) - AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @CurrentHasClusteredColumnstore IS NOT NULL AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND @CurrentIsColumnstoreOrdered IS NOT NULL AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + + -- Which actions are allowed? + IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REBUILD_ONLINE') + IF NOT (@CurrentOnReadOnlyFileGroup = 1) + AND NOT (@CurrentIsMemoryOptimized = 1) + AND NOT (@CurrentAllowPageLocks = 0) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REORGANIZE') + END + IF NOT (@CurrentOnReadOnlyFileGroup = 1) + AND NOT (@CurrentIsMemoryOptimized = 1) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REBUILD_OFFLINE') + END + IF @EngineEdition IN (3, 5, 8) + AND NOT (@CurrentOnReadOnlyFileGroup = 1) + AND NOT (@CurrentIsMemoryOptimized = 1) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1 AND @CurrentIsImageText IS NOT NULL) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1 AND @CurrentIsFileStream IS NOT NULL) + AND NOT (@CurrentIndexType = 3) + AND NOT (@CurrentIndexType = 4) + AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @CurrentHasClusteredColumnstore IS NOT NULL AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND @CurrentIsColumnstoreOrdered IS NOT NULL AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REBUILD_ONLINE') + END END - END - -- Decide action - IF @CurrentIndexID IS NOT NULL - 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) + -- Decide action + IF @CurrentIndexID IS NOT NULL + AND EXISTS(SELECT * FROM @ActionsPreferred) + AND (@CurrentPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) + AND (@CurrentPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL) + AND @CurrentResumableIndexOperation = 0 BEGIN - SELECT @CurrentAction = [Action] - FROM @ActionsPreferred - WHERE FragmentationGroup = @CurrentFragmentationGroup - AND [Priority] = (SELECT MIN([Priority]) - FROM @ActionsPreferred - WHERE FragmentationGroup = @CurrentFragmentationGroup - AND [Action] IN (SELECT [Action] FROM @CurrentActionsAllowed)) + IF EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) + BEGIN + SELECT @CurrentAction = [Action] + FROM @ActionsPreferred + WHERE FragmentationGroup = @CurrentFragmentationGroup + AND [Priority] = (SELECT MIN([Priority]) + FROM @ActionsPreferred + WHERE FragmentationGroup = @CurrentFragmentationGroup + AND [Action] IN (SELECT [Action] FROM @CurrentActionsAllowed)) + END + ELSE + BEGIN + SELECT @CurrentAction = [Action] + FROM @ActionsPreferred + WHERE [Priority] = (SELECT MIN([Priority]) + FROM @ActionsPreferred + WHERE [Action] IN (SELECT [Action] FROM @CurrentActionsAllowed)) + END END - ELSE + + IF @CurrentResumableIndexOperation = 1 BEGIN - SELECT @CurrentAction = [Action] - FROM @ActionsPreferred - WHERE [Priority] = (SELECT MIN([Priority]) - FROM @ActionsPreferred - WHERE [Action] IN (SELECT [Action] FROM @CurrentActionsAllowed)) + SET @CurrentAction = 'INDEX_REBUILD_ONLINE' END - END - IF @CurrentResumableIndexOperation = 1 - BEGIN - SET @CurrentAction = 'INDEX_REBUILD_ONLINE' - END + SET @CurrentMaxDOP = @MaxDOP - SET @CurrentMaxDOP = @MaxDOP + -- Workaround for limitation in SQL Server, http://support.microsoft.com/kb/2292737 + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentIndexType IN (1, 2) AND @CurrentAllowPageLocks = 0 + BEGIN + SET @CurrentMaxDOP = 1 + END - -- Workaround for limitation in SQL Server, http://support.microsoft.com/kb/2292737 - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentIndexType IN (1, 2) AND @CurrentAllowPageLocks = 0 - BEGIN - SET @CurrentMaxDOP = 1 END -- Create index comment @@ -9458,6 +9476,22 @@ BEGIN AND [Order] = @CurrentIxOrder AND ID = @CurrentIxID + -- Update that statistics on remaining partitions are completed where no update is needed + IF (NOT EXISTS(SELECT * FROM @ActionsPreferred) OR @CurrentIndexID IS NULL) AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentStatisticsID IS NOT NULL + BEGIN + UPDATE tmpIndexesStatistics + SET Completed = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @IncrementalStatsProperties IncrementalStatsProperties ON tmpIndexesStatistics.ObjectID = IncrementalStatsProperties.ObjectID AND tmpIndexesStatistics.StatisticsID = IncrementalStatsProperties.StatisticsID AND tmpIndexesStatistics.PartitionNumber = IncrementalStatsProperties.PartitionNumber + WHERE tmpIndexesStatistics.ObjectID = @CurrentObjectID + AND tmpIndexesStatistics.StatisticsID = @CurrentStatisticsID + AND tmpIndexesStatistics.Selected = 1 + AND tmpIndexesStatistics.Completed = 0 + AND IncrementalStatsProperties.ModificationCounter IS NOT NULL + AND ((@OnlyModifiedStatistics = 'Y' AND NOT (IncrementalStatsProperties.ModificationCounter > 0)) + OR (@StatisticsModificationLevel IS NOT NULL AND NOT ((IncrementalStatsProperties.ModificationCounter * 1. / NULLIF(IncrementalStatsProperties.[Rows],0)) * 100 >= @StatisticsModificationLevel OR (IncrementalStatsProperties.ModificationCounter > 0 AND IncrementalStatsProperties.ModificationCounter >= SQRT(IncrementalStatsProperties.[Rows] * 1000))))) + END + -- Clear variables SET @CurrentDatabaseContext = NULL @@ -9483,6 +9517,7 @@ BEGIN SET @CurrentPartitionID = NULL SET @CurrentPartitionNumber = NULL SET @CurrentPartitionCount = NULL + SET @CurrentInRowDataPageCount = NULL SET @CurrentIsPartition = NULL SET @CurrentIndexExists = NULL SET @CurrentStatisticsExists = NULL From b18ce95255a6de968582ebc9387156254211c8ad Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 18 Jul 2026 00:13:56 +0200 Subject: [PATCH 073/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 53 +++++++++++++++++++++++++++++++-- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 61 ++++++++++++++++++++++++++++++++++---- 5 files changed, 109 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 126de019..f2b353af 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-16 23:38:29 //-- + --// Version: 2026-07-18 00:13:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 77a81295..0fd5d6e2 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-16 23:38:29 //-- + --// Version: 2026-07-18 00:13:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -148,6 +148,7 @@ BEGIN DECLARE @CurrentDifferentialBaseLSN numeric(25,0) DECLARE @CurrentDifferentialBaseIsSnapshot bit DECLARE @CurrentLogLSN numeric(25,0) + DECLARE @BackupInProgress bit DECLARE @CurrentLatestBackup datetime2 DECLARE @CurrentDatabaseNameFS nvarchar(max) DECLARE @CurrentDirectoryStructure nvarchar(max) @@ -1616,6 +1617,12 @@ BEGIN SELECT 'The value for the parameter @Description is not supported.', 16, 3 END + IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @Description LIKE '%"%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Description is not supported.', 16, 4 + END + ---------------------------------------------------------------------------------------------------- IF LEN(@BackupSetName) > 128 @@ -1624,6 +1631,12 @@ BEGIN SELECT 'The value for the parameter @BackupSetName is not supported.', 16, 1 END + IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @BackupSetName LIKE '%"%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BackupSetName is not supported.', 16, 2 + END + ---------------------------------------------------------------------------------------------------- IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) @@ -2018,6 +2031,12 @@ BEGIN SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16, 2 END + IF @DataDomainBoostHost LIKE '%"%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16, 3 + END + ---------------------------------------------------------------------------------------------------- IF @DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) @@ -2032,6 +2051,12 @@ BEGIN SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16, 2 END + IF @DataDomainBoostUser LIKE '%"%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16, 3 + END + ---------------------------------------------------------------------------------------------------- IF @DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) @@ -2046,6 +2071,12 @@ BEGIN SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 2 END + IF @DataDomainBoostDevicePath LIKE '%"%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 3 + END + ---------------------------------------------------------------------------------------------------- IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) @@ -2054,6 +2085,12 @@ BEGIN SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 1 END + IF @DataDomainBoostLockboxPath LIKE '%"%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 2 + END + ---------------------------------------------------------------------------------------------------- IF @DataDomainBoostNoOutputTable NOT IN('Y','N') OR @DataDomainBoostNoOutputTable IS NULL @@ -2896,11 +2933,16 @@ BEGIN EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAllocatedExtentPageCount bigint OUTPUT, @ParamModifiedExtentPageCount bigint OUTPUT', @ParamAllocatedExtentPageCount = @CurrentAllocatedExtentPageCount OUTPUT, @ParamModifiedExtentPageCount = @CurrentModifiedExtentPageCount OUTPUT END + IF (@Version >= 16.04265 AND @Version < 17) OR @Version >= 17.04065 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous') + BEGIN + SET @BackupInProgress = CASE WHEN EXISTS(SELECT * FROM sys.dm_exec_requests WHERE database_id = DB_ID(@CurrentDatabaseName) AND command = 'BACKUP DATABASE') THEN 1 ELSE 0 END + END + SET @CurrentBackupType = @BackupType IF @ChangeBackupType = 'Y' BEGIN - IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) + IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) BEGIN SET @CurrentBackupType = 'DIFF' END @@ -3059,6 +3101,12 @@ BEGIN SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar(max)),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + IF @CurrentBackupType = 'LOG' AND @ChangeBackupType = 'Y' + BEGIN + SET @DatabaseMessage = 'Full or differential backup in progress: ' + CASE WHEN @BackupInProgress = 1 THEN 'Yes' WHEN @BackupInProgress = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + IF @CurrentBackupType IN('DIFF','FULL') BEGIN SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar(max)) + ' (' + CAST(@CurrentAllocatedExtentPageCount * 1. * 8 / 1024 AS nvarchar(max)) + ' MB)','N/A') @@ -4370,6 +4418,7 @@ BEGIN SET @CurrentDifferentialBaseLSN = NULL SET @CurrentDifferentialBaseIsSnapshot = NULL SET @CurrentLogLSN = NULL + SET @BackupInProgress = NULL SET @CurrentLatestBackup = NULL SET @CurrentDatabaseNameFS = NULL SET @CurrentDirectoryStructure = NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index fce51797..75649348 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-16 23:38:29 //-- + --// Version: 2026-07-18 00:13:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index c5dd456d..00c62d1e 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-16 23:38:29 //-- + --// Version: 2026-07-18 00:13:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 920def78..7e41cb06 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: 2026-07-16 23:38:29 +Version: 2026-07-18 00:13:04 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-16 23:38:29 //-- + --// Version: 2026-07-18 00:13:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-16 23:38:29 //-- + --// Version: 2026-07-18 00:13:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -547,6 +547,7 @@ BEGIN DECLARE @CurrentDifferentialBaseLSN numeric(25,0) DECLARE @CurrentDifferentialBaseIsSnapshot bit DECLARE @CurrentLogLSN numeric(25,0) + DECLARE @BackupInProgress bit DECLARE @CurrentLatestBackup datetime2 DECLARE @CurrentDatabaseNameFS nvarchar(max) DECLARE @CurrentDirectoryStructure nvarchar(max) @@ -2015,6 +2016,12 @@ BEGIN SELECT 'The value for the parameter @Description is not supported.', 16, 3 END + IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @Description LIKE '%"%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @Description is not supported.', 16, 4 + END + ---------------------------------------------------------------------------------------------------- IF LEN(@BackupSetName) > 128 @@ -2023,6 +2030,12 @@ BEGIN SELECT 'The value for the parameter @BackupSetName is not supported.', 16, 1 END + IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @BackupSetName LIKE '%"%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @BackupSetName is not supported.', 16, 2 + END + ---------------------------------------------------------------------------------------------------- IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) @@ -2417,6 +2430,12 @@ BEGIN SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16, 2 END + IF @DataDomainBoostHost LIKE '%"%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16, 3 + END + ---------------------------------------------------------------------------------------------------- IF @DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) @@ -2431,6 +2450,12 @@ BEGIN SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16, 2 END + IF @DataDomainBoostUser LIKE '%"%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16, 3 + END + ---------------------------------------------------------------------------------------------------- IF @DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) @@ -2445,6 +2470,12 @@ BEGIN SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 2 END + IF @DataDomainBoostDevicePath LIKE '%"%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 3 + END + ---------------------------------------------------------------------------------------------------- IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) @@ -2453,6 +2484,12 @@ BEGIN SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 1 END + IF @DataDomainBoostLockboxPath LIKE '%"%' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 2 + END + ---------------------------------------------------------------------------------------------------- IF @DataDomainBoostNoOutputTable NOT IN('Y','N') OR @DataDomainBoostNoOutputTable IS NULL @@ -3295,11 +3332,16 @@ BEGIN EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAllocatedExtentPageCount bigint OUTPUT, @ParamModifiedExtentPageCount bigint OUTPUT', @ParamAllocatedExtentPageCount = @CurrentAllocatedExtentPageCount OUTPUT, @ParamModifiedExtentPageCount = @CurrentModifiedExtentPageCount OUTPUT END + IF (@Version >= 16.04265 AND @Version < 17) OR @Version >= 17.04065 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous') + BEGIN + SET @BackupInProgress = CASE WHEN EXISTS(SELECT * FROM sys.dm_exec_requests WHERE database_id = DB_ID(@CurrentDatabaseName) AND command = 'BACKUP DATABASE') THEN 1 ELSE 0 END + END + SET @CurrentBackupType = @BackupType IF @ChangeBackupType = 'Y' BEGIN - IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) + IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) BEGIN SET @CurrentBackupType = 'DIFF' END @@ -3458,6 +3500,12 @@ BEGIN SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar(max)),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + IF @CurrentBackupType = 'LOG' AND @ChangeBackupType = 'Y' + BEGIN + SET @DatabaseMessage = 'Full or differential backup in progress: ' + CASE WHEN @BackupInProgress = 1 THEN 'Yes' WHEN @BackupInProgress = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + IF @CurrentBackupType IN('DIFF','FULL') BEGIN SET @DatabaseMessage = 'Allocated extent page count: ' + ISNULL(CAST(@CurrentAllocatedExtentPageCount AS nvarchar(max)) + ' (' + CAST(@CurrentAllocatedExtentPageCount * 1. * 8 / 1024 AS nvarchar(max)) + ' MB)','N/A') @@ -4769,6 +4817,7 @@ BEGIN SET @CurrentDifferentialBaseLSN = NULL SET @CurrentDifferentialBaseIsSnapshot = NULL SET @CurrentLogLSN = NULL + SET @BackupInProgress = NULL SET @CurrentLatestBackup = NULL SET @CurrentDatabaseNameFS = NULL SET @CurrentDirectoryStructure = NULL @@ -4873,7 +4922,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-16 23:38:29 //-- + --// Version: 2026-07-18 00:13:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6842,7 +6891,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-16 23:38:29 //-- + --// Version: 2026-07-18 00:13:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From fc7051841bb59310c5817d83d1f2b462995dbf6c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 18 Jul 2026 10:58:29 +0200 Subject: [PATCH 074/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 56 +++++++++++++++++++++++++++++++-- MaintenanceSolution.sql | 64 +++++++++++++++++++++++++++++++++----- 5 files changed, 113 insertions(+), 13 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index f2b353af..a8534e9b 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-18 00:13:04 //-- + --// Version: 2026-07-18 10:57:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 0fd5d6e2..e4bf281c 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-18 00:13:04 //-- + --// Version: 2026-07-18 10:57:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 75649348..7da5df8f 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-18 00:13:04 //-- + --// Version: 2026-07-18 10:57:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 00c62d1e..a91ecd9e 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-18 00:13:04 //-- + --// Version: 2026-07-18 10:57:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -271,6 +271,17 @@ BEGIN IsIndex bit, PRIMARY KEY (ObjectID, StatisticsID)) + DROP TABLE IF EXISTS #ExistingObjects + + CREATE TABLE #ExistingObjects (SchemaName nvarchar(max) COLLATE DATABASE_DEFAULT, + ObjectName nvarchar(max) COLLATE DATABASE_DEFAULT) + + DROP TABLE IF EXISTS #ExistingIndexes + + CREATE TABLE #ExistingIndexes (SchemaName nvarchar(max) COLLATE DATABASE_DEFAULT, + ObjectName nvarchar(max) COLLATE DATABASE_DEFAULT, + IndexName nvarchar(max) COLLATE DATABASE_DEFAULT) + DECLARE @tmpResumableOperations TABLE (ObjectID int NOT NULL, IndexID int NOT NULL, PartitionNumber int) @@ -1711,6 +1722,11 @@ BEGIN SET @CurrentCommand += ' AND EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes WHERE @ParamDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND schemas.[name] LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND objects.[name] LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND SelectedIndexes.Selected = 1)' END + IF @Indexes IS NOT NULL AND EXISTS(SELECT * FROM @SelectedIndexes WHERE Selected = 0 AND IndexName = '%') + BEGIN + SET @CurrentCommand += ' AND NOT EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes WHERE @ParamDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND schemas.[name] LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND objects.[name] LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND SelectedIndexes.IndexName = ''%'' AND SelectedIndexes.Selected = 0)' + END + INSERT INTO #Objects (ObjectID, SchemaID, SchemaName, ObjectName, ObjectType, IsMemoryOptimized, HasClusteredColumnstore, IsClusteredIndexComputed, IsClusteredIndexDisabled) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max)', @ParamDatabaseName = @CurrentDatabaseName SET @Error = @@ERROR @@ -2063,6 +2079,38 @@ BEGIN UPDATE tmpIndexesStatistics SET [Order] = RowNumber + SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName' + + ' FROM sys.objects objects' + + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' + + ' WHERE objects.[type] IN(''U'',''V'')' + + ' AND EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes' + + ' WHERE SelectedIndexes.DatabaseName = @ParamDatabaseName' + + ' AND SelectedIndexes.SchemaName NOT LIKE ''%[%]%''' + + ' AND SelectedIndexes.ObjectName NOT LIKE ''%[%]%''' + + ' AND schemas.[name] = SelectedIndexes.SchemaName COLLATE ' + @Collation + + ' AND objects.[name] = SelectedIndexes.ObjectName COLLATE ' + @Collation + ')' + + INSERT INTO #ExistingObjects (SchemaName, ObjectName) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max)', @ParamDatabaseName = @CurrentDatabaseName + + SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName, [Names].[name] AS IndexName' + + ' FROM sys.objects objects' + + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' + + ' CROSS APPLY (SELECT indexes.[name] FROM sys.indexes indexes WHERE indexes.[object_id] = objects.[object_id] AND indexes.[type] <> 0' + + ' UNION SELECT stats.[name] FROM sys.stats stats WHERE stats.[object_id] = objects.[object_id]) [Names]' + + ' WHERE objects.[type] IN(''U'',''V'')' + + ' AND EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes' + + ' WHERE SelectedIndexes.DatabaseName = @ParamDatabaseName' + + ' AND SelectedIndexes.SchemaName NOT LIKE ''%[%]%''' + + ' AND SelectedIndexes.ObjectName NOT LIKE ''%[%]%''' + + ' AND SelectedIndexes.IndexName NOT LIKE ''%[%]%''' + + ' AND schemas.[name] = SelectedIndexes.SchemaName COLLATE ' + @Collation + + ' AND objects.[name] = SelectedIndexes.ObjectName COLLATE ' + @Collation + + ' AND [Names].[name] = SelectedIndexes.IndexName COLLATE ' + @Collation + ')' + + INSERT INTO #ExistingIndexes (SchemaName, ObjectName, IndexName) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max)', @ParamDatabaseName = @CurrentDatabaseName + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName), ', ') WITHIN GROUP (ORDER BY DatabaseName ASC, SchemaName ASC, ObjectName ASC) FROM @SelectedIndexes SelectedIndexes @@ -2070,7 +2118,7 @@ BEGIN AND SchemaName NOT LIKE '%[%]%' AND ObjectName NOT LIKE '%[%]%' AND IndexName LIKE '%[%]%' - AND NOT EXISTS (SELECT * FROM #Objects WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName) + AND NOT EXISTS (SELECT * FROM #ExistingObjects WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName) IF @ErrorMessage IS NOT NULL BEGIN @@ -2086,7 +2134,7 @@ BEGIN AND SchemaName NOT LIKE '%[%]%' AND ObjectName NOT LIKE '%[%]%' AND IndexName NOT LIKE '%[%]%' - AND NOT EXISTS (SELECT * FROM #Indexes Indexes INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID WHERE Objects.SchemaName = SelectedIndexes.SchemaName AND Objects.ObjectName = SelectedIndexes.ObjectName AND Indexes.IndexName = SelectedIndexes.IndexName) + AND NOT EXISTS (SELECT * FROM #ExistingIndexes WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName AND IndexName = SelectedIndexes.IndexName) IF @ErrorMessage IS NOT NULL BEGIN @@ -2826,6 +2874,8 @@ BEGIN TRUNCATE TABLE #Objects TRUNCATE TABLE #Indexes TRUNCATE TABLE #Stats + TRUNCATE TABLE #ExistingObjects + TRUNCATE TABLE #ExistingIndexes DELETE FROM @tmpResumableOperations DELETE FROM @IncrementalStatsProperties diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 7e41cb06..34c13d3c 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: 2026-07-18 00:13:04 +Version: 2026-07-18 10:57:42 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-18 00:13:04 //-- + --// Version: 2026-07-18 10:57:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-18 00:13:04 //-- + --// Version: 2026-07-18 10:57:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4922,7 +4922,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-18 00:13:04 //-- + --// Version: 2026-07-18 10:57:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6891,7 +6891,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-18 00:13:04 //-- + --// Version: 2026-07-18 10:57:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7106,6 +7106,17 @@ BEGIN IsIndex bit, PRIMARY KEY (ObjectID, StatisticsID)) + DROP TABLE IF EXISTS #ExistingObjects + + CREATE TABLE #ExistingObjects (SchemaName nvarchar(max) COLLATE DATABASE_DEFAULT, + ObjectName nvarchar(max) COLLATE DATABASE_DEFAULT) + + DROP TABLE IF EXISTS #ExistingIndexes + + CREATE TABLE #ExistingIndexes (SchemaName nvarchar(max) COLLATE DATABASE_DEFAULT, + ObjectName nvarchar(max) COLLATE DATABASE_DEFAULT, + IndexName nvarchar(max) COLLATE DATABASE_DEFAULT) + DECLARE @tmpResumableOperations TABLE (ObjectID int NOT NULL, IndexID int NOT NULL, PartitionNumber int) @@ -8546,6 +8557,11 @@ BEGIN SET @CurrentCommand += ' AND EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes WHERE @ParamDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND schemas.[name] LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND objects.[name] LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND SelectedIndexes.Selected = 1)' END + IF @Indexes IS NOT NULL AND EXISTS(SELECT * FROM @SelectedIndexes WHERE Selected = 0 AND IndexName = '%') + BEGIN + SET @CurrentCommand += ' AND NOT EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes WHERE @ParamDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND schemas.[name] LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND objects.[name] LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND SelectedIndexes.IndexName = ''%'' AND SelectedIndexes.Selected = 0)' + END + INSERT INTO #Objects (ObjectID, SchemaID, SchemaName, ObjectName, ObjectType, IsMemoryOptimized, HasClusteredColumnstore, IsClusteredIndexComputed, IsClusteredIndexDisabled) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max)', @ParamDatabaseName = @CurrentDatabaseName SET @Error = @@ERROR @@ -8898,6 +8914,38 @@ BEGIN UPDATE tmpIndexesStatistics SET [Order] = RowNumber + SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName' + + ' FROM sys.objects objects' + + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' + + ' WHERE objects.[type] IN(''U'',''V'')' + + ' AND EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes' + + ' WHERE SelectedIndexes.DatabaseName = @ParamDatabaseName' + + ' AND SelectedIndexes.SchemaName NOT LIKE ''%[%]%''' + + ' AND SelectedIndexes.ObjectName NOT LIKE ''%[%]%''' + + ' AND schemas.[name] = SelectedIndexes.SchemaName COLLATE ' + @Collation + + ' AND objects.[name] = SelectedIndexes.ObjectName COLLATE ' + @Collation + ')' + + INSERT INTO #ExistingObjects (SchemaName, ObjectName) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max)', @ParamDatabaseName = @CurrentDatabaseName + + SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName, [Names].[name] AS IndexName' + + ' FROM sys.objects objects' + + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' + + ' CROSS APPLY (SELECT indexes.[name] FROM sys.indexes indexes WHERE indexes.[object_id] = objects.[object_id] AND indexes.[type] <> 0' + + ' UNION SELECT stats.[name] FROM sys.stats stats WHERE stats.[object_id] = objects.[object_id]) [Names]' + + ' WHERE objects.[type] IN(''U'',''V'')' + + ' AND EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes' + + ' WHERE SelectedIndexes.DatabaseName = @ParamDatabaseName' + + ' AND SelectedIndexes.SchemaName NOT LIKE ''%[%]%''' + + ' AND SelectedIndexes.ObjectName NOT LIKE ''%[%]%''' + + ' AND SelectedIndexes.IndexName NOT LIKE ''%[%]%''' + + ' AND schemas.[name] = SelectedIndexes.SchemaName COLLATE ' + @Collation + + ' AND objects.[name] = SelectedIndexes.ObjectName COLLATE ' + @Collation + + ' AND [Names].[name] = SelectedIndexes.IndexName COLLATE ' + @Collation + ')' + + INSERT INTO #ExistingIndexes (SchemaName, ObjectName, IndexName) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max)', @ParamDatabaseName = @CurrentDatabaseName + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName), ', ') WITHIN GROUP (ORDER BY DatabaseName ASC, SchemaName ASC, ObjectName ASC) FROM @SelectedIndexes SelectedIndexes @@ -8905,7 +8953,7 @@ BEGIN AND SchemaName NOT LIKE '%[%]%' AND ObjectName NOT LIKE '%[%]%' AND IndexName LIKE '%[%]%' - AND NOT EXISTS (SELECT * FROM #Objects WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName) + AND NOT EXISTS (SELECT * FROM #ExistingObjects WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName) IF @ErrorMessage IS NOT NULL BEGIN @@ -8921,7 +8969,7 @@ BEGIN AND SchemaName NOT LIKE '%[%]%' AND ObjectName NOT LIKE '%[%]%' AND IndexName NOT LIKE '%[%]%' - AND NOT EXISTS (SELECT * FROM #Indexes Indexes INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID WHERE Objects.SchemaName = SelectedIndexes.SchemaName AND Objects.ObjectName = SelectedIndexes.ObjectName AND Indexes.IndexName = SelectedIndexes.IndexName) + AND NOT EXISTS (SELECT * FROM #ExistingIndexes WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName AND IndexName = SelectedIndexes.IndexName) IF @ErrorMessage IS NOT NULL BEGIN @@ -9661,6 +9709,8 @@ BEGIN TRUNCATE TABLE #Objects TRUNCATE TABLE #Indexes TRUNCATE TABLE #Stats + TRUNCATE TABLE #ExistingObjects + TRUNCATE TABLE #ExistingIndexes DELETE FROM @tmpResumableOperations DELETE FROM @IncrementalStatsProperties From d00bea88195548b0c8c81fe087766926f74b04d6 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 18 Jul 2026 14:03:19 +0200 Subject: [PATCH 075/177] Add files via upload --- README.md | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 497a862c..8fb03bdd 100644 --- a/README.md +++ b/README.md @@ -13,24 +13,29 @@ 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 + - [DatabaseBackup.sql](/DatabaseBackup.sql): Stored procedure to back up databases + - [DatabaseIntegrityCheck.sql](/DatabaseIntegrityCheck.sql): Stored procedure to check the integrity of databases + - [IndexOptimize.sql](/IndexOptimize.sql): Stored procedure to rebuild and reorganize indexes and update statistics + - [CommandExecute.sql](/CommandExecute.sql): Stored procedure to execute and log commands + - [CommandLog.sql](/CommandLog.sql): Table to log commands + - [Queue.sql](/Queue.sql): Table for processing databases in parallel + - [QueueDatabase.sql](/QueueDatabase.sql): Table for processing databases in parallel + +Note that you always need CommandExecute; DatabaseBackup, DatabaseIntegrityCheck, and IndexOptimize use it. + +When you update DatabaseBackup, DatabaseIntegrityCheck, or IndexOptimize, you should also update CommandExecute. -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 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, Azure SQL Database, and Azure SQL Managed Instance +Supported versions: SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, Azure SQL Database, and Azure SQL Managed Instance. ## 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
  • -
+ - [SQL Server Backup](https://ola.hallengren.com/sql-server-backup.html) + - [SQL Server Integrity Check](https://ola.hallengren.com/sql-server-integrity-check.html) + - [SQL Server Index and Statistics Maintenance](https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html) + - [Frequently Asked Questions](https://ola.hallengren.com/frequently-asked-questions.html) + - [Version History](https://ola.hallengren.com/versions.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 From 5b58bf1fa58391c29baae49289f589196a799653 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 00:11:33 +0200 Subject: [PATCH 076/177] Create create-tag.yml --- workflows/create-tag.yml | 56 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 workflows/create-tag.yml diff --git a/workflows/create-tag.yml b/workflows/create-tag.yml new file mode 100644 index 00000000..cd4b3576 --- /dev/null +++ b/workflows/create-tag.yml @@ -0,0 +1,56 @@ +name: Create tag from version header + +# Runs every time you push/merge a commit to main. It reads the version +# timestamp out of the script header and creates a matching, immutable Git tag. +# Because your header timestamp includes the time down to the second, every +# release gets a unique tag - even several releases on the same day - and a +# quiet stretch with no commits simply produces no tags. + +on: + push: + branches: + - main + paths: + - MaintenanceSolution.sql # only run when this file actually changes + +permissions: + contents: write # allow the workflow to create and push a tag + +jobs: + tag: + runs-on: ubuntu-latest + steps: + - name: Check out the repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 # full history so existing tags are visible + + - name: Read version from header and create tag + run: | + set -euo pipefail + + # 1. Pull the "YYYY-MM-DD HH:MM:SS" timestamp out of the header. + VERSION=$(grep -m1 -oP '(?<=--// Version: )\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}' MaintenanceSolution.sql || true) + + if [ -z "$VERSION" ]; then + echo "No version line found in MaintenanceSolution.sql - nothing to tag." + exit 0 + fi + + # 2. Turn it into a valid tag name. + # Tags cannot contain spaces or colons, so strip the separators: + # "2026-07-16 23:38:29" -> "20260716_233829" + TAG=$(echo "$VERSION" | sed 's/[-:]//g; s/ /_/') + echo "Version in header : $VERSION" + echo "Tag name : $TAG" + + # 3. If that tag already exists, do nothing (safe to re-run). + if git ls-remote --exit-code --tags origin "refs/tags/$TAG" >/dev/null 2>&1; then + echo "Tag $TAG already exists - skipping." + exit 0 + fi + + # 4. Create the tag on this commit and push it. + git tag "$TAG" + git push origin "refs/tags/$TAG" + echo "Created tag $TAG" From 543c2ae2bd4c865dcb5ea32c4e8e045f8a64de52 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 00:20:49 +0200 Subject: [PATCH 077/177] Rename workflows/create-tag.yml to .github/workflows/create-tag.yml --- {workflows => .github/workflows}/create-tag.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {workflows => .github/workflows}/create-tag.yml (100%) diff --git a/workflows/create-tag.yml b/.github/workflows/create-tag.yml similarity index 100% rename from workflows/create-tag.yml rename to .github/workflows/create-tag.yml From 47dd31e58da8e6768cc9bdeeb49e520a0a2b789b Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 16:57:54 +0200 Subject: [PATCH 078/177] Add files via upload --- CommandExecute.sql | 26 +- DatabaseBackup.sql | 698 ++++++++++---------- DatabaseIntegrityCheck.sql | 212 +++--- IndexOptimize.sql | 308 +++++---- MaintenanceSolution.sql | 1246 ++++++++++++++++++++---------------- 5 files changed, 1371 insertions(+), 1119 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index a8534e9b..eb289b47 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-18 10:57:42 //-- + --// Version: 2026-07-19 16:57:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -81,19 +81,19 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 + VALUES('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, [State]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 + VALUES('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], Severity, [State]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 + VALUES('The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -103,55 +103,55 @@ BEGIN IF @DatabaseContext IS NULL OR NOT EXISTS (SELECT * FROM sys.databases WHERE name = @DatabaseContext) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabaseContext is not supported.', 16, 1 + VALUES('The value for the parameter @DatabaseContext is not supported.', 16, 1) END IF @Command IS NULL OR @Command = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Command is not supported.', 16, 1 + VALUES('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], Severity, [State]) - SELECT 'The value for the parameter @CommandType is not supported.', 16, 1 + VALUES('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], Severity, [State]) - SELECT 'The value for the parameter @Mode is not supported.', 16, 1 + VALUES('The value for the parameter @Mode is not supported.', 16, 1) END IF (@EncryptionKey IS NULL AND @EncryptionKeyPlaceholder IS NOT NULL) OR (@EncryptionKey IS NOT NULL AND @EncryptionKeyPlaceholder IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameters @EncryptionKey and @EncryptionKeyPlaceholder must be specified together.', 16, 1 + VALUES('The parameters @EncryptionKey and @EncryptionKeyPlaceholder must be specified together.', 16, 1) END IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 + VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) END IF LEN(@ExecuteAsUser) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ExecuteAsUser is not supported.', 16, 1 + VALUES('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]) - SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 + VALUES('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, [State]) - SELECT 'The value for the parameter @Execute is not supported.', 16, 1 + VALUES('The value for the parameter @Execute is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index e4bf281c..ae38296f 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-18 10:57:42 //-- + --// Version: 2026-07-19 16:57:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -108,7 +108,20 @@ BEGIN 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 @Parameters TABLE (ID int IDENTITY PRIMARY KEY, + [Name] nvarchar(max) NOT NULL, + ValueNvarchar nvarchar(max), + ValueInt int, + ValueDatetime datetime2) + + DECLARE @ParametersString nvarchar(max) + DECLARE @CurrentParameterName nvarchar(max) + DECLARE @CurrentParameterValueNvarchar nvarchar(max) + DECLARE @CurrentParameterValueInt int + DECLARE @CurrentParameterValueDatetime datetime2 + DECLARE @CurrentParameterDelimiter nvarchar(max) + DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 @@ -324,82 +337,85 @@ BEGIN --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','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(max)),'NULL') - SET @Parameters += ', @CleanupMode = ' + ISNULL('''' + REPLACE(@CleanupMode,'''','''''') + '''','NULL') - SET @Parameters += ', @Compress = ' + ISNULL('''' + REPLACE(@Compress,'''','''''') + '''','NULL') - SET @Parameters += ', @CompressionAlgorithm = ' + ISNULL('''' + REPLACE(@CompressionAlgorithm,'''','''''') + '''','NULL') - SET @Parameters += ', @CompressionLevel = ' + ISNULL('''' + REPLACE(@CompressionLevel,'''','''''') + '''','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(max)),'NULL') - SET @Parameters += ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar(max)),'NULL') - SET @Parameters += ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar(max)),'NULL') - SET @Parameters += ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar(max)),'NULL') - SET @Parameters += ', @MinBackupSizeForMultipleFiles = ' + ISNULL(CAST(@MinBackupSizeForMultipleFiles AS nvarchar(max)),'NULL') - SET @Parameters += ', @MaxFileSize = ' + ISNULL(CAST(@MaxFileSize AS nvarchar(max)),'NULL') - SET @Parameters += ', @CompressionLevelNumeric = ' + ISNULL(CAST(@CompressionLevelNumeric AS nvarchar(max)),'NULL') - SET @Parameters += ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL') - SET @Parameters += ', @BackupSetName = ' + ISNULL('''' + REPLACE(@BackupSetName,'''','''''') + '''','NULL') - SET @Parameters += ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar(max)),'NULL') - SET @Parameters += ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar(max)),'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('''' + @EncryptionKeyMasked + '''','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(max)),'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 += ', @MinModificationLevel = ' + ISNULL(CAST(@MinModificationLevel AS nvarchar(max)),'NULL') - SET @Parameters += ', @MinDatabaseSizeForDifferentialBackup = ' + ISNULL(CAST(@MinDatabaseSizeForDifferentialBackup AS nvarchar(max)),'NULL') - SET @Parameters += ', @MinLogSizeSinceLastLogBackup = ' + ISNULL(CAST(@MinLogSizeSinceLastLogBackup AS nvarchar(max)),'NULL') - SET @Parameters += ', @MinTimeSinceLastLogBackup = ' + ISNULL(CAST(@MinTimeSinceLastLogBackup AS nvarchar(max)),'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 += ', @DataDomainBoostNoOutputTable = ' + ISNULL('''' + REPLACE(@DataDomainBoostNoOutputTable,'''','''''') + '''','NULL') - SET @Parameters += ', @DirectoryStructure = ' + ISNULL('''' + REPLACE(@DirectoryStructure,'''','''''') + '''','NULL') - SET @Parameters += ', @AvailabilityGroupDirectoryStructure = ' + ISNULL('''' + REPLACE(@AvailabilityGroupDirectoryStructure,'''','''''') + '''','NULL') - SET @Parameters += ', @DirectoryStructureCase = ' + ISNULL('''' + REPLACE(@DirectoryStructureCase,'''','''''') + '''','NULL') - SET @Parameters += ', @FileName = ' + ISNULL('''' + REPLACE(@FileName,'''','''''') + '''','NULL') - SET @Parameters += ', @AvailabilityGroupFileName = ' + ISNULL('''' + REPLACE(@AvailabilityGroupFileName,'''','''''') + '''','NULL') - SET @Parameters += ', @FileNameCase = ' + ISNULL('''' + REPLACE(@FileNameCase,'''','''''') + '''','NULL') - SET @Parameters += ', @TokenTimezone = ' + ISNULL('''' + REPLACE(@TokenTimezone,'''','''''') + '''','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 += ', @ExcludeLogShippedFromLogBackup = ' + ISNULL('''' + REPLACE(@ExcludeLogShippedFromLogBackup,'''','''''') + '''','NULL') - SET @Parameters += ', @ExcludeSeedingFromLogBackup = ' + ISNULL('''' + REPLACE(@ExcludeSeedingFromLogBackup,'''','''''') + '''','NULL') - SET @Parameters += ', @DirectoryCheck = ' + ISNULL('''' + REPLACE(@DirectoryCheck,'''','''''') + '''','NULL') - SET @Parameters += ', @BackupOptions = ' + ISNULL('''' + REPLACE(@BackupOptions,'''','''''') + '''','NULL') - SET @Parameters += ', @Stats = ' + ISNULL(CAST(@Stats AS nvarchar(max)),'NULL') - SET @Parameters += ', @ExpireDate = ' + ISNULL('''' + CONVERT(nvarchar(max), @ExpireDate, 21) + '''','NULL') - SET @Parameters += ', @RetainDays = ' + ISNULL(CAST(@RetainDays AS nvarchar(max)),'NULL') - SET @Parameters += ', @AllowNonCopyOnlyBackupsOnForwarder = ' + ISNULL('''' + REPLACE(@AllowNonCopyOnlyBackupsOnForwarder,'''','''''') + '''','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') - SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Databases', @Databases) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Directory', @Directory) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@BackupType', @BackupType) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Verify', @Verify) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@CleanupTime', @CleanupTime) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@CleanupMode', @CleanupMode) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Compress', @Compress) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@CompressionAlgorithm', @CompressionAlgorithm) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@CompressionLevel', @CompressionLevel) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@CopyOnly', @CopyOnly) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ChangeBackupType', @ChangeBackupType) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@BackupSoftware', @BackupSoftware) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Checksum', @Checksum) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@BlockSize', @BlockSize) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@BufferCount', @BufferCount) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MaxTransferSize', @MaxTransferSize) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@NumberOfFiles', @NumberOfFiles) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MinBackupSizeForMultipleFiles', @MinBackupSizeForMultipleFiles) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MaxFileSize', @MaxFileSize) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@CompressionLevelNumeric', @CompressionLevelNumeric) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Description', @Description) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@BackupSetName', @BackupSetName) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@Threads', @Threads) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@Throttle', @Throttle) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Encrypt', @Encrypt) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@EncryptionAlgorithm', @EncryptionAlgorithm) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ServerCertificate', @ServerCertificate) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ServerAsymmetricKey', @ServerAsymmetricKey) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@EncryptionKey', @EncryptionKeyMasked) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ReadWriteFileGroups', @ReadWriteFileGroups) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@OverrideBackupPreference', @OverrideBackupPreference) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@NoRecovery', @NoRecovery) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@URL', @URL) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Credential', @Credential) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@MirrorDirectory', @MirrorDirectory) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MirrorCleanupTime', @MirrorCleanupTime) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@MirrorCleanupMode', @MirrorCleanupMode) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@MirrorURL', @MirrorURL) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroups', @AvailabilityGroups) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Updateability', @Updateability) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AdaptiveCompression', @AdaptiveCompression) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MinModificationLevel', @MinModificationLevel) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MinDatabaseSizeForDifferentialBackup', @MinDatabaseSizeForDifferentialBackup) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MinLogSizeSinceLastLogBackup', @MinLogSizeSinceLastLogBackup) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MinTimeSinceLastLogBackup', @MinTimeSinceLastLogBackup) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataDomainBoostHost', @DataDomainBoostHost) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataDomainBoostUser', @DataDomainBoostUser) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataDomainBoostDevicePath', @DataDomainBoostDevicePath) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataDomainBoostLockboxPath', @DataDomainBoostLockboxPath) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataDomainBoostNoOutputTable', @DataDomainBoostNoOutputTable) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DirectoryStructure', @DirectoryStructure) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroupDirectoryStructure', @AvailabilityGroupDirectoryStructure) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DirectoryStructureCase', @DirectoryStructureCase) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FileName', @FileName) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroupFileName', @AvailabilityGroupFileName) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FileNameCase', @FileNameCase) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@TokenTimezone', @TokenTimezone) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FileExtensionFull', @FileExtensionFull) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FileExtensionDiff', @FileExtensionDiff) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FileExtensionLog', @FileExtensionLog) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Init', @Init) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Format', @Format) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ObjectLevelRecoveryMap', @ObjectLevelRecoveryMap) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ExcludeLogShippedFromLogBackup', @ExcludeLogShippedFromLogBackup) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ExcludeSeedingFromLogBackup', @ExcludeSeedingFromLogBackup) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DirectoryCheck', @DirectoryCheck) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@BackupOptions', @BackupOptions) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@Stats', @Stats) + INSERT INTO @Parameters ([Name], ValueDatetime) VALUES('@ExpireDate', @ExpireDate) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@RetainDays', @RetainDays) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AllowNonCopyOnlyBackupsOnForwarder', @AllowNonCopyOnlyBackupsOnForwarder) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@StringDelimiter', @StringDelimiter) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabaseOrder', @DatabaseOrder) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabasesInParallel', @DatabasesInParallel) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@LogToTable', @LogToTable) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Execute', @Execute) + + SELECT @ParametersString = STRING_AGG(CAST([Name] + ' = ' + CASE WHEN ValueNvarchar IS NOT NULL THEN '''' + REPLACE(ValueNvarchar,'''','''''') + '''' WHEN ValueInt IS NOT NULL THEN CAST(ValueInt AS nvarchar(max)) WHEN ValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), ValueDatetime, 21) + '''' ELSE 'NULL' END AS nvarchar(max)), ', ') WITHIN GROUP (ORDER BY [ID] ASC) + FROM @Parameters SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -431,10 +447,10 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Parameters: ' + @Parameters + SET @StartMessage = 'Procedure: ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + @VersionTimestamp @@ -442,6 +458,32 @@ BEGIN SET @StartMessage = 'Source: https://ola.hallengren.com' RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + SET @StartMessage = 'Command:' + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'EXECUTE ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + DECLARE ParameterCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Name], ValueNvarchar, ValueInt, ValueDatetime, CASE WHEN [ID] = MAX([ID]) OVER() THEN '' ELSE ',' END FROM @Parameters ORDER BY [ID] ASC + + OPEN ParameterCursor + + FETCH ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + + WHILE @@FETCH_STATUS = 0 + BEGIN + SET @CurrentParameterMessage = @CurrentParameterName + ' = ' + CASE WHEN @CurrentParameterValueNvarchar IS NOT NULL THEN '''' + REPLACE(@CurrentParameterValueNvarchar,'''','''''') + '''' WHEN @CurrentParameterValueInt IS NOT NULL THEN CAST(@CurrentParameterValueInt AS nvarchar(max)) WHEN @CurrentParameterValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), @CurrentParameterValueDatetime, 21) + '''' ELSE 'NULL' END + @CurrentParameterDelimiter + + RAISERROR('%s',10,1,@CurrentParameterMessage) WITH NOWAIT + + FETCH NEXT FROM ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + END + + CLOSE ParameterCursor + + DEALLOCATE ParameterCursor RAISERROR(@EmptyLine,10,1) WITH NOWAIT @@ -452,55 +494,55 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 + VALUES('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, [State]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 + VALUES('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, [State]) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 + VALUES('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 '%@EncryptionKeyPlaceholder%') BEGIN 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 + VALUES('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, [State]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The transaction count is not 0.', 16, 1 + VALUES('The transaction count is not 0.', 16, 1) END IF @AmazonRDS = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The stored procedure DatabaseBackup is not supported on Amazon RDS.', 16, 1 + VALUES('The stored procedure DatabaseBackup is not supported on Amazon RDS.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -624,7 +666,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DATALENGTH(DatabaseName) = 0)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Databases is not supported.', 16, 1 + VALUES('The value for the parameter @Databases is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -719,19 +761,19 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @IsHadrEnabled = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 + VALUES('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, [State]) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2 + VALUES('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, [State]) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3 + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -747,7 +789,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The names of the following databases are not supported: ' + @ErrorMessage + '.', 16, 1 + VALUES('The names of the following databases are not supported: ' + @ErrorMessage + '.', 16, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -760,7 +802,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The names of the following databases are not unique in the file system: ' + @ErrorMessage + '.', 16, 1 + VALUES('The names of the following databases are not unique in the file system: ' + @ErrorMessage + '.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -785,7 +827,7 @@ BEGIN ELSE BEGIN INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) - SELECT 1, @DefaultDirectory, 0, 0 + VALUES(1, @DefaultDirectory, 0, 0) END END @@ -858,43 +900,43 @@ 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 = '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 + VALUES('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 same directory has been specified multiple times in the parameters @Directory and @MirrorDirectory.', 16, 2 + VALUES('The same directory has been specified multiple times in the parameters @Directory and @MirrorDirectory.', 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 number of directories for the parameters @Directory and @MirrorDirectory has to be the same.', 16, 3 + VALUES('The number of directories for the parameters @Directory and @MirrorDirectory has to be the same.', 16, 3) END IF (@Directory IS NOT NULL AND @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 + VALUES('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 + VALUES('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 'Mirrored backup is not supported when backing up to NUL.', 16, 6 + VALUES('Mirrored backup is not supported when backing up to NUL.', 16, 6) END IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'Backup to NUL is only supported with SQL Server native backups.', 16, 7 + VALUES('Backup to NUL is only supported with SQL Server native backups.', 16, 7) END ---------------------------------------------------------------------------------------------------- @@ -902,31 +944,31 @@ 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 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 + VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 1) 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, 2 + VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 2) END IF @MirrorDirectory IS NOT NULL AND @EngineEdition = 8 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 3 + VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 3) 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, 4 + VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 4) END IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND @EngineEdition <> 3) BEGIN 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, 5 + VALUES('The value for the parameter @MirrorDirectory is not supported. Mirrored backup to disk is only available in Enterprise and Developer Edition.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -956,7 +998,7 @@ BEGIN IF NOT EXISTS (SELECT * FROM @DirectoryInfo WHERE FileExists = 0 AND FileIsADirectory = 1 AND ParentDirectoryExists = 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.', 16, 1 + VALUES('The directory ' + @CurrentRootDirectoryPath + ' does not exist.', 16, 1) END UPDATE @Directories @@ -1037,19 +1079,19 @@ BEGIN IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND NOT (DirectoryPath LIKE 'https://%/%' OR DirectoryPath LIKE 's3://%/%')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @URL is not supported.', 16, 1 + VALUES('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 same URL has been specified multiple times in the parameters @URL and @MirrorURL.', 16, 2 + VALUES('The same URL has been specified multiple times in the parameters @URL and @MirrorURL.', 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 number of URLs for the parameters @URL and @MirrorURL has to be the same.', 16, 3 + VALUES('The number of URLs for the parameters @URL and @MirrorURL has to be the same.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -1057,7 +1099,7 @@ BEGIN IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND NOT (DirectoryPath LIKE 'https://%/%' OR DirectoryPath LIKE 's3://%/%')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 1 + VALUES('The value for the parameter @MirrorURL is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1161,7 +1203,7 @@ BEGIN IF @BackupType NOT IN ('FULL','DIFF','LOG') OR @BackupType IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BackupType is not supported.', 16, 1 + VALUES('The value for the parameter @BackupType is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1169,7 +1211,7 @@ BEGIN IF @EngineEdition = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.', 16, 1 + VALUES('SQL Database Managed Instance only supports COPY_ONLY full backups.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1177,25 +1219,25 @@ BEGIN IF @Verify NOT IN ('Y','N') OR @Verify IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Verify is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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, [State]) - SELECT 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.', 16, 4 + VALUES('The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -1203,37 +1245,37 @@ BEGIN IF @CleanupTime < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CleanupTime is not supported.', 16, 1 + VALUES('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, [State]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.', 16, 2 + VALUES('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 EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN 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, 3 + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.', 16, 3) END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN 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, 4 + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.', 16, 4) END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) AND (SELECT COUNT(*) FROM (SELECT @FileExtensionFull AS FileExtension UNION SELECT @FileExtensionDiff UNION SELECT @FileExtensionLog) FileExtension) <> 3 BEGIN 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 and the file extensions are not unique.', 16, 5 + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory and the file extensions are not unique.', 16, 5) END IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN 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, 6 + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.', 16, 6) END ---------------------------------------------------------------------------------------------------- @@ -1241,7 +1283,7 @@ BEGIN IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CleanupMode is not supported.', 16, 1 + VALUES('The value for the parameter @CleanupMode is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1249,26 +1291,26 @@ BEGIN IF @Compress NOT IN ('Y','N') OR @Compress IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Compress is not supported.', 16, 1 + VALUES('The value for the parameter @Compress is not supported.', 16, 1) END IF @Compress = 'Y' AND @BackupSoftware IS NULL AND NOT (@EngineEdition IN (3, 8) OR @EditionID IN (-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Compress is not supported. Backup compression is not supported in this edition of SQL Server.', 16, 2 + VALUES('The value for the parameter @Compress is not supported. Backup compression is not supported in this edition of SQL Server.', 16, 2) END IF @Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevelNumeric IS NULL OR @CompressionLevelNumeric >= 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Compress is not supported.', 16, 3 + VALUES('The value for the parameter @Compress is not supported.', 16, 3) END IF @Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevelNumeric = 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Compress is not supported.', 16, 4 + VALUES('The value for the parameter @Compress is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -1276,31 +1318,31 @@ BEGIN IF @CompressionAlgorithm NOT IN ('MS_XPRESS','QAT_DEFLATE','ZSTD') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionAlgorithm is not supported. The allowed values are MS_XPRESS, QAT_DEFLATE and ZSTD.', 16, 1 + VALUES('The value for the parameter @CompressionAlgorithm is not supported. The allowed values are MS_XPRESS, QAT_DEFLATE and ZSTD.', 16, 1) END IF @CompressionAlgorithm IS NOT NULL AND NOT (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Specifying the compression algorithm is only supported in SQL Server 2022 and later.', 16, 2 + VALUES('The value for the parameter @CompressionAlgorithm is not supported. Specifying the compression algorithm is only supported in SQL Server 2022 and later.', 16, 2) END IF @CompressionAlgorithm = 'QAT_DEFLATE' AND NOT (@EngineEdition IN(2, 3)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to QAT_DEFLATE is only supported in Standard and Enterprise Edition.', 16, 3 + VALUES('The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to QAT_DEFLATE is only supported in Standard and Enterprise Edition.', 16, 3) END IF @CompressionAlgorithm = 'ZSTD' AND NOT (@Version >= 17 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to ZSTD is only supported in SQL Server 2025 and later.', 16, 4 + VALUES('The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to ZSTD is only supported in SQL Server 2025 and later.', 16, 4) END IF @CompressionAlgorithm IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm is only supported with SQL Server native backup.', 16, 5 + VALUES('The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm is only supported with SQL Server native backup.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -1308,19 +1350,19 @@ BEGIN IF @CompressionLevel IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevel is not supported. For third-party backup software, use the parameter @CompressionLevelNumeric.', 16, 1 + VALUES('The value for the parameter @CompressionLevel is not supported. For third-party backup software, use the parameter @CompressionLevelNumeric.', 16, 1) END IF @CompressionLevel NOT IN ('LOW','MEDIUM','HIGH') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevel is not supported. The supported values are LOW, MEDIUM and HIGH.', 16, 2 + VALUES('The value for the parameter @CompressionLevel is not supported. The supported values are LOW, MEDIUM and HIGH.', 16, 2) END IF @CompressionLevel IS NOT NULL AND NOT (@Version >= 17 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevel is not supported. Setting the compression level is only supported in SQL Server 2025 and later.', 16, 3 + VALUES('The value for the parameter @CompressionLevel is not supported. Setting the compression level is only supported in SQL Server 2025 and later.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -1328,7 +1370,7 @@ BEGIN IF @CopyOnly NOT IN ('Y','N') OR @CopyOnly IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CopyOnly is not supported.', 16, 1 + VALUES('The value for the parameter @CopyOnly is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1336,13 +1378,13 @@ BEGIN IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ChangeBackupType is not supported.', 16, 1 + VALUES('The value for the parameter @ChangeBackupType is not supported.', 16, 1) END IF @ChangeBackupType = 'Y' AND NOT @BackupType IN ('DIFF', 'LOG') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'Setting @ChangeBackupType to ''Y'' is only supported with differential and log backups.', 16, 2 + VALUES('Setting @ChangeBackupType to ''Y'' is only supported with differential and log backups.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1350,37 +1392,37 @@ BEGIN IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BackupSoftware is not supported.', 16, 1 + VALUES('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 + VALUES('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, [State]) - SELECT 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.', 16, 3 + VALUES('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, [State]) - SELECT 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.', 16, 4 + VALUES('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, [State]) - SELECT 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.', 16, 5 + VALUES('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, [State]) - SELECT 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.', 16, 6 + VALUES('EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.', 16, 6) END ---------------------------------------------------------------------------------------------------- @@ -1388,7 +1430,7 @@ BEGIN IF @Checksum NOT IN ('Y','N') OR @Checksum IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Checksum is not supported.', 16, 1 + VALUES('The value for the parameter @Checksum is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1396,31 +1438,31 @@ BEGIN IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BlockSize is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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 '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 + VALUES('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' 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 + VALUES('The value for the parameter @BlockSize is not supported. This parameter is not supported with Data Domain Boost.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -1428,19 +1470,19 @@ BEGIN IF @BufferCount <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BufferCount is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @BufferCount is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -1448,31 +1490,31 @@ BEGIN IF @MaxTransferSize < 65536 OR @MaxTransferSize > 20971520 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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 '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 + VALUES('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' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 5 + VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -1480,61 +1522,61 @@ BEGIN IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('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 '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 + VALUES('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) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 6 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 9) END IF @NumberOfFiles > 32 AND @URL LIKE 's3%' AND @MirrorURL LIKE 's3%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored backups to S3 storage is 32.', 16, 10 + VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored backups to S3 storage is 32.', 16, 10) END ---------------------------------------------------------------------------------------------------- @@ -1542,13 +1584,13 @@ BEGIN IF @MinBackupSizeForMultipleFiles <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported.', 16, 1 + VALUES('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, [State]) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.', 16, 2 + VALUES('The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1556,13 +1598,13 @@ BEGIN IF @MaxFileSize <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MaxFileSize is not supported.', 16, 1 + VALUES('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, [State]) - SELECT 'The parameters @MaxFileSize and @NumberOfFiles cannot be used together.', 16, 2 + VALUES('The parameters @MaxFileSize and @NumberOfFiles cannot be used together.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1570,31 +1612,31 @@ BEGIN IF (@BackupSoftware IS NULL AND @CompressionLevelNumeric IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevelNumeric is not supported.', 16, 1 + VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 1) END IF @BackupSoftware = 'LITESPEED' AND (@CompressionLevelNumeric < 0 OR @CompressionLevelNumeric > 8) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevelNumeric is not supported.', 16, 2 + VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 2) END IF @BackupSoftware = 'SQLBACKUP' AND (@CompressionLevelNumeric < 0 OR @CompressionLevelNumeric > 4) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevelNumeric is not supported.', 16, 3 + VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 3) END IF @BackupSoftware = 'SQLSAFE' AND (@CompressionLevelNumeric < 1 OR @CompressionLevelNumeric > 4) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevelNumeric is not supported.', 16, 4 + VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 4) END IF @CompressionLevelNumeric IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevelNumeric is not supported.', 16, 5 + VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -1602,25 +1644,25 @@ BEGIN IF LEN(@Description) > 255 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Description is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @Description is not supported.', 16, 3) END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @Description LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Description is not supported.', 16, 4 + VALUES('The value for the parameter @Description is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -1628,13 +1670,13 @@ BEGIN IF LEN(@BackupSetName) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BackupSetName is not supported.', 16, 1 + VALUES('The value for the parameter @BackupSetName is not supported.', 16, 1) END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @BackupSetName LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BackupSetName is not supported.', 16, 2 + VALUES('The value for the parameter @BackupSetName is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1642,25 +1684,25 @@ BEGIN IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Threads is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @Threads is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -1668,13 +1710,13 @@ BEGIN 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 + VALUES('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) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Throttle is not supported.', 16, 2 + VALUES('The value for the parameter @Throttle is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1682,19 +1724,19 @@ BEGIN IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Encrypt is not supported.', 16, 1 + VALUES('The value for the parameter @Encrypt is not supported.', 16, 1) END IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@EngineEdition IN(3, 8) OR @EditionID IN(-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Encrypt is not supported.', 16, 2 + VALUES('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 + VALUES('The value for the parameter @Encrypt is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -1702,31 +1744,31 @@ BEGIN 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 + VALUES('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 + VALUES('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 + VALUES('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) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16, 4 + VALUES('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 + VALUES('The value for the parameter @EncryptionAlgorithm is not supported.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -1734,25 +1776,25 @@ BEGIN IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ServerCertificate is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @ServerCertificate is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -1760,25 +1802,25 @@ BEGIN 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 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @ServerAsymmetricKey is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -1786,25 +1828,25 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @EncryptionKey is not supported.', 16, 2) END IF @EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @EncryptionKey is not supported.', 16, 3 + VALUES('The value for the parameter @EncryptionKey is not supported.', 16, 3) END IF @EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @EncryptionKey is not supported.', 16, 4 + VALUES('The value for the parameter @EncryptionKey is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -1812,13 +1854,13 @@ BEGIN IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.', 16, 1 + VALUES('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 + VALUES('The value for the parameter @ReadWriteFileGroups is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1826,7 +1868,7 @@ BEGIN 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 + VALUES('The value for the parameter @OverrideBackupPreference is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1834,19 +1876,19 @@ BEGIN 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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @NoRecovery is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -1854,19 +1896,19 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @URL is not supported.', 16, 2) 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, 3 + VALUES('The value for the parameter @URL is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -1874,19 +1916,19 @@ BEGIN 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, 1 + VALUES('The value for the parameter @Credential is not supported.', 16, 1) END IF @URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) IN('SHARED ACCESS SIGNATURE','MANAGED IDENTITY','S3 ACCESS KEY')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Credential is not supported.', 16, 2 + VALUES('The value for the parameter @Credential is not supported.', 16, 2) 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, 3 + VALUES('The value for the parameter @Credential is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -1894,13 +1936,13 @@ BEGIN IF @MirrorCleanupTime < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MirrorCleanupTime is not supported.', 16, 1 + VALUES('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 + VALUES('The value for the parameter @MirrorCleanupTime is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1908,7 +1950,7 @@ BEGIN 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 + VALUES('The value for the parameter @MirrorCleanupMode is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1916,25 +1958,25 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @MirrorURL is not supported.', 16, 2) 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, 3 + VALUES('The value for the parameter @MirrorURL is not supported.', 16, 3) 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, 4 + VALUES('The value for the parameter @MirrorURL is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -1942,7 +1984,7 @@ BEGIN 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 + VALUES('The value for the parameter @Updateability is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1950,13 +1992,13 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @AdaptiveCompression is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1964,19 +2006,19 @@ BEGIN IF @MinModificationLevel <= 0 OR @MinModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinModificationLevel is not supported.', 16, 1 + VALUES('The value for the parameter @MinModificationLevel is not supported.', 16, 1) END IF @MinModificationLevel IS NOT NULL AND @ChangeBackupType = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 2 + VALUES('The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 2) END IF @MinModificationLevel IS NOT NULL AND @BackupType <> 'DIFF' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @MinModificationLevel can only be used for differential backups.', 16, 3 + VALUES('The parameter @MinModificationLevel can only be used for differential backups.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -1984,13 +2026,13 @@ BEGIN IF @MinDatabaseSizeForDifferentialBackup <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinDatabaseSizeForDifferentialBackup is not supported.', 16, 1 + VALUES('The value for the parameter @MinDatabaseSizeForDifferentialBackup is not supported.', 16, 1) END IF @MinDatabaseSizeForDifferentialBackup IS NOT NULL AND @BackupType <> 'DIFF' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @MinDatabaseSizeForDifferentialBackup can only be used for differential backups.', 16, 2 + VALUES('The parameter @MinDatabaseSizeForDifferentialBackup can only be used for differential backups.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1998,7 +2040,7 @@ BEGIN IF @MinLogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinLogSizeSinceLastLogBackup is not supported.', 16, 1 + VALUES('The value for the parameter @MinLogSizeSinceLastLogBackup is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2006,7 +2048,7 @@ BEGIN IF @MinTimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinTimeSinceLastLogBackup is not supported.', 16, 1 + VALUES('The value for the parameter @MinTimeSinceLastLogBackup is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2014,7 +2056,7 @@ BEGIN IF (@MinTimeSinceLastLogBackup IS NOT NULL AND @MinLogSizeSinceLastLogBackup IS NULL) OR (@MinTimeSinceLastLogBackup IS NULL AND @MinLogSizeSinceLastLogBackup IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameters @MinTimeSinceLastLogBackup and @MinLogSizeSinceLastLogBackup can only be used together.', 16, 1 + VALUES('The parameters @MinTimeSinceLastLogBackup and @MinLogSizeSinceLastLogBackup can only be used together.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2022,19 +2064,19 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @DataDomainBoostHost is not supported.', 16, 2) END IF @DataDomainBoostHost LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16, 3 + VALUES('The value for the parameter @DataDomainBoostHost is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2042,19 +2084,19 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @DataDomainBoostUser is not supported.', 16, 2) END IF @DataDomainBoostUser LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16, 3 + VALUES('The value for the parameter @DataDomainBoostUser is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2062,19 +2104,19 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 2) END IF @DataDomainBoostDevicePath LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 3 + VALUES('The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2082,13 +2124,13 @@ BEGIN 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 + VALUES('The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 1) END IF @DataDomainBoostLockboxPath LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 2 + VALUES('The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2096,13 +2138,13 @@ BEGIN IF @DataDomainBoostNoOutputTable NOT IN('Y','N') OR @DataDomainBoostNoOutputTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 1 + VALUES('The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 1) END IF @DataDomainBoostNoOutputTable = 'Y' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 2 + VALUES('The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2110,7 +2152,7 @@ BEGIN IF @DirectoryStructure = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DirectoryStructure is not supported.', 16, 1 + VALUES('The value for the parameter @DirectoryStructure is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2118,7 +2160,7 @@ BEGIN IF @AvailabilityGroupDirectoryStructure = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.', 16, 1 + VALUES('The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2126,7 +2168,7 @@ BEGIN IF @DirectoryStructureCase NOT IN('LOWER','UPPER') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DirectoryStructureCase is not supported.', 16, 1 + VALUES('The value for the parameter @DirectoryStructureCase is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2134,37 +2176,37 @@ BEGIN 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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @FileName is not supported.', 16, 3) END IF @FileName LIKE '%{DirectorySeparator}%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FileName is not supported.', 16, 4 + VALUES('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 + VALUES('The value for the parameter @FileName is not supported.', 16, 5) END IF @FileName LIKE '%\%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FileName is not supported.', 16, 6 + VALUES('The value for the parameter @FileName is not supported.', 16, 6) END ---------------------------------------------------------------------------------------------------- @@ -2172,43 +2214,43 @@ BEGIN IF (@IsHadrEnabled = 1 AND @AvailabilityGroupFileName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 4) END IF @AvailabilityGroupFileName LIKE '%{DirectorySeparator}%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 5 + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 5) END IF @AvailabilityGroupFileName LIKE '%/%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 6 + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 6) END IF @AvailabilityGroupFileName LIKE '%\%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 7 + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 7) END ---------------------------------------------------------------------------------------------------- @@ -2216,7 +2258,7 @@ BEGIN IF @FileNameCase NOT IN('LOWER','UPPER') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FileNameCase is not supported.', 16, 1 + VALUES('The value for the parameter @FileNameCase is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2224,7 +2266,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(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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 + VALUES('The parameter @DirectoryStructure contains one or more tokens that are not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2232,7 +2274,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(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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 + VALUES('The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2240,7 +2282,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(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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 + VALUES('The parameter @FileName contains one or more tokens that are not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2248,7 +2290,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(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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 + VALUES('The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2256,7 +2298,7 @@ BEGIN IF @TokenTimezone NOT IN('LOCAL','UTC') OR @TokenTimezone IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @TokenTimezone is not supported.', 16, 1 + VALUES('The value for the parameter @TokenTimezone is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2264,7 +2306,7 @@ BEGIN IF @FileExtensionFull LIKE '%.%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FileExtensionFull is not supported.', 16, 1 + VALUES('The value for the parameter @FileExtensionFull is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2272,7 +2314,7 @@ BEGIN IF @FileExtensionDiff LIKE '%.%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FileExtensionDiff is not supported.', 16, 1 + VALUES('The value for the parameter @FileExtensionDiff is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2280,7 +2322,7 @@ BEGIN IF @FileExtensionLog LIKE '%.%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FileExtensionLog is not supported.', 16, 1 + VALUES('The value for the parameter @FileExtensionLog is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2288,19 +2330,19 @@ BEGIN IF @Init NOT IN('Y','N') OR @Init IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Init is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @Init is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2308,19 +2350,19 @@ BEGIN IF @Format NOT IN('Y','N') OR @Format IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Format is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @Format is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2328,25 +2370,25 @@ BEGIN IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ObjectLevelRecoveryMap is not supported.', 16, 1 + VALUES('The value for the parameter @ObjectLevelRecoveryMap 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 @ObjectLevelRecoveryMap is not supported.', 16, 2 + VALUES('The value for the parameter @ObjectLevelRecoveryMap 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 @ObjectLevelRecoveryMap is not supported.', 16, 3 + VALUES('The value for the parameter @ObjectLevelRecoveryMap 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 @ObjectLevelRecoveryMap is not supported.', 16, 4 + VALUES('The value for the parameter @ObjectLevelRecoveryMap is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -2354,7 +2396,7 @@ 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 + VALUES('The value for the parameter @ExcludeLogShippedFromLogBackup is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2362,13 +2404,13 @@ BEGIN IF @ExcludeSeedingFromLogBackup NOT IN('Y','N') OR @ExcludeSeedingFromLogBackup IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ExcludeSeedingFromLogBackup is not supported.', 16, 1 + VALUES('The value for the parameter @ExcludeSeedingFromLogBackup is not supported.', 16, 1) END IF @ExcludeSeedingFromLogBackup = 'Y' AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @ExcludeSeedingFromLogBackup can only be used for log backups.', 16, 2 + VALUES('The parameter @ExcludeSeedingFromLogBackup can only be used for log backups.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2376,7 +2418,7 @@ 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 + VALUES('The value for the parameter @DirectoryCheck is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2384,7 +2426,7 @@ BEGIN IF @BackupOptions IS NOT NULL AND @URL IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BackupOptions is not supported.', 16, 1 + VALUES('The value for the parameter @BackupOptions is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2392,7 +2434,7 @@ BEGIN IF @Stats <= 0 OR @Stats > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Stats is not supported.', 16, 1 + VALUES('The value for the parameter @Stats is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2400,7 +2442,7 @@ BEGIN IF @ExpireDate IS NOT NULL AND @BackupSoftware <> 'LITESPEED' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ExpireDate is not supported.', 16, 1 + VALUES('The value for the parameter @ExpireDate is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2408,13 +2450,13 @@ BEGIN IF @RetainDays < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @RetainDays is not supported.', 16, 1 + VALUES('The value for the parameter @RetainDays is not supported.', 16, 1) END IF @RetainDays IS NOT NULL AND @BackupSoftware <> 'LITESPEED' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @RetainDays is not supported.', 16, 2 + VALUES('The value for the parameter @RetainDays is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2422,7 +2464,7 @@ BEGIN IF @AllowNonCopyOnlyBackupsOnForwarder NOT IN('Y','N') OR @AllowNonCopyOnlyBackupsOnForwarder IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AllowNonCopyOnlyBackupsOnForwarder is not supported.', 16, 1 + VALUES('The value for the parameter @AllowNonCopyOnlyBackupsOnForwarder is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2430,7 +2472,7 @@ BEGIN IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 + VALUES('The value for the parameter @StringDelimiter is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2438,13 +2480,13 @@ BEGIN 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, [State]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 + VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 1) END IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 2 + VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2452,13 +2494,13 @@ BEGIN IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 + VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) END IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 2 + VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2466,7 +2508,7 @@ BEGIN IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 + VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2474,7 +2516,7 @@ BEGIN IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Execute is not supported.', 16, 1 + VALUES('The value for the parameter @Execute is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2482,7 +2524,7 @@ BEGIN IF EXISTS(SELECT * FROM @Errors) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.', 16, 1 + VALUES('The documentation is available at https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2498,7 +2540,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') @@ -2510,7 +2552,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) END ---------------------------------------------------------------------------------------------------- @@ -2520,7 +2562,7 @@ BEGIN IF UPPER(@@SERVERNAME) <> UPPER(@ServerName) AND @IsHadrEnabled = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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 + VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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 ---------------------------------------------------------------------------------------------------- @@ -2669,7 +2711,7 @@ BEGIN FROM dbo.[Queue] WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName - AND [Parameters] = @Parameters + AND [Parameters] = @ParametersString IF @QueueID IS NULL BEGIN @@ -2679,12 +2721,12 @@ BEGIN FROM dbo.[Queue] WITH (UPDLOCK, HOLDLOCK) WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName - AND [Parameters] = @Parameters + AND [Parameters] = @ParametersString IF @QueueID IS NULL BEGIN INSERT INTO dbo.[Queue] (SchemaName, ObjectName, [Parameters]) - SELECT @SchemaName, @ObjectName, @Parameters + VALUES(@SchemaName, @ObjectName, @ParametersString) SET @QueueID = SCOPE_IDENTITY() END @@ -3161,12 +3203,12 @@ BEGIN SET @CurrentDateUTC = SYSUTCDATETIME() INSERT INTO @CurrentCleanupDates ([Type], CleanupDate) - SELECT 'CurrentTime', @CurrentDate + VALUES('CurrentTime', @CurrentDate) IF @CurrentBackupType = 'LOG' BEGIN INSERT INTO @CurrentCleanupDates ([Type], CleanupDate) - SELECT 'LatestBackupTime', @CurrentLatestBackup + VALUES('LatestBackupTime', @CurrentLatestBackup) END SELECT @CurrentDirectoryStructure = CASE @@ -3570,7 +3612,7 @@ BEGIN END INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) - SELECT 'DISK', @CurrentFilePath, 0 + VALUES('DISK', @CurrentFilePath, 0) SET @CurrentDirectoryPath = NULL SET @CurrentFileName = NULL @@ -3578,7 +3620,7 @@ BEGIN END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) - SELECT 0, 0 + VALUES(0, 0) END IF EXISTS (SELECT * FROM @CurrentDirectories WHERE Mirror = 1) @@ -3600,7 +3642,7 @@ BEGIN SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) - SELECT 'DISK', @CurrentFilePath, 1 + VALUES('DISK', @CurrentFilePath, 1) SET @CurrentDirectoryPath = NULL SET @CurrentFileName = NULL @@ -3608,7 +3650,7 @@ BEGIN END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) - SELECT 1, 0 + VALUES(1, 0) END IF EXISTS (SELECT * FROM @CurrentURLs WHERE Mirror = 0) @@ -3630,7 +3672,7 @@ BEGIN SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) - SELECT 'URL', @CurrentFilePath, 0 + VALUES('URL', @CurrentFilePath, 0) SET @CurrentDirectoryPath = NULL SET @CurrentFileName = NULL @@ -3638,7 +3680,7 @@ BEGIN END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) - SELECT 0, 0 + VALUES(0, 0) END IF EXISTS (SELECT * FROM @CurrentURLs WHERE Mirror = 1) @@ -3660,7 +3702,7 @@ BEGIN SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) - SELECT 'URL', @CurrentFilePath, 1 + VALUES('URL', @CurrentFilePath, 1) SET @CurrentDirectoryPath = NULL SET @CurrentFileName = NULL @@ -3668,7 +3710,7 @@ BEGIN END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) - SELECT 1, 0 + VALUES(1, 0) END -- Create directory @@ -3739,7 +3781,7 @@ BEGIN IF @CleanupMode = 'BEFORE_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) - SELECT 'CleanupTime', DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 + VALUES('CleanupTime', DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0) IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 0 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -3755,7 +3797,7 @@ BEGIN IF @MirrorCleanupMode = 'BEFORE_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) - SELECT 'MirrorCleanupTime', DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 + VALUES('MirrorCleanupTime', DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1) IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 1 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -4261,7 +4303,7 @@ BEGIN IF @CleanupMode = 'AFTER_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) - SELECT 'CleanupTime', DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 + VALUES('CleanupTime', DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0) IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 0 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -4277,7 +4319,7 @@ BEGIN IF @MirrorCleanupMode = 'AFTER_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) - SELECT 'MirrorCleanupTime', DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 + VALUES('MirrorCleanupTime', DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1) IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 1 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 7da5df8f..f8a13013 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-18 10:57:42 //-- + --// Version: 2026-07-19 16:57:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -55,7 +55,20 @@ BEGIN 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 @Parameters TABLE (ID int IDENTITY PRIMARY KEY, + [Name] nvarchar(max) NOT NULL, + ValueNvarchar nvarchar(max), + ValueInt int, + ValueDatetime datetime2) + + DECLARE @ParametersString nvarchar(max) + DECLARE @CurrentParameterName nvarchar(max) + DECLARE @CurrentParameterValueNvarchar nvarchar(max) + DECLARE @CurrentParameterValueInt int + DECLARE @CurrentParameterValueDatetime datetime2 + DECLARE @CurrentParameterDelimiter nvarchar(max) + DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 @@ -220,28 +233,31 @@ BEGIN --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - 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 += ', @NoInformationalMessages = ' + ISNULL('''' + REPLACE(@NoInformationalMessages,'''','''''') + '''','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(max)),'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(max)),'NULL') - SET @Parameters += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar(max)),'NULL') - SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar(max)),'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') - SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Databases', @Databases) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@CheckCommands', @CheckCommands) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@PhysicalOnly', @PhysicalOnly) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataPurity', @DataPurity) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@NoIndex', @NoIndex) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ExtendedLogicalChecks', @ExtendedLogicalChecks) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@NoInformationalMessages', @NoInformationalMessages) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@TabLock', @TabLock) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FileGroups', @FileGroups) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Objects', @Objects) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MaxDOP', @MaxDOP) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroups', @AvailabilityGroups) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroupReplicas', @AvailabilityGroupReplicas) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Updateability', @Updateability) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@TimeLimit', @TimeLimit) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@LockTimeout', @LockTimeout) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@LockMessageSeverity', @LockMessageSeverity) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@StringDelimiter', @StringDelimiter) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabaseOrder', @DatabaseOrder) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabasesInParallel', @DatabasesInParallel) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@LogToTable', @LogToTable) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Execute', @Execute) + + SELECT @ParametersString = STRING_AGG(CAST([Name] + ' = ' + CASE WHEN ValueNvarchar IS NOT NULL THEN '''' + REPLACE(ValueNvarchar,'''','''''') + '''' WHEN ValueInt IS NOT NULL THEN CAST(ValueInt AS nvarchar(max)) WHEN ValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), ValueDatetime, 21) + '''' ELSE 'NULL' END AS nvarchar(max)), ', ') WITHIN GROUP (ORDER BY [ID] ASC) + FROM @Parameters SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -273,10 +289,10 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Parameters: ' + @Parameters + SET @StartMessage = 'Procedure: ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + @VersionTimestamp @@ -284,6 +300,32 @@ BEGIN SET @StartMessage = 'Source: https://ola.hallengren.com' RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + SET @StartMessage = 'Command:' + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'EXECUTE ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + DECLARE ParameterCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Name], ValueNvarchar, ValueInt, ValueDatetime, CASE WHEN [ID] = MAX([ID]) OVER() THEN '' ELSE ',' END FROM @Parameters ORDER BY [ID] ASC + + OPEN ParameterCursor + + FETCH ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + + WHILE @@FETCH_STATUS = 0 + BEGIN + SET @CurrentParameterMessage = @CurrentParameterName + ' = ' + CASE WHEN @CurrentParameterValueNvarchar IS NOT NULL THEN '''' + REPLACE(@CurrentParameterValueNvarchar,'''','''''') + '''' WHEN @CurrentParameterValueInt IS NOT NULL THEN CAST(@CurrentParameterValueInt AS nvarchar(max)) WHEN @CurrentParameterValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), @CurrentParameterValueDatetime, 21) + '''' ELSE 'NULL' END + @CurrentParameterDelimiter + + RAISERROR('%s',10,1,@CurrentParameterMessage) WITH NOWAIT + + FETCH NEXT FROM ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + END + + CLOSE ParameterCursor + + DEALLOCATE ParameterCursor RAISERROR(@EmptyLine,10,1) WITH NOWAIT @@ -294,49 +336,49 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 + VALUES('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, [State]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 + VALUES('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, [State]) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The transaction count is not 0.', 16, 1 + VALUES('The transaction count is not 0.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -460,7 +502,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DATALENGTH(DatabaseName) = 0)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Databases is not supported.', 16, 1 + VALUES('The value for the parameter @Databases is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -555,19 +597,19 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @IsHadrEnabled = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 + VALUES('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, [State]) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2 + VALUES('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, [State]) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3 + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -706,31 +748,31 @@ BEGIN IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CheckCommands is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @CheckCommands is not supported.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -738,7 +780,7 @@ BEGIN IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @PhysicalOnly is not supported.', 16, 1 + VALUES('The value for the parameter @PhysicalOnly is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -746,13 +788,13 @@ 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 + VALUES('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 + VALUES('The parameters @PhysicalOnly and @DataPurity cannot be used together.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -760,7 +802,7 @@ BEGIN IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @NoIndex is not supported.', 16, 1 + VALUES('The value for the parameter @NoIndex is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -768,13 +810,13 @@ BEGIN IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ExtendedLogicalChecks is not supported.', 16, 1 + VALUES('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 + VALUES('The parameters @PhysicalOnly and @ExtendedLogicalChecks cannot be used together.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -782,7 +824,7 @@ BEGIN IF @NoInformationalMessages NOT IN ('Y','N') OR @NoInformationalMessages IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @NoInformationalMessages is not supported.', 16, 1 + VALUES('The value for the parameter @NoInformationalMessages is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -790,7 +832,7 @@ BEGIN IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @TabLock is not supported.', 16, 1 + VALUES('The value for the parameter @TabLock is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -798,19 +840,19 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FileGroups is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @FileGroups is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -818,19 +860,19 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Objects is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @Objects is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -838,7 +880,7 @@ BEGIN IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MaxDOP is not supported.', 16, 1 + VALUES('The value for the parameter @MaxDOP is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -846,7 +888,7 @@ BEGIN IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroupReplicas is not supported.', 16, 1 + VALUES('The value for the parameter @AvailabilityGroupReplicas is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -854,7 +896,7 @@ BEGIN 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 + VALUES('The value for the parameter @Updateability is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -862,7 +904,7 @@ BEGIN IF @TimeLimit < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @TimeLimit is not supported.', 16, 1 + VALUES('The value for the parameter @TimeLimit is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -870,13 +912,13 @@ BEGIN IF @LockTimeout < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 1 + VALUES('The value for the parameter @LockTimeout is not supported.', 16, 1) END IF @LockTimeout > 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 2 + VALUES('The value for the parameter @LockTimeout is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -884,7 +926,7 @@ BEGIN IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 + VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -892,7 +934,7 @@ BEGIN IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 + VALUES('The value for the parameter @StringDelimiter is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -900,31 +942,31 @@ BEGIN 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') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 + VALUES('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 >= 14.03029 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) 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 + VALUES('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 + VALUES('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 + VALUES('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 @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 + VALUES('The value for the parameter @DatabaseOrder is not supported. This parameter is not supported in Azure SQL Database.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -932,13 +974,13 @@ BEGIN IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 + VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) END IF @DatabasesInParallel = 'Y' AND @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 + VALUES('The value for the parameter @DatabasesInParallel is not supported. This parameter is not supported in Azure SQL Database.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -946,7 +988,7 @@ BEGIN IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 + VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -954,7 +996,7 @@ BEGIN IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Execute is not supported.', 16, 1 + VALUES('The value for the parameter @Execute is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -962,7 +1004,7 @@ BEGIN IF EXISTS(SELECT * FROM @Errors) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1 + VALUES('The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -978,7 +1020,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -990,7 +1032,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following databases in the @FileGroups parameter do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases in the @FileGroups parameter do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1002,7 +1044,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following databases in the @Objects parameter do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases in the @Objects parameter do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') @@ -1014,7 +1056,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1027,7 +1069,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN 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: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1040,7 +1082,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN 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: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) END ---------------------------------------------------------------------------------------------------- @@ -1050,7 +1092,7 @@ BEGIN IF UPPER(@@SERVERNAME) <> UPPER(@ServerName) AND @IsHadrEnabled = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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 + VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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 ---------------------------------------------------------------------------------------------------- @@ -1224,7 +1266,7 @@ BEGIN FROM dbo.[Queue] WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName - AND [Parameters] = @Parameters + AND [Parameters] = @ParametersString IF @QueueID IS NULL BEGIN @@ -1234,12 +1276,12 @@ BEGIN FROM dbo.[Queue] WITH (UPDLOCK, HOLDLOCK) WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName - AND [Parameters] = @Parameters + AND [Parameters] = @ParametersString IF @QueueID IS NULL BEGIN INSERT INTO dbo.[Queue] (SchemaName, ObjectName, [Parameters]) - SELECT @SchemaName, @ObjectName, @Parameters + VALUES(@SchemaName, @ObjectName, @ParametersString) SET @QueueID = SCOPE_IDENTITY() END diff --git a/IndexOptimize.sql b/IndexOptimize.sql index a91ecd9e..36516a4b 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-18 10:57:42 //-- + --// Version: 2026-07-19 16:57:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -75,7 +75,20 @@ BEGIN 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 @Parameters TABLE (ID int IDENTITY PRIMARY KEY, + [Name] nvarchar(max) NOT NULL, + ValueNvarchar nvarchar(max), + ValueInt int, + ValueDatetime datetime2) + + DECLARE @ParametersString nvarchar(max) + DECLARE @CurrentParameterName nvarchar(max) + DECLARE @CurrentParameterValueNvarchar nvarchar(max) + DECLARE @CurrentParameterValueInt int + DECLARE @CurrentParameterValueDatetime datetime2 + DECLARE @CurrentParameterDelimiter nvarchar(max) + DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 @@ -370,43 +383,46 @@ BEGIN --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','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(max)),'NULL') - SET @Parameters += ', @FragmentationLevel2 = ' + ISNULL(CAST(@FragmentationLevel2 AS nvarchar(max)),'NULL') - SET @Parameters += ', @MinNumberOfPages = ' + ISNULL(CAST(@MinNumberOfPages AS nvarchar(max)),'NULL') - SET @Parameters += ', @MaxNumberOfPages = ' + ISNULL(CAST(@MaxNumberOfPages AS nvarchar(max)),'NULL') - SET @Parameters += ', @SortInTempdb = ' + ISNULL('''' + REPLACE(@SortInTempdb,'''','''''') + '''','NULL') - SET @Parameters += ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar(max)),'NULL') - SET @Parameters += ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar(max)),'NULL') - SET @Parameters += ', @PadIndex = ' + ISNULL('''' + REPLACE(@PadIndex,'''','''''') + '''','NULL') - SET @Parameters += ', @DataCompression = ' + ISNULL('''' + REPLACE(@DataCompression,'''','''''') + '''','NULL') - SET @Parameters += ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)),'NULL') - SET @Parameters += ', @WaitAtLowPriorityAbortAfterWait = ' + ISNULL('''' + REPLACE(@WaitAtLowPriorityAbortAfterWait,'''','''''') + '''','NULL') - SET @Parameters += ', @Resumable = ' + ISNULL('''' + REPLACE(@Resumable,'''','''''') + '''','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(max)),'NULL') - SET @Parameters += ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar(max)),'NULL') - SET @Parameters += ', @StatisticsPersistSample = ' + ISNULL('''' + REPLACE(@StatisticsPersistSample,'''','''''') + '''','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(max)),'NULL') - SET @Parameters += ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar(max)),'NULL') - SET @Parameters += ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') - SET @Parameters += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar(max)),'NULL') - SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar(max)),'NULL') - 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') + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Databases', @Databases) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FragmentationLow', @FragmentationLow) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FragmentationMedium', @FragmentationMedium) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FragmentationHigh', @FragmentationHigh) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@FragmentationLevel1', @FragmentationLevel1) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@FragmentationLevel2', @FragmentationLevel2) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MinNumberOfPages', @MinNumberOfPages) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MaxNumberOfPages', @MaxNumberOfPages) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@SortInTempdb', @SortInTempdb) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MaxDOP', @MaxDOP) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@FillFactor', @FillFactor) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@PadIndex', @PadIndex) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataCompression', @DataCompression) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@WaitAtLowPriorityMaxDuration', @WaitAtLowPriorityMaxDuration) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@WaitAtLowPriorityAbortAfterWait', @WaitAtLowPriorityAbortAfterWait) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Resumable', @Resumable) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@LOBCompaction', @LOBCompaction) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@UpdateStatistics', @UpdateStatistics) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@OnlyModifiedStatistics', @OnlyModifiedStatistics) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@StatisticsModificationLevel', @StatisticsModificationLevel) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@StatisticsSample', @StatisticsSample) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@StatisticsPersistSample', @StatisticsPersistSample) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@StatisticsResample', @StatisticsResample) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@PartitionLevel', @PartitionLevel) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@MSShippedObjects', @MSShippedObjects) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Indexes', @Indexes) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@TimeLimit', @TimeLimit) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@Delay', @Delay) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroups', @AvailabilityGroups) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@LockTimeout', @LockTimeout) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@LockMessageSeverity', @LockMessageSeverity) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@StringDelimiter', @StringDelimiter) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabaseOrder', @DatabaseOrder) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabasesInParallel', @DatabasesInParallel) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ExecuteAsUser', @ExecuteAsUser) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@LogToTable', @LogToTable) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Execute', @Execute) + + SELECT @ParametersString = STRING_AGG(CAST([Name] + ' = ' + CASE WHEN ValueNvarchar IS NOT NULL THEN '''' + REPLACE(ValueNvarchar,'''','''''') + '''' WHEN ValueInt IS NOT NULL THEN CAST(ValueInt AS nvarchar(max)) WHEN ValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), ValueDatetime, 21) + '''' ELSE 'NULL' END AS nvarchar(max)), ', ') WITHIN GROUP (ORDER BY [ID] ASC) + FROM @Parameters SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -438,10 +454,10 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Parameters: ' + @Parameters + SET @StartMessage = 'Procedure: ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + @VersionTimestamp @@ -449,6 +465,32 @@ BEGIN SET @StartMessage = 'Source: https://ola.hallengren.com' RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + SET @StartMessage = 'Command:' + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'EXECUTE ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + DECLARE ParameterCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Name], ValueNvarchar, ValueInt, ValueDatetime, CASE WHEN [ID] = MAX([ID]) OVER() THEN '' ELSE ',' END FROM @Parameters ORDER BY [ID] ASC + + OPEN ParameterCursor + + FETCH ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + + WHILE @@FETCH_STATUS = 0 + BEGIN + SET @CurrentParameterMessage = @CurrentParameterName + ' = ' + CASE WHEN @CurrentParameterValueNvarchar IS NOT NULL THEN '''' + REPLACE(@CurrentParameterValueNvarchar,'''','''''') + '''' WHEN @CurrentParameterValueInt IS NOT NULL THEN CAST(@CurrentParameterValueInt AS nvarchar(max)) WHEN @CurrentParameterValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), @CurrentParameterValueDatetime, 21) + '''' ELSE 'NULL' END + @CurrentParameterDelimiter + + RAISERROR('%s',10,1,@CurrentParameterMessage) WITH NOWAIT + + FETCH NEXT FROM ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + END + + CLOSE ParameterCursor + + DEALLOCATE ParameterCursor RAISERROR(@EmptyLine,10,1) WITH NOWAIT @@ -459,49 +501,49 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 + VALUES('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, [State]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 + VALUES('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, [State]) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The transaction count is not 0.', 16, 1 + VALUES('The transaction count is not 0.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -624,7 +666,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DATALENGTH(DatabaseName) = 0)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Databases is not supported.', 16, 1 + VALUES('The value for the parameter @Databases is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -719,19 +761,19 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @IsHadrEnabled = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 + VALUES('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, [State]) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2 + VALUES('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, [State]) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3 + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -869,13 +911,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FragmentationLow is not supported.', 16, 1 + VALUES('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 + VALUES('The value for the parameter @FragmentationLow is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -883,13 +925,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FragmentationMedium is not supported.', 16, 1 + VALUES('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 + VALUES('The value for the parameter @FragmentationMedium is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -897,13 +939,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'High' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FragmentationHigh is not supported.', 16, 1 + VALUES('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 + VALUES('The value for the parameter @FragmentationHigh is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -911,13 +953,13 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @FragmentationLevel1 is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -925,13 +967,13 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @FragmentationLevel2 is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -939,7 +981,7 @@ BEGIN IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinNumberOfPages is not supported.', 16, 1 + VALUES('The value for the parameter @MinNumberOfPages is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -947,7 +989,7 @@ BEGIN IF @MaxNumberOfPages < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MaxNumberOfPages is not supported.', 16, 1 + VALUES('The value for the parameter @MaxNumberOfPages is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -955,7 +997,7 @@ BEGIN IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @SortInTempdb is not supported.', 16, 1 + VALUES('The value for the parameter @SortInTempdb is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -963,7 +1005,7 @@ BEGIN IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MaxDOP is not supported.', 16, 1 + VALUES('The value for the parameter @MaxDOP is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -971,7 +1013,7 @@ BEGIN IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FillFactor is not supported.', 16, 1 + VALUES('The value for the parameter @FillFactor is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -979,7 +1021,7 @@ BEGIN IF @PadIndex NOT IN('Y','N') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @PadIndex is not supported.', 16, 1 + VALUES('The value for the parameter @PadIndex is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -987,7 +1029,7 @@ BEGIN IF @DataCompression NOT IN('NONE', 'PAGE', 'ROW') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DataCompression is not supported.', 16, 1 + VALUES('The value for the parameter @DataCompression is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -995,7 +1037,7 @@ BEGIN IF @WaitAtLowPriorityMaxDuration < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1 + VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1003,7 +1045,7 @@ BEGIN IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16, 1 + VALUES('The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1011,7 +1053,7 @@ BEGIN 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 + VALUES('The parameters @WaitAtLowPriorityMaxDuration and @WaitAtLowPriorityAbortAfterWait can only be used together.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1019,13 +1061,13 @@ BEGIN 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 + VALUES('The value for the parameter @Resumable is not supported.', 16, 1) END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 2 + VALUES('You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1033,7 +1075,7 @@ BEGIN IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LOBCompaction is not supported.', 16, 1 + VALUES('The value for the parameter @LOBCompaction is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1041,7 +1083,7 @@ BEGIN IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @UpdateStatistics is not supported.', 16, 1 + VALUES('The value for the parameter @UpdateStatistics is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1049,7 +1091,7 @@ BEGIN IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @OnlyModifiedStatistics is not supported.', 16, 1 + VALUES('The value for the parameter @OnlyModifiedStatistics is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1057,7 +1099,7 @@ BEGIN IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsModificationLevel is not supported.', 16, 1 + VALUES('The value for the parameter @StatisticsModificationLevel is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1065,7 +1107,7 @@ BEGIN IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.', 16, 1 + VALUES('You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1073,7 +1115,7 @@ BEGIN IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsSample is not supported.', 16, 1 + VALUES('The value for the parameter @StatisticsSample is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1081,25 +1123,25 @@ BEGIN IF @StatisticsPersistSample NOT IN('Y','N') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 1 + VALUES('The value for the parameter @StatisticsPersistSample is not supported.', 16, 1) END IF @StatisticsPersistSample IS NOT NULL AND @StatisticsSample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @StatisticsPersistSample can only be used together with @StatisticsSample.', 16, 2 + VALUES('The parameter @StatisticsPersistSample can only be used together with @StatisticsSample.', 16, 2) END IF @StatisticsPersistSample IS NOT NULL AND @StatisticsResample = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3 + VALUES('The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3) END IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.03006 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 4 + VALUES('The value for the parameter @StatisticsPersistSample is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -1107,13 +1149,13 @@ BEGIN IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 1 + VALUES('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 + VALUES('The value for the parameter @StatisticsResample is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1121,7 +1163,7 @@ BEGIN IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @PartitionLevel is not supported.', 16, 1 + VALUES('The value for the parameter @PartitionLevel is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1129,7 +1171,7 @@ BEGIN IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MSShippedObjects is not supported.', 16, 1 + VALUES('The value for the parameter @MSShippedObjects is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1137,13 +1179,13 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Indexes is not supported.', 16, 1 + VALUES('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 + VALUES('The value for the parameter @Indexes is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1151,7 +1193,7 @@ BEGIN IF @TimeLimit < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @TimeLimit is not supported.', 16, 1 + VALUES('The value for the parameter @TimeLimit is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1159,13 +1201,13 @@ BEGIN IF @Delay < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Delay is not supported.', 16, 1 + VALUES('The value for the parameter @Delay is not supported.', 16, 1) END IF @Delay >= 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Delay is not supported.', 16, 2 + VALUES('The value for the parameter @Delay is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1173,13 +1215,13 @@ BEGIN IF @LockTimeout < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 1 + VALUES('The value for the parameter @LockTimeout is not supported.', 16, 1) END IF @LockTimeout > 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 2 + VALUES('The value for the parameter @LockTimeout is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1187,7 +1229,7 @@ BEGIN IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 + VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1195,7 +1237,7 @@ BEGIN IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 + VALUES('The value for the parameter @StringDelimiter is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1203,13 +1245,13 @@ BEGIN IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 + VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 1) END IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 2 + VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1217,13 +1259,13 @@ BEGIN IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 + VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) END IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 2 + VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1231,7 +1273,7 @@ BEGIN IF LEN(@ExecuteAsUser) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ExecuteAsUser is not supported.', 16, 1 + VALUES('The value for the parameter @ExecuteAsUser is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1239,7 +1281,7 @@ BEGIN IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 + VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1247,7 +1289,7 @@ BEGIN IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Execute is not supported.', 16, 1 + VALUES('The value for the parameter @Execute is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1255,7 +1297,7 @@ BEGIN IF EXISTS(SELECT * FROM @Errors) BEGIN 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 + VALUES('The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1271,7 +1313,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1283,7 +1325,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following databases in the @Indexes parameter do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases in the @Indexes parameter do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') @@ -1295,7 +1337,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1308,7 +1350,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN 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: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) END ---------------------------------------------------------------------------------------------------- @@ -1418,7 +1460,7 @@ BEGIN FROM dbo.[Queue] WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName - AND [Parameters] = @Parameters + AND [Parameters] = @ParametersString IF @QueueID IS NULL BEGIN @@ -1428,12 +1470,12 @@ BEGIN FROM dbo.[Queue] WITH (UPDLOCK, HOLDLOCK) WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName - AND [Parameters] = @Parameters + AND [Parameters] = @ParametersString IF @QueueID IS NULL BEGIN INSERT INTO dbo.[Queue] (SchemaName, ObjectName, [Parameters]) - SELECT @SchemaName, @ObjectName, @Parameters + VALUES(@SchemaName, @ObjectName, @ParametersString) SET @QueueID = SCOPE_IDENTITY() END @@ -2390,79 +2432,79 @@ BEGIN 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' + VALUES('SORT_IN_TEMPDB = ON') END 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' + VALUES('SORT_IN_TEMPDB = OFF') END IF @CurrentAction = 'INDEX_REBUILD_ONLINE' 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(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END + VALUES('ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END) END IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 1 AND @WaitAtLowPriorityMaxDuration IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + ')' + VALUES('WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + ')') END IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'ONLINE = OFF' + VALUES('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(max)) + VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) 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) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max)) + VALUES('FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max))) END IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END + VALUES('PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END) END IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'DATA_COMPRESSION = ' + @DataCompression + VALUES('DATA_COMPRESSION = ' + @DataCompression) END IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL) THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END + VALUES(CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL) THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END) END IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL)) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max)) + VALUES('MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max))) END IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'LOB_COMPACTION = ON' + VALUES('LOB_COMPACTION = ON') END IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'N' BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'LOB_COMPACTION = OFF' + VALUES('LOB_COMPACTION = OFF') END IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) @@ -2675,43 +2717,43 @@ BEGIN IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max)) + VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) END IF @CurrentStatisticsSample = 100 BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'FULLSCAN' + VALUES('FULLSCAN') END IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT' + VALUES('SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT') END IF @CurrentStatisticsPersistSample = 'Y' BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'PERSIST_SAMPLE_PERCENT = ON' + VALUES('PERSIST_SAMPLE_PERCENT = ON') END IF @CurrentStatisticsPersistSample = 'N' BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'PERSIST_SAMPLE_PERCENT = OFF' + VALUES('PERSIST_SAMPLE_PERCENT = OFF') END IF @CurrentNoRecompute = 1 BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'NORECOMPUTE' + VALUES('NORECOMPUTE') END IF @CurrentStatisticsResample = 'Y' BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'RESAMPLE' + VALUES('RESAMPLE') END IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 34c13d3c..37da46ee 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: 2026-07-18 10:57:42 +Version: 2026-07-19 16:57:12 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-18 10:57:42 //-- + --// Version: 2026-07-19 16:57:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -176,19 +176,19 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 + VALUES('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, [State]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 + VALUES('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], Severity, [State]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 + VALUES('The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -198,55 +198,55 @@ BEGIN IF @DatabaseContext IS NULL OR NOT EXISTS (SELECT * FROM sys.databases WHERE name = @DatabaseContext) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabaseContext is not supported.', 16, 1 + VALUES('The value for the parameter @DatabaseContext is not supported.', 16, 1) END IF @Command IS NULL OR @Command = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Command is not supported.', 16, 1 + VALUES('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], Severity, [State]) - SELECT 'The value for the parameter @CommandType is not supported.', 16, 1 + VALUES('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], Severity, [State]) - SELECT 'The value for the parameter @Mode is not supported.', 16, 1 + VALUES('The value for the parameter @Mode is not supported.', 16, 1) END IF (@EncryptionKey IS NULL AND @EncryptionKeyPlaceholder IS NOT NULL) OR (@EncryptionKey IS NOT NULL AND @EncryptionKeyPlaceholder IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameters @EncryptionKey and @EncryptionKeyPlaceholder must be specified together.', 16, 1 + VALUES('The parameters @EncryptionKey and @EncryptionKeyPlaceholder must be specified together.', 16, 1) END IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 + VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) END IF LEN(@ExecuteAsUser) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ExecuteAsUser is not supported.', 16, 1 + VALUES('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]) - SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 + VALUES('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, [State]) - SELECT 'The value for the parameter @Execute is not supported.', 16, 1 + VALUES('The value for the parameter @Execute is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-18 10:57:42 //-- + --// Version: 2026-07-19 16:57:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -507,7 +507,20 @@ BEGIN 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 @Parameters TABLE (ID int IDENTITY PRIMARY KEY, + [Name] nvarchar(max) NOT NULL, + ValueNvarchar nvarchar(max), + ValueInt int, + ValueDatetime datetime2) + + DECLARE @ParametersString nvarchar(max) + DECLARE @CurrentParameterName nvarchar(max) + DECLARE @CurrentParameterValueNvarchar nvarchar(max) + DECLARE @CurrentParameterValueInt int + DECLARE @CurrentParameterValueDatetime datetime2 + DECLARE @CurrentParameterDelimiter nvarchar(max) + DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 @@ -723,82 +736,85 @@ BEGIN --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','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(max)),'NULL') - SET @Parameters += ', @CleanupMode = ' + ISNULL('''' + REPLACE(@CleanupMode,'''','''''') + '''','NULL') - SET @Parameters += ', @Compress = ' + ISNULL('''' + REPLACE(@Compress,'''','''''') + '''','NULL') - SET @Parameters += ', @CompressionAlgorithm = ' + ISNULL('''' + REPLACE(@CompressionAlgorithm,'''','''''') + '''','NULL') - SET @Parameters += ', @CompressionLevel = ' + ISNULL('''' + REPLACE(@CompressionLevel,'''','''''') + '''','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(max)),'NULL') - SET @Parameters += ', @BufferCount = ' + ISNULL(CAST(@BufferCount AS nvarchar(max)),'NULL') - SET @Parameters += ', @MaxTransferSize = ' + ISNULL(CAST(@MaxTransferSize AS nvarchar(max)),'NULL') - SET @Parameters += ', @NumberOfFiles = ' + ISNULL(CAST(@NumberOfFiles AS nvarchar(max)),'NULL') - SET @Parameters += ', @MinBackupSizeForMultipleFiles = ' + ISNULL(CAST(@MinBackupSizeForMultipleFiles AS nvarchar(max)),'NULL') - SET @Parameters += ', @MaxFileSize = ' + ISNULL(CAST(@MaxFileSize AS nvarchar(max)),'NULL') - SET @Parameters += ', @CompressionLevelNumeric = ' + ISNULL(CAST(@CompressionLevelNumeric AS nvarchar(max)),'NULL') - SET @Parameters += ', @Description = ' + ISNULL('''' + REPLACE(@Description,'''','''''') + '''','NULL') - SET @Parameters += ', @BackupSetName = ' + ISNULL('''' + REPLACE(@BackupSetName,'''','''''') + '''','NULL') - SET @Parameters += ', @Threads = ' + ISNULL(CAST(@Threads AS nvarchar(max)),'NULL') - SET @Parameters += ', @Throttle = ' + ISNULL(CAST(@Throttle AS nvarchar(max)),'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('''' + @EncryptionKeyMasked + '''','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(max)),'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 += ', @MinModificationLevel = ' + ISNULL(CAST(@MinModificationLevel AS nvarchar(max)),'NULL') - SET @Parameters += ', @MinDatabaseSizeForDifferentialBackup = ' + ISNULL(CAST(@MinDatabaseSizeForDifferentialBackup AS nvarchar(max)),'NULL') - SET @Parameters += ', @MinLogSizeSinceLastLogBackup = ' + ISNULL(CAST(@MinLogSizeSinceLastLogBackup AS nvarchar(max)),'NULL') - SET @Parameters += ', @MinTimeSinceLastLogBackup = ' + ISNULL(CAST(@MinTimeSinceLastLogBackup AS nvarchar(max)),'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 += ', @DataDomainBoostNoOutputTable = ' + ISNULL('''' + REPLACE(@DataDomainBoostNoOutputTable,'''','''''') + '''','NULL') - SET @Parameters += ', @DirectoryStructure = ' + ISNULL('''' + REPLACE(@DirectoryStructure,'''','''''') + '''','NULL') - SET @Parameters += ', @AvailabilityGroupDirectoryStructure = ' + ISNULL('''' + REPLACE(@AvailabilityGroupDirectoryStructure,'''','''''') + '''','NULL') - SET @Parameters += ', @DirectoryStructureCase = ' + ISNULL('''' + REPLACE(@DirectoryStructureCase,'''','''''') + '''','NULL') - SET @Parameters += ', @FileName = ' + ISNULL('''' + REPLACE(@FileName,'''','''''') + '''','NULL') - SET @Parameters += ', @AvailabilityGroupFileName = ' + ISNULL('''' + REPLACE(@AvailabilityGroupFileName,'''','''''') + '''','NULL') - SET @Parameters += ', @FileNameCase = ' + ISNULL('''' + REPLACE(@FileNameCase,'''','''''') + '''','NULL') - SET @Parameters += ', @TokenTimezone = ' + ISNULL('''' + REPLACE(@TokenTimezone,'''','''''') + '''','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 += ', @ExcludeLogShippedFromLogBackup = ' + ISNULL('''' + REPLACE(@ExcludeLogShippedFromLogBackup,'''','''''') + '''','NULL') - SET @Parameters += ', @ExcludeSeedingFromLogBackup = ' + ISNULL('''' + REPLACE(@ExcludeSeedingFromLogBackup,'''','''''') + '''','NULL') - SET @Parameters += ', @DirectoryCheck = ' + ISNULL('''' + REPLACE(@DirectoryCheck,'''','''''') + '''','NULL') - SET @Parameters += ', @BackupOptions = ' + ISNULL('''' + REPLACE(@BackupOptions,'''','''''') + '''','NULL') - SET @Parameters += ', @Stats = ' + ISNULL(CAST(@Stats AS nvarchar(max)),'NULL') - SET @Parameters += ', @ExpireDate = ' + ISNULL('''' + CONVERT(nvarchar(max), @ExpireDate, 21) + '''','NULL') - SET @Parameters += ', @RetainDays = ' + ISNULL(CAST(@RetainDays AS nvarchar(max)),'NULL') - SET @Parameters += ', @AllowNonCopyOnlyBackupsOnForwarder = ' + ISNULL('''' + REPLACE(@AllowNonCopyOnlyBackupsOnForwarder,'''','''''') + '''','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') - SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Databases', @Databases) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Directory', @Directory) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@BackupType', @BackupType) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Verify', @Verify) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@CleanupTime', @CleanupTime) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@CleanupMode', @CleanupMode) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Compress', @Compress) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@CompressionAlgorithm', @CompressionAlgorithm) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@CompressionLevel', @CompressionLevel) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@CopyOnly', @CopyOnly) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ChangeBackupType', @ChangeBackupType) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@BackupSoftware', @BackupSoftware) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Checksum', @Checksum) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@BlockSize', @BlockSize) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@BufferCount', @BufferCount) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MaxTransferSize', @MaxTransferSize) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@NumberOfFiles', @NumberOfFiles) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MinBackupSizeForMultipleFiles', @MinBackupSizeForMultipleFiles) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MaxFileSize', @MaxFileSize) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@CompressionLevelNumeric', @CompressionLevelNumeric) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Description', @Description) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@BackupSetName', @BackupSetName) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@Threads', @Threads) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@Throttle', @Throttle) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Encrypt', @Encrypt) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@EncryptionAlgorithm', @EncryptionAlgorithm) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ServerCertificate', @ServerCertificate) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ServerAsymmetricKey', @ServerAsymmetricKey) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@EncryptionKey', @EncryptionKeyMasked) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ReadWriteFileGroups', @ReadWriteFileGroups) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@OverrideBackupPreference', @OverrideBackupPreference) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@NoRecovery', @NoRecovery) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@URL', @URL) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Credential', @Credential) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@MirrorDirectory', @MirrorDirectory) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MirrorCleanupTime', @MirrorCleanupTime) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@MirrorCleanupMode', @MirrorCleanupMode) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@MirrorURL', @MirrorURL) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroups', @AvailabilityGroups) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Updateability', @Updateability) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AdaptiveCompression', @AdaptiveCompression) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MinModificationLevel', @MinModificationLevel) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MinDatabaseSizeForDifferentialBackup', @MinDatabaseSizeForDifferentialBackup) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MinLogSizeSinceLastLogBackup', @MinLogSizeSinceLastLogBackup) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MinTimeSinceLastLogBackup', @MinTimeSinceLastLogBackup) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataDomainBoostHost', @DataDomainBoostHost) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataDomainBoostUser', @DataDomainBoostUser) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataDomainBoostDevicePath', @DataDomainBoostDevicePath) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataDomainBoostLockboxPath', @DataDomainBoostLockboxPath) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataDomainBoostNoOutputTable', @DataDomainBoostNoOutputTable) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DirectoryStructure', @DirectoryStructure) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroupDirectoryStructure', @AvailabilityGroupDirectoryStructure) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DirectoryStructureCase', @DirectoryStructureCase) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FileName', @FileName) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroupFileName', @AvailabilityGroupFileName) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FileNameCase', @FileNameCase) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@TokenTimezone', @TokenTimezone) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FileExtensionFull', @FileExtensionFull) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FileExtensionDiff', @FileExtensionDiff) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FileExtensionLog', @FileExtensionLog) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Init', @Init) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Format', @Format) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ObjectLevelRecoveryMap', @ObjectLevelRecoveryMap) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ExcludeLogShippedFromLogBackup', @ExcludeLogShippedFromLogBackup) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ExcludeSeedingFromLogBackup', @ExcludeSeedingFromLogBackup) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DirectoryCheck', @DirectoryCheck) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@BackupOptions', @BackupOptions) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@Stats', @Stats) + INSERT INTO @Parameters ([Name], ValueDatetime) VALUES('@ExpireDate', @ExpireDate) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@RetainDays', @RetainDays) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AllowNonCopyOnlyBackupsOnForwarder', @AllowNonCopyOnlyBackupsOnForwarder) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@StringDelimiter', @StringDelimiter) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabaseOrder', @DatabaseOrder) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabasesInParallel', @DatabasesInParallel) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@LogToTable', @LogToTable) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Execute', @Execute) + + SELECT @ParametersString = STRING_AGG(CAST([Name] + ' = ' + CASE WHEN ValueNvarchar IS NOT NULL THEN '''' + REPLACE(ValueNvarchar,'''','''''') + '''' WHEN ValueInt IS NOT NULL THEN CAST(ValueInt AS nvarchar(max)) WHEN ValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), ValueDatetime, 21) + '''' ELSE 'NULL' END AS nvarchar(max)), ', ') WITHIN GROUP (ORDER BY [ID] ASC) + FROM @Parameters SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -830,10 +846,10 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Parameters: ' + @Parameters + SET @StartMessage = 'Procedure: ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + @VersionTimestamp @@ -841,6 +857,32 @@ BEGIN SET @StartMessage = 'Source: https://ola.hallengren.com' RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + SET @StartMessage = 'Command:' + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'EXECUTE ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + DECLARE ParameterCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Name], ValueNvarchar, ValueInt, ValueDatetime, CASE WHEN [ID] = MAX([ID]) OVER() THEN '' ELSE ',' END FROM @Parameters ORDER BY [ID] ASC + + OPEN ParameterCursor + + FETCH ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + + WHILE @@FETCH_STATUS = 0 + BEGIN + SET @CurrentParameterMessage = @CurrentParameterName + ' = ' + CASE WHEN @CurrentParameterValueNvarchar IS NOT NULL THEN '''' + REPLACE(@CurrentParameterValueNvarchar,'''','''''') + '''' WHEN @CurrentParameterValueInt IS NOT NULL THEN CAST(@CurrentParameterValueInt AS nvarchar(max)) WHEN @CurrentParameterValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), @CurrentParameterValueDatetime, 21) + '''' ELSE 'NULL' END + @CurrentParameterDelimiter + + RAISERROR('%s',10,1,@CurrentParameterMessage) WITH NOWAIT + + FETCH NEXT FROM ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + END + + CLOSE ParameterCursor + + DEALLOCATE ParameterCursor RAISERROR(@EmptyLine,10,1) WITH NOWAIT @@ -851,55 +893,55 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 + VALUES('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, [State]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 + VALUES('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, [State]) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 + VALUES('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 '%@EncryptionKeyPlaceholder%') BEGIN 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 + VALUES('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, [State]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The transaction count is not 0.', 16, 1 + VALUES('The transaction count is not 0.', 16, 1) END IF @AmazonRDS = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The stored procedure DatabaseBackup is not supported on Amazon RDS.', 16, 1 + VALUES('The stored procedure DatabaseBackup is not supported on Amazon RDS.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1023,7 +1065,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DATALENGTH(DatabaseName) = 0)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Databases is not supported.', 16, 1 + VALUES('The value for the parameter @Databases is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1118,19 +1160,19 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @IsHadrEnabled = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 + VALUES('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, [State]) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2 + VALUES('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, [State]) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3 + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -1146,7 +1188,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The names of the following databases are not supported: ' + @ErrorMessage + '.', 16, 1 + VALUES('The names of the following databases are not supported: ' + @ErrorMessage + '.', 16, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1159,7 +1201,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The names of the following databases are not unique in the file system: ' + @ErrorMessage + '.', 16, 1 + VALUES('The names of the following databases are not unique in the file system: ' + @ErrorMessage + '.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1184,7 +1226,7 @@ BEGIN ELSE BEGIN INSERT INTO @Directories (ID, DirectoryPath, Mirror, Completed) - SELECT 1, @DefaultDirectory, 0, 0 + VALUES(1, @DefaultDirectory, 0, 0) END END @@ -1257,43 +1299,43 @@ 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 = '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 + VALUES('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 same directory has been specified multiple times in the parameters @Directory and @MirrorDirectory.', 16, 2 + VALUES('The same directory has been specified multiple times in the parameters @Directory and @MirrorDirectory.', 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 number of directories for the parameters @Directory and @MirrorDirectory has to be the same.', 16, 3 + VALUES('The number of directories for the parameters @Directory and @MirrorDirectory has to be the same.', 16, 3) END IF (@Directory IS NOT NULL AND @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 + VALUES('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 + VALUES('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 'Mirrored backup is not supported when backing up to NUL.', 16, 6 + VALUES('Mirrored backup is not supported when backing up to NUL.', 16, 6) END IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'Backup to NUL is only supported with SQL Server native backups.', 16, 7 + VALUES('Backup to NUL is only supported with SQL Server native backups.', 16, 7) END ---------------------------------------------------------------------------------------------------- @@ -1301,31 +1343,31 @@ 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 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 + VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 1) 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, 2 + VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 2) END IF @MirrorDirectory IS NOT NULL AND @EngineEdition = 8 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MirrorDirectory is not supported.', 16, 3 + VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 3) 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, 4 + VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 4) END IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND @EngineEdition <> 3) BEGIN 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, 5 + VALUES('The value for the parameter @MirrorDirectory is not supported. Mirrored backup to disk is only available in Enterprise and Developer Edition.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -1355,7 +1397,7 @@ BEGIN IF NOT EXISTS (SELECT * FROM @DirectoryInfo WHERE FileExists = 0 AND FileIsADirectory = 1 AND ParentDirectoryExists = 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The directory ' + @CurrentRootDirectoryPath + ' does not exist.', 16, 1 + VALUES('The directory ' + @CurrentRootDirectoryPath + ' does not exist.', 16, 1) END UPDATE @Directories @@ -1436,19 +1478,19 @@ BEGIN IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND NOT (DirectoryPath LIKE 'https://%/%' OR DirectoryPath LIKE 's3://%/%')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @URL is not supported.', 16, 1 + VALUES('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 same URL has been specified multiple times in the parameters @URL and @MirrorURL.', 16, 2 + VALUES('The same URL has been specified multiple times in the parameters @URL and @MirrorURL.', 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 number of URLs for the parameters @URL and @MirrorURL has to be the same.', 16, 3 + VALUES('The number of URLs for the parameters @URL and @MirrorURL has to be the same.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -1456,7 +1498,7 @@ BEGIN IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND NOT (DirectoryPath LIKE 'https://%/%' OR DirectoryPath LIKE 's3://%/%')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MirrorURL is not supported.', 16, 1 + VALUES('The value for the parameter @MirrorURL is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1560,7 +1602,7 @@ BEGIN IF @BackupType NOT IN ('FULL','DIFF','LOG') OR @BackupType IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BackupType is not supported.', 16, 1 + VALUES('The value for the parameter @BackupType is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1568,7 +1610,7 @@ BEGIN IF @EngineEdition = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'SQL Database Managed Instance only supports COPY_ONLY full backups.', 16, 1 + VALUES('SQL Database Managed Instance only supports COPY_ONLY full backups.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1576,25 +1618,25 @@ BEGIN IF @Verify NOT IN ('Y','N') OR @Verify IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Verify is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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, [State]) - SELECT 'The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.', 16, 4 + VALUES('The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -1602,37 +1644,37 @@ BEGIN IF @CleanupTime < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CleanupTime is not supported.', 16, 1 + VALUES('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, [State]) - SELECT 'The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.', 16, 2 + VALUES('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 EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN 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, 3 + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.', 16, 3) END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN 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, 4 + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.', 16, 4) END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) AND (SELECT COUNT(*) FROM (SELECT @FileExtensionFull AS FileExtension UNION SELECT @FileExtensionDiff UNION SELECT @FileExtensionLog) FileExtension) <> 3 BEGIN 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 and the file extensions are not unique.', 16, 5 + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory and the file extensions are not unique.', 16, 5) END IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN 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, 6 + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.', 16, 6) END ---------------------------------------------------------------------------------------------------- @@ -1640,7 +1682,7 @@ BEGIN IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CleanupMode is not supported.', 16, 1 + VALUES('The value for the parameter @CleanupMode is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1648,26 +1690,26 @@ BEGIN IF @Compress NOT IN ('Y','N') OR @Compress IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Compress is not supported.', 16, 1 + VALUES('The value for the parameter @Compress is not supported.', 16, 1) END IF @Compress = 'Y' AND @BackupSoftware IS NULL AND NOT (@EngineEdition IN (3, 8) OR @EditionID IN (-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Compress is not supported. Backup compression is not supported in this edition of SQL Server.', 16, 2 + VALUES('The value for the parameter @Compress is not supported. Backup compression is not supported in this edition of SQL Server.', 16, 2) END IF @Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevelNumeric IS NULL OR @CompressionLevelNumeric >= 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Compress is not supported.', 16, 3 + VALUES('The value for the parameter @Compress is not supported.', 16, 3) END IF @Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevelNumeric = 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Compress is not supported.', 16, 4 + VALUES('The value for the parameter @Compress is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -1675,31 +1717,31 @@ BEGIN IF @CompressionAlgorithm NOT IN ('MS_XPRESS','QAT_DEFLATE','ZSTD') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionAlgorithm is not supported. The allowed values are MS_XPRESS, QAT_DEFLATE and ZSTD.', 16, 1 + VALUES('The value for the parameter @CompressionAlgorithm is not supported. The allowed values are MS_XPRESS, QAT_DEFLATE and ZSTD.', 16, 1) END IF @CompressionAlgorithm IS NOT NULL AND NOT (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Specifying the compression algorithm is only supported in SQL Server 2022 and later.', 16, 2 + VALUES('The value for the parameter @CompressionAlgorithm is not supported. Specifying the compression algorithm is only supported in SQL Server 2022 and later.', 16, 2) END IF @CompressionAlgorithm = 'QAT_DEFLATE' AND NOT (@EngineEdition IN(2, 3)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to QAT_DEFLATE is only supported in Standard and Enterprise Edition.', 16, 3 + VALUES('The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to QAT_DEFLATE is only supported in Standard and Enterprise Edition.', 16, 3) END IF @CompressionAlgorithm = 'ZSTD' AND NOT (@Version >= 17 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to ZSTD is only supported in SQL Server 2025 and later.', 16, 4 + VALUES('The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to ZSTD is only supported in SQL Server 2025 and later.', 16, 4) END IF @CompressionAlgorithm IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm is only supported with SQL Server native backup.', 16, 5 + VALUES('The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm is only supported with SQL Server native backup.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -1707,19 +1749,19 @@ BEGIN IF @CompressionLevel IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevel is not supported. For third-party backup software, use the parameter @CompressionLevelNumeric.', 16, 1 + VALUES('The value for the parameter @CompressionLevel is not supported. For third-party backup software, use the parameter @CompressionLevelNumeric.', 16, 1) END IF @CompressionLevel NOT IN ('LOW','MEDIUM','HIGH') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevel is not supported. The supported values are LOW, MEDIUM and HIGH.', 16, 2 + VALUES('The value for the parameter @CompressionLevel is not supported. The supported values are LOW, MEDIUM and HIGH.', 16, 2) END IF @CompressionLevel IS NOT NULL AND NOT (@Version >= 17 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevel is not supported. Setting the compression level is only supported in SQL Server 2025 and later.', 16, 3 + VALUES('The value for the parameter @CompressionLevel is not supported. Setting the compression level is only supported in SQL Server 2025 and later.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -1727,7 +1769,7 @@ BEGIN IF @CopyOnly NOT IN ('Y','N') OR @CopyOnly IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CopyOnly is not supported.', 16, 1 + VALUES('The value for the parameter @CopyOnly is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1735,13 +1777,13 @@ BEGIN IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ChangeBackupType is not supported.', 16, 1 + VALUES('The value for the parameter @ChangeBackupType is not supported.', 16, 1) END IF @ChangeBackupType = 'Y' AND NOT @BackupType IN ('DIFF', 'LOG') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'Setting @ChangeBackupType to ''Y'' is only supported with differential and log backups.', 16, 2 + VALUES('Setting @ChangeBackupType to ''Y'' is only supported with differential and log backups.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1749,37 +1791,37 @@ BEGIN IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BackupSoftware is not supported.', 16, 1 + VALUES('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 + VALUES('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, [State]) - SELECT 'LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.', 16, 3 + VALUES('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, [State]) - SELECT 'Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.', 16, 4 + VALUES('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, [State]) - SELECT 'Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.', 16, 5 + VALUES('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, [State]) - SELECT 'EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.', 16, 6 + VALUES('EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.', 16, 6) END ---------------------------------------------------------------------------------------------------- @@ -1787,7 +1829,7 @@ BEGIN IF @Checksum NOT IN ('Y','N') OR @Checksum IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Checksum is not supported.', 16, 1 + VALUES('The value for the parameter @Checksum is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1795,31 +1837,31 @@ BEGIN IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BlockSize is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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 '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 + VALUES('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' 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 + VALUES('The value for the parameter @BlockSize is not supported. This parameter is not supported with Data Domain Boost.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -1827,19 +1869,19 @@ BEGIN IF @BufferCount <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BufferCount is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @BufferCount is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -1847,31 +1889,31 @@ BEGIN IF @MaxTransferSize < 65536 OR @MaxTransferSize > 20971520 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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 '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 + VALUES('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' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MaxTransferSize is not supported.', 16, 5 + VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -1879,61 +1921,61 @@ BEGIN IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('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 '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 + VALUES('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) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @NumberOfFiles is not supported.', 16, 6 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 9) END IF @NumberOfFiles > 32 AND @URL LIKE 's3%' AND @MirrorURL LIKE 's3%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored backups to S3 storage is 32.', 16, 10 + VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored backups to S3 storage is 32.', 16, 10) END ---------------------------------------------------------------------------------------------------- @@ -1941,13 +1983,13 @@ BEGIN IF @MinBackupSizeForMultipleFiles <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported.', 16, 1 + VALUES('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, [State]) - SELECT 'The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.', 16, 2 + VALUES('The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1955,13 +1997,13 @@ BEGIN IF @MaxFileSize <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MaxFileSize is not supported.', 16, 1 + VALUES('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, [State]) - SELECT 'The parameters @MaxFileSize and @NumberOfFiles cannot be used together.', 16, 2 + VALUES('The parameters @MaxFileSize and @NumberOfFiles cannot be used together.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1969,31 +2011,31 @@ BEGIN IF (@BackupSoftware IS NULL AND @CompressionLevelNumeric IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevelNumeric is not supported.', 16, 1 + VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 1) END IF @BackupSoftware = 'LITESPEED' AND (@CompressionLevelNumeric < 0 OR @CompressionLevelNumeric > 8) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevelNumeric is not supported.', 16, 2 + VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 2) END IF @BackupSoftware = 'SQLBACKUP' AND (@CompressionLevelNumeric < 0 OR @CompressionLevelNumeric > 4) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevelNumeric is not supported.', 16, 3 + VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 3) END IF @BackupSoftware = 'SQLSAFE' AND (@CompressionLevelNumeric < 1 OR @CompressionLevelNumeric > 4) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevelNumeric is not supported.', 16, 4 + VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 4) END IF @CompressionLevelNumeric IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CompressionLevelNumeric is not supported.', 16, 5 + VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -2001,25 +2043,25 @@ BEGIN IF LEN(@Description) > 255 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Description is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @Description is not supported.', 16, 3) END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @Description LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Description is not supported.', 16, 4 + VALUES('The value for the parameter @Description is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -2027,13 +2069,13 @@ BEGIN IF LEN(@BackupSetName) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BackupSetName is not supported.', 16, 1 + VALUES('The value for the parameter @BackupSetName is not supported.', 16, 1) END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @BackupSetName LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BackupSetName is not supported.', 16, 2 + VALUES('The value for the parameter @BackupSetName is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2041,25 +2083,25 @@ BEGIN IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Threads is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @Threads is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -2067,13 +2109,13 @@ BEGIN 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 + VALUES('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) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Throttle is not supported.', 16, 2 + VALUES('The value for the parameter @Throttle is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2081,19 +2123,19 @@ BEGIN IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Encrypt is not supported.', 16, 1 + VALUES('The value for the parameter @Encrypt is not supported.', 16, 1) END IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@EngineEdition IN(3, 8) OR @EditionID IN(-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Encrypt is not supported.', 16, 2 + VALUES('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 + VALUES('The value for the parameter @Encrypt is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2101,31 +2143,31 @@ BEGIN 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 + VALUES('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 + VALUES('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 + VALUES('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) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @EncryptionAlgorithm is not supported.', 16, 4 + VALUES('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 + VALUES('The value for the parameter @EncryptionAlgorithm is not supported.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -2133,25 +2175,25 @@ BEGIN IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ServerCertificate is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @ServerCertificate is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -2159,25 +2201,25 @@ BEGIN 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 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @ServerAsymmetricKey is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -2185,25 +2227,25 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @EncryptionKey is not supported.', 16, 2) END IF @EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @EncryptionKey is not supported.', 16, 3 + VALUES('The value for the parameter @EncryptionKey is not supported.', 16, 3) END IF @EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @EncryptionKey is not supported.', 16, 4 + VALUES('The value for the parameter @EncryptionKey is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -2211,13 +2253,13 @@ BEGIN IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ReadWriteFileGroups is not supported.', 16, 1 + VALUES('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 + VALUES('The value for the parameter @ReadWriteFileGroups is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2225,7 +2267,7 @@ BEGIN 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 + VALUES('The value for the parameter @OverrideBackupPreference is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2233,19 +2275,19 @@ BEGIN 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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @NoRecovery is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2253,19 +2295,19 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @URL is not supported.', 16, 2) 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, 3 + VALUES('The value for the parameter @URL is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2273,19 +2315,19 @@ BEGIN 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, 1 + VALUES('The value for the parameter @Credential is not supported.', 16, 1) END IF @URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) IN('SHARED ACCESS SIGNATURE','MANAGED IDENTITY','S3 ACCESS KEY')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Credential is not supported.', 16, 2 + VALUES('The value for the parameter @Credential is not supported.', 16, 2) 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, 3 + VALUES('The value for the parameter @Credential is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2293,13 +2335,13 @@ BEGIN IF @MirrorCleanupTime < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MirrorCleanupTime is not supported.', 16, 1 + VALUES('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 + VALUES('The value for the parameter @MirrorCleanupTime is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2307,7 +2349,7 @@ BEGIN 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 + VALUES('The value for the parameter @MirrorCleanupMode is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2315,25 +2357,25 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @MirrorURL is not supported.', 16, 2) 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, 3 + VALUES('The value for the parameter @MirrorURL is not supported.', 16, 3) 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, 4 + VALUES('The value for the parameter @MirrorURL is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -2341,7 +2383,7 @@ BEGIN 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 + VALUES('The value for the parameter @Updateability is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2349,13 +2391,13 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @AdaptiveCompression is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2363,19 +2405,19 @@ BEGIN IF @MinModificationLevel <= 0 OR @MinModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinModificationLevel is not supported.', 16, 1 + VALUES('The value for the parameter @MinModificationLevel is not supported.', 16, 1) END IF @MinModificationLevel IS NOT NULL AND @ChangeBackupType = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 2 + VALUES('The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 2) END IF @MinModificationLevel IS NOT NULL AND @BackupType <> 'DIFF' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @MinModificationLevel can only be used for differential backups.', 16, 3 + VALUES('The parameter @MinModificationLevel can only be used for differential backups.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2383,13 +2425,13 @@ BEGIN IF @MinDatabaseSizeForDifferentialBackup <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinDatabaseSizeForDifferentialBackup is not supported.', 16, 1 + VALUES('The value for the parameter @MinDatabaseSizeForDifferentialBackup is not supported.', 16, 1) END IF @MinDatabaseSizeForDifferentialBackup IS NOT NULL AND @BackupType <> 'DIFF' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @MinDatabaseSizeForDifferentialBackup can only be used for differential backups.', 16, 2 + VALUES('The parameter @MinDatabaseSizeForDifferentialBackup can only be used for differential backups.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2397,7 +2439,7 @@ BEGIN IF @MinLogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinLogSizeSinceLastLogBackup is not supported.', 16, 1 + VALUES('The value for the parameter @MinLogSizeSinceLastLogBackup is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2405,7 +2447,7 @@ BEGIN IF @MinTimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinTimeSinceLastLogBackup is not supported.', 16, 1 + VALUES('The value for the parameter @MinTimeSinceLastLogBackup is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2413,7 +2455,7 @@ BEGIN IF (@MinTimeSinceLastLogBackup IS NOT NULL AND @MinLogSizeSinceLastLogBackup IS NULL) OR (@MinTimeSinceLastLogBackup IS NULL AND @MinLogSizeSinceLastLogBackup IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameters @MinTimeSinceLastLogBackup and @MinLogSizeSinceLastLogBackup can only be used together.', 16, 1 + VALUES('The parameters @MinTimeSinceLastLogBackup and @MinLogSizeSinceLastLogBackup can only be used together.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2421,19 +2463,19 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @DataDomainBoostHost is not supported.', 16, 2) END IF @DataDomainBoostHost LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DataDomainBoostHost is not supported.', 16, 3 + VALUES('The value for the parameter @DataDomainBoostHost is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2441,19 +2483,19 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @DataDomainBoostUser is not supported.', 16, 2) END IF @DataDomainBoostUser LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DataDomainBoostUser is not supported.', 16, 3 + VALUES('The value for the parameter @DataDomainBoostUser is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2461,19 +2503,19 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 2) END IF @DataDomainBoostDevicePath LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 3 + VALUES('The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2481,13 +2523,13 @@ BEGIN 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 + VALUES('The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 1) END IF @DataDomainBoostLockboxPath LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 2 + VALUES('The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2495,13 +2537,13 @@ BEGIN IF @DataDomainBoostNoOutputTable NOT IN('Y','N') OR @DataDomainBoostNoOutputTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 1 + VALUES('The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 1) END IF @DataDomainBoostNoOutputTable = 'Y' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 2 + VALUES('The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2509,7 +2551,7 @@ BEGIN IF @DirectoryStructure = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DirectoryStructure is not supported.', 16, 1 + VALUES('The value for the parameter @DirectoryStructure is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2517,7 +2559,7 @@ BEGIN IF @AvailabilityGroupDirectoryStructure = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.', 16, 1 + VALUES('The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2525,7 +2567,7 @@ BEGIN IF @DirectoryStructureCase NOT IN('LOWER','UPPER') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DirectoryStructureCase is not supported.', 16, 1 + VALUES('The value for the parameter @DirectoryStructureCase is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2533,37 +2575,37 @@ BEGIN 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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @FileName is not supported.', 16, 3) END IF @FileName LIKE '%{DirectorySeparator}%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FileName is not supported.', 16, 4 + VALUES('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 + VALUES('The value for the parameter @FileName is not supported.', 16, 5) END IF @FileName LIKE '%\%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FileName is not supported.', 16, 6 + VALUES('The value for the parameter @FileName is not supported.', 16, 6) END ---------------------------------------------------------------------------------------------------- @@ -2571,43 +2613,43 @@ BEGIN IF (@IsHadrEnabled = 1 AND @AvailabilityGroupFileName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 4) END IF @AvailabilityGroupFileName LIKE '%{DirectorySeparator}%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 5 + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 5) END IF @AvailabilityGroupFileName LIKE '%/%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 6 + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 6) END IF @AvailabilityGroupFileName LIKE '%\%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 7 + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 7) END ---------------------------------------------------------------------------------------------------- @@ -2615,7 +2657,7 @@ BEGIN IF @FileNameCase NOT IN('LOWER','UPPER') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FileNameCase is not supported.', 16, 1 + VALUES('The value for the parameter @FileNameCase is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2623,7 +2665,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(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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 + VALUES('The parameter @DirectoryStructure contains one or more tokens that are not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2631,7 +2673,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(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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 + VALUES('The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2639,7 +2681,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(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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 + VALUES('The parameter @FileName contains one or more tokens that are not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2647,7 +2689,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(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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 + VALUES('The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2655,7 +2697,7 @@ BEGIN IF @TokenTimezone NOT IN('LOCAL','UTC') OR @TokenTimezone IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @TokenTimezone is not supported.', 16, 1 + VALUES('The value for the parameter @TokenTimezone is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2663,7 +2705,7 @@ BEGIN IF @FileExtensionFull LIKE '%.%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FileExtensionFull is not supported.', 16, 1 + VALUES('The value for the parameter @FileExtensionFull is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2671,7 +2713,7 @@ BEGIN IF @FileExtensionDiff LIKE '%.%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FileExtensionDiff is not supported.', 16, 1 + VALUES('The value for the parameter @FileExtensionDiff is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2679,7 +2721,7 @@ BEGIN IF @FileExtensionLog LIKE '%.%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FileExtensionLog is not supported.', 16, 1 + VALUES('The value for the parameter @FileExtensionLog is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2687,19 +2729,19 @@ BEGIN IF @Init NOT IN('Y','N') OR @Init IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Init is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @Init is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2707,19 +2749,19 @@ BEGIN IF @Format NOT IN('Y','N') OR @Format IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Format is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @Format is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -2727,25 +2769,25 @@ BEGIN IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ObjectLevelRecoveryMap is not supported.', 16, 1 + VALUES('The value for the parameter @ObjectLevelRecoveryMap 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 @ObjectLevelRecoveryMap is not supported.', 16, 2 + VALUES('The value for the parameter @ObjectLevelRecoveryMap 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 @ObjectLevelRecoveryMap is not supported.', 16, 3 + VALUES('The value for the parameter @ObjectLevelRecoveryMap 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 @ObjectLevelRecoveryMap is not supported.', 16, 4 + VALUES('The value for the parameter @ObjectLevelRecoveryMap is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -2753,7 +2795,7 @@ 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 + VALUES('The value for the parameter @ExcludeLogShippedFromLogBackup is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2761,13 +2803,13 @@ BEGIN IF @ExcludeSeedingFromLogBackup NOT IN('Y','N') OR @ExcludeSeedingFromLogBackup IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ExcludeSeedingFromLogBackup is not supported.', 16, 1 + VALUES('The value for the parameter @ExcludeSeedingFromLogBackup is not supported.', 16, 1) END IF @ExcludeSeedingFromLogBackup = 'Y' AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @ExcludeSeedingFromLogBackup can only be used for log backups.', 16, 2 + VALUES('The parameter @ExcludeSeedingFromLogBackup can only be used for log backups.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2775,7 +2817,7 @@ 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 + VALUES('The value for the parameter @DirectoryCheck is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2783,7 +2825,7 @@ BEGIN IF @BackupOptions IS NOT NULL AND @URL IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @BackupOptions is not supported.', 16, 1 + VALUES('The value for the parameter @BackupOptions is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2791,7 +2833,7 @@ BEGIN IF @Stats <= 0 OR @Stats > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Stats is not supported.', 16, 1 + VALUES('The value for the parameter @Stats is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2799,7 +2841,7 @@ BEGIN IF @ExpireDate IS NOT NULL AND @BackupSoftware <> 'LITESPEED' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ExpireDate is not supported.', 16, 1 + VALUES('The value for the parameter @ExpireDate is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2807,13 +2849,13 @@ BEGIN IF @RetainDays < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @RetainDays is not supported.', 16, 1 + VALUES('The value for the parameter @RetainDays is not supported.', 16, 1) END IF @RetainDays IS NOT NULL AND @BackupSoftware <> 'LITESPEED' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @RetainDays is not supported.', 16, 2 + VALUES('The value for the parameter @RetainDays is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2821,7 +2863,7 @@ BEGIN IF @AllowNonCopyOnlyBackupsOnForwarder NOT IN('Y','N') OR @AllowNonCopyOnlyBackupsOnForwarder IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AllowNonCopyOnlyBackupsOnForwarder is not supported.', 16, 1 + VALUES('The value for the parameter @AllowNonCopyOnlyBackupsOnForwarder is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2829,7 +2871,7 @@ BEGIN IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 + VALUES('The value for the parameter @StringDelimiter is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2837,13 +2879,13 @@ BEGIN 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, [State]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 + VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 1) END IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 2 + VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2851,13 +2893,13 @@ BEGIN IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 + VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) END IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 2 + VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -2865,7 +2907,7 @@ BEGIN IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 + VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2873,7 +2915,7 @@ BEGIN IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Execute is not supported.', 16, 1 + VALUES('The value for the parameter @Execute is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2881,7 +2923,7 @@ BEGIN IF EXISTS(SELECT * FROM @Errors) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-backup.html.', 16, 1 + VALUES('The documentation is available at https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2897,7 +2939,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') @@ -2909,7 +2951,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) END ---------------------------------------------------------------------------------------------------- @@ -2919,7 +2961,7 @@ BEGIN IF UPPER(@@SERVERNAME) <> UPPER(@ServerName) AND @IsHadrEnabled = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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 + VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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 ---------------------------------------------------------------------------------------------------- @@ -3068,7 +3110,7 @@ BEGIN FROM dbo.[Queue] WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName - AND [Parameters] = @Parameters + AND [Parameters] = @ParametersString IF @QueueID IS NULL BEGIN @@ -3078,12 +3120,12 @@ BEGIN FROM dbo.[Queue] WITH (UPDLOCK, HOLDLOCK) WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName - AND [Parameters] = @Parameters + AND [Parameters] = @ParametersString IF @QueueID IS NULL BEGIN INSERT INTO dbo.[Queue] (SchemaName, ObjectName, [Parameters]) - SELECT @SchemaName, @ObjectName, @Parameters + VALUES(@SchemaName, @ObjectName, @ParametersString) SET @QueueID = SCOPE_IDENTITY() END @@ -3560,12 +3602,12 @@ BEGIN SET @CurrentDateUTC = SYSUTCDATETIME() INSERT INTO @CurrentCleanupDates ([Type], CleanupDate) - SELECT 'CurrentTime', @CurrentDate + VALUES('CurrentTime', @CurrentDate) IF @CurrentBackupType = 'LOG' BEGIN INSERT INTO @CurrentCleanupDates ([Type], CleanupDate) - SELECT 'LatestBackupTime', @CurrentLatestBackup + VALUES('LatestBackupTime', @CurrentLatestBackup) END SELECT @CurrentDirectoryStructure = CASE @@ -3969,7 +4011,7 @@ BEGIN END INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) - SELECT 'DISK', @CurrentFilePath, 0 + VALUES('DISK', @CurrentFilePath, 0) SET @CurrentDirectoryPath = NULL SET @CurrentFileName = NULL @@ -3977,7 +4019,7 @@ BEGIN END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) - SELECT 0, 0 + VALUES(0, 0) END IF EXISTS (SELECT * FROM @CurrentDirectories WHERE Mirror = 1) @@ -3999,7 +4041,7 @@ BEGIN SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) - SELECT 'DISK', @CurrentFilePath, 1 + VALUES('DISK', @CurrentFilePath, 1) SET @CurrentDirectoryPath = NULL SET @CurrentFileName = NULL @@ -4007,7 +4049,7 @@ BEGIN END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) - SELECT 1, 0 + VALUES(1, 0) END IF EXISTS (SELECT * FROM @CurrentURLs WHERE Mirror = 0) @@ -4029,7 +4071,7 @@ BEGIN SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) - SELECT 'URL', @CurrentFilePath, 0 + VALUES('URL', @CurrentFilePath, 0) SET @CurrentDirectoryPath = NULL SET @CurrentFileName = NULL @@ -4037,7 +4079,7 @@ BEGIN END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) - SELECT 0, 0 + VALUES(0, 0) END IF EXISTS (SELECT * FROM @CurrentURLs WHERE Mirror = 1) @@ -4059,7 +4101,7 @@ BEGIN SET @CurrentFilePath = @CurrentDirectoryPath + @DirectorySeparator + @CurrentFileName INSERT INTO @CurrentFiles ([Type], FilePath, Mirror) - SELECT 'URL', @CurrentFilePath, 1 + VALUES('URL', @CurrentFilePath, 1) SET @CurrentDirectoryPath = NULL SET @CurrentFileName = NULL @@ -4067,7 +4109,7 @@ BEGIN END INSERT INTO @CurrentBackupSet (Mirror, VerifyCompleted) - SELECT 1, 0 + VALUES(1, 0) END -- Create directory @@ -4138,7 +4180,7 @@ BEGIN IF @CleanupMode = 'BEFORE_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) - SELECT 'CleanupTime', DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 + VALUES('CleanupTime', DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0) IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 0 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -4154,7 +4196,7 @@ BEGIN IF @MirrorCleanupMode = 'BEFORE_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) - SELECT 'MirrorCleanupTime', DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 + VALUES('MirrorCleanupTime', DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1) IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 1 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -4660,7 +4702,7 @@ BEGIN IF @CleanupMode = 'AFTER_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) - SELECT 'CleanupTime', DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0 + VALUES('CleanupTime', DATEADD(hh,-(@CleanupTime),SYSDATETIME()), 0) IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 0 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -4676,7 +4718,7 @@ BEGIN IF @MirrorCleanupMode = 'AFTER_BACKUP' BEGIN INSERT INTO @CurrentCleanupDates ([Type], CleanupDate, Mirror) - SELECT 'MirrorCleanupTime', DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1 + VALUES('MirrorCleanupTime', DATEADD(hh,-(@MirrorCleanupTime),SYSDATETIME()), 1) IF NOT EXISTS(SELECT * FROM @CurrentCleanupDates WHERE (Mirror = 1 OR Mirror IS NULL) AND CleanupDate IS NULL) BEGIN @@ -4922,7 +4964,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-18 10:57:42 //-- + --// Version: 2026-07-19 16:57:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4937,7 +4979,20 @@ BEGIN 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 @Parameters TABLE (ID int IDENTITY PRIMARY KEY, + [Name] nvarchar(max) NOT NULL, + ValueNvarchar nvarchar(max), + ValueInt int, + ValueDatetime datetime2) + + DECLARE @ParametersString nvarchar(max) + DECLARE @CurrentParameterName nvarchar(max) + DECLARE @CurrentParameterValueNvarchar nvarchar(max) + DECLARE @CurrentParameterValueInt int + DECLARE @CurrentParameterValueDatetime datetime2 + DECLARE @CurrentParameterDelimiter nvarchar(max) + DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 @@ -5102,28 +5157,31 @@ BEGIN --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - 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 += ', @NoInformationalMessages = ' + ISNULL('''' + REPLACE(@NoInformationalMessages,'''','''''') + '''','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(max)),'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(max)),'NULL') - SET @Parameters += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar(max)),'NULL') - SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar(max)),'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') - SET @Parameters += ', @Execute = ' + ISNULL('''' + REPLACE(@Execute,'''','''''') + '''','NULL') + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Databases', @Databases) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@CheckCommands', @CheckCommands) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@PhysicalOnly', @PhysicalOnly) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataPurity', @DataPurity) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@NoIndex', @NoIndex) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ExtendedLogicalChecks', @ExtendedLogicalChecks) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@NoInformationalMessages', @NoInformationalMessages) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@TabLock', @TabLock) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FileGroups', @FileGroups) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Objects', @Objects) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MaxDOP', @MaxDOP) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroups', @AvailabilityGroups) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroupReplicas', @AvailabilityGroupReplicas) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Updateability', @Updateability) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@TimeLimit', @TimeLimit) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@LockTimeout', @LockTimeout) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@LockMessageSeverity', @LockMessageSeverity) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@StringDelimiter', @StringDelimiter) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabaseOrder', @DatabaseOrder) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabasesInParallel', @DatabasesInParallel) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@LogToTable', @LogToTable) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Execute', @Execute) + + SELECT @ParametersString = STRING_AGG(CAST([Name] + ' = ' + CASE WHEN ValueNvarchar IS NOT NULL THEN '''' + REPLACE(ValueNvarchar,'''','''''') + '''' WHEN ValueInt IS NOT NULL THEN CAST(ValueInt AS nvarchar(max)) WHEN ValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), ValueDatetime, 21) + '''' ELSE 'NULL' END AS nvarchar(max)), ', ') WITHIN GROUP (ORDER BY [ID] ASC) + FROM @Parameters SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -5155,10 +5213,10 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Parameters: ' + @Parameters + SET @StartMessage = 'Procedure: ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + @VersionTimestamp @@ -5166,6 +5224,32 @@ BEGIN SET @StartMessage = 'Source: https://ola.hallengren.com' RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + SET @StartMessage = 'Command:' + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'EXECUTE ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + DECLARE ParameterCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Name], ValueNvarchar, ValueInt, ValueDatetime, CASE WHEN [ID] = MAX([ID]) OVER() THEN '' ELSE ',' END FROM @Parameters ORDER BY [ID] ASC + + OPEN ParameterCursor + + FETCH ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + + WHILE @@FETCH_STATUS = 0 + BEGIN + SET @CurrentParameterMessage = @CurrentParameterName + ' = ' + CASE WHEN @CurrentParameterValueNvarchar IS NOT NULL THEN '''' + REPLACE(@CurrentParameterValueNvarchar,'''','''''') + '''' WHEN @CurrentParameterValueInt IS NOT NULL THEN CAST(@CurrentParameterValueInt AS nvarchar(max)) WHEN @CurrentParameterValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), @CurrentParameterValueDatetime, 21) + '''' ELSE 'NULL' END + @CurrentParameterDelimiter + + RAISERROR('%s',10,1,@CurrentParameterMessage) WITH NOWAIT + + FETCH NEXT FROM ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + END + + CLOSE ParameterCursor + + DEALLOCATE ParameterCursor RAISERROR(@EmptyLine,10,1) WITH NOWAIT @@ -5176,49 +5260,49 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 + VALUES('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, [State]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 + VALUES('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, [State]) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The transaction count is not 0.', 16, 1 + VALUES('The transaction count is not 0.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5342,7 +5426,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DATALENGTH(DatabaseName) = 0)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Databases is not supported.', 16, 1 + VALUES('The value for the parameter @Databases is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5437,19 +5521,19 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @IsHadrEnabled = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 + VALUES('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, [State]) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2 + VALUES('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, [State]) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3 + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -5588,31 +5672,31 @@ BEGIN IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @CheckCommands is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @CheckCommands is not supported.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -5620,7 +5704,7 @@ BEGIN IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @PhysicalOnly is not supported.', 16, 1 + VALUES('The value for the parameter @PhysicalOnly is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5628,13 +5712,13 @@ 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 + VALUES('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 + VALUES('The parameters @PhysicalOnly and @DataPurity cannot be used together.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -5642,7 +5726,7 @@ BEGIN IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @NoIndex is not supported.', 16, 1 + VALUES('The value for the parameter @NoIndex is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5650,13 +5734,13 @@ BEGIN IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ExtendedLogicalChecks is not supported.', 16, 1 + VALUES('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 + VALUES('The parameters @PhysicalOnly and @ExtendedLogicalChecks cannot be used together.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -5664,7 +5748,7 @@ BEGIN IF @NoInformationalMessages NOT IN ('Y','N') OR @NoInformationalMessages IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @NoInformationalMessages is not supported.', 16, 1 + VALUES('The value for the parameter @NoInformationalMessages is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5672,7 +5756,7 @@ BEGIN IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @TabLock is not supported.', 16, 1 + VALUES('The value for the parameter @TabLock is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5680,19 +5764,19 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FileGroups is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @FileGroups is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -5700,19 +5784,19 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Objects is not supported.', 16, 1 + VALUES('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 + VALUES('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 + VALUES('The value for the parameter @Objects is not supported.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -5720,7 +5804,7 @@ BEGIN IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MaxDOP is not supported.', 16, 1 + VALUES('The value for the parameter @MaxDOP is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5728,7 +5812,7 @@ BEGIN IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroupReplicas is not supported.', 16, 1 + VALUES('The value for the parameter @AvailabilityGroupReplicas is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5736,7 +5820,7 @@ BEGIN 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 + VALUES('The value for the parameter @Updateability is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5744,7 +5828,7 @@ BEGIN IF @TimeLimit < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @TimeLimit is not supported.', 16, 1 + VALUES('The value for the parameter @TimeLimit is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5752,13 +5836,13 @@ BEGIN IF @LockTimeout < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 1 + VALUES('The value for the parameter @LockTimeout is not supported.', 16, 1) END IF @LockTimeout > 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 2 + VALUES('The value for the parameter @LockTimeout is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -5766,7 +5850,7 @@ BEGIN IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 + VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5774,7 +5858,7 @@ BEGIN IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 + VALUES('The value for the parameter @StringDelimiter is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5782,31 +5866,31 @@ BEGIN 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') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 + VALUES('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 >= 14.03029 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) 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 + VALUES('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 + VALUES('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 + VALUES('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 @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 + VALUES('The value for the parameter @DatabaseOrder is not supported. This parameter is not supported in Azure SQL Database.', 16, 5) END ---------------------------------------------------------------------------------------------------- @@ -5814,13 +5898,13 @@ BEGIN IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 + VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) END IF @DatabasesInParallel = 'Y' AND @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 + VALUES('The value for the parameter @DatabasesInParallel is not supported. This parameter is not supported in Azure SQL Database.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -5828,7 +5912,7 @@ BEGIN IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 + VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5836,7 +5920,7 @@ BEGIN IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Execute is not supported.', 16, 1 + VALUES('The value for the parameter @Execute is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5844,7 +5928,7 @@ BEGIN IF EXISTS(SELECT * FROM @Errors) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1 + VALUES('The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5860,7 +5944,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -5872,7 +5956,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following databases in the @FileGroups parameter do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases in the @FileGroups parameter do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -5884,7 +5968,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following databases in the @Objects parameter do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases in the @Objects parameter do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') @@ -5896,7 +5980,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -5909,7 +5993,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN 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: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -5922,7 +6006,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN 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: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) END ---------------------------------------------------------------------------------------------------- @@ -5932,7 +6016,7 @@ BEGIN IF UPPER(@@SERVERNAME) <> UPPER(@ServerName) AND @IsHadrEnabled = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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 + VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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 ---------------------------------------------------------------------------------------------------- @@ -6106,7 +6190,7 @@ BEGIN FROM dbo.[Queue] WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName - AND [Parameters] = @Parameters + AND [Parameters] = @ParametersString IF @QueueID IS NULL BEGIN @@ -6116,12 +6200,12 @@ BEGIN FROM dbo.[Queue] WITH (UPDLOCK, HOLDLOCK) WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName - AND [Parameters] = @Parameters + AND [Parameters] = @ParametersString IF @QueueID IS NULL BEGIN INSERT INTO dbo.[Queue] (SchemaName, ObjectName, [Parameters]) - SELECT @SchemaName, @ObjectName, @Parameters + VALUES(@SchemaName, @ObjectName, @ParametersString) SET @QueueID = SCOPE_IDENTITY() END @@ -6891,7 +6975,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-18 10:57:42 //-- + --// Version: 2026-07-19 16:57:12 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6910,7 +6994,20 @@ BEGIN 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 @Parameters TABLE (ID int IDENTITY PRIMARY KEY, + [Name] nvarchar(max) NOT NULL, + ValueNvarchar nvarchar(max), + ValueInt int, + ValueDatetime datetime2) + + DECLARE @ParametersString nvarchar(max) + DECLARE @CurrentParameterName nvarchar(max) + DECLARE @CurrentParameterValueNvarchar nvarchar(max) + DECLARE @CurrentParameterValueInt int + DECLARE @CurrentParameterValueDatetime datetime2 + DECLARE @CurrentParameterDelimiter nvarchar(max) + DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 @@ -7205,43 +7302,46 @@ BEGIN --// Log initial information //-- ---------------------------------------------------------------------------------------------------- - SET @Parameters = '@Databases = ' + ISNULL('''' + REPLACE(@Databases,'''','''''') + '''','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(max)),'NULL') - SET @Parameters += ', @FragmentationLevel2 = ' + ISNULL(CAST(@FragmentationLevel2 AS nvarchar(max)),'NULL') - SET @Parameters += ', @MinNumberOfPages = ' + ISNULL(CAST(@MinNumberOfPages AS nvarchar(max)),'NULL') - SET @Parameters += ', @MaxNumberOfPages = ' + ISNULL(CAST(@MaxNumberOfPages AS nvarchar(max)),'NULL') - SET @Parameters += ', @SortInTempdb = ' + ISNULL('''' + REPLACE(@SortInTempdb,'''','''''') + '''','NULL') - SET @Parameters += ', @MaxDOP = ' + ISNULL(CAST(@MaxDOP AS nvarchar(max)),'NULL') - SET @Parameters += ', @FillFactor = ' + ISNULL(CAST(@FillFactor AS nvarchar(max)),'NULL') - SET @Parameters += ', @PadIndex = ' + ISNULL('''' + REPLACE(@PadIndex,'''','''''') + '''','NULL') - SET @Parameters += ', @DataCompression = ' + ISNULL('''' + REPLACE(@DataCompression,'''','''''') + '''','NULL') - SET @Parameters += ', @WaitAtLowPriorityMaxDuration = ' + ISNULL(CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)),'NULL') - SET @Parameters += ', @WaitAtLowPriorityAbortAfterWait = ' + ISNULL('''' + REPLACE(@WaitAtLowPriorityAbortAfterWait,'''','''''') + '''','NULL') - SET @Parameters += ', @Resumable = ' + ISNULL('''' + REPLACE(@Resumable,'''','''''') + '''','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(max)),'NULL') - SET @Parameters += ', @StatisticsSample = ' + ISNULL(CAST(@StatisticsSample AS nvarchar(max)),'NULL') - SET @Parameters += ', @StatisticsPersistSample = ' + ISNULL('''' + REPLACE(@StatisticsPersistSample,'''','''''') + '''','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(max)),'NULL') - SET @Parameters += ', @Delay = ' + ISNULL(CAST(@Delay AS nvarchar(max)),'NULL') - SET @Parameters += ', @AvailabilityGroups = ' + ISNULL('''' + REPLACE(@AvailabilityGroups,'''','''''') + '''','NULL') - SET @Parameters += ', @LockTimeout = ' + ISNULL(CAST(@LockTimeout AS nvarchar(max)),'NULL') - SET @Parameters += ', @LockMessageSeverity = ' + ISNULL(CAST(@LockMessageSeverity AS nvarchar(max)),'NULL') - 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') + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Databases', @Databases) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FragmentationLow', @FragmentationLow) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FragmentationMedium', @FragmentationMedium) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FragmentationHigh', @FragmentationHigh) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@FragmentationLevel1', @FragmentationLevel1) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@FragmentationLevel2', @FragmentationLevel2) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MinNumberOfPages', @MinNumberOfPages) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MaxNumberOfPages', @MaxNumberOfPages) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@SortInTempdb', @SortInTempdb) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MaxDOP', @MaxDOP) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@FillFactor', @FillFactor) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@PadIndex', @PadIndex) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataCompression', @DataCompression) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@WaitAtLowPriorityMaxDuration', @WaitAtLowPriorityMaxDuration) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@WaitAtLowPriorityAbortAfterWait', @WaitAtLowPriorityAbortAfterWait) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Resumable', @Resumable) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@LOBCompaction', @LOBCompaction) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@UpdateStatistics', @UpdateStatistics) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@OnlyModifiedStatistics', @OnlyModifiedStatistics) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@StatisticsModificationLevel', @StatisticsModificationLevel) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@StatisticsSample', @StatisticsSample) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@StatisticsPersistSample', @StatisticsPersistSample) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@StatisticsResample', @StatisticsResample) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@PartitionLevel', @PartitionLevel) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@MSShippedObjects', @MSShippedObjects) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Indexes', @Indexes) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@TimeLimit', @TimeLimit) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@Delay', @Delay) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroups', @AvailabilityGroups) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@LockTimeout', @LockTimeout) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@LockMessageSeverity', @LockMessageSeverity) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@StringDelimiter', @StringDelimiter) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabaseOrder', @DatabaseOrder) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabasesInParallel', @DatabasesInParallel) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ExecuteAsUser', @ExecuteAsUser) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@LogToTable', @LogToTable) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Execute', @Execute) + + SELECT @ParametersString = STRING_AGG(CAST([Name] + ' = ' + CASE WHEN ValueNvarchar IS NOT NULL THEN '''' + REPLACE(ValueNvarchar,'''','''''') + '''' WHEN ValueInt IS NOT NULL THEN CAST(ValueInt AS nvarchar(max)) WHEN ValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), ValueDatetime, 21) + '''' ELSE 'NULL' END AS nvarchar(max)), ', ') WITHIN GROUP (ORDER BY [ID] ASC) + FROM @Parameters SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -7273,10 +7373,10 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - SET @StartMessage = 'Procedure: ' + QUOTENAME(DB_NAME()) + '.' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - SET @StartMessage = 'Parameters: ' + @Parameters + SET @StartMessage = 'Procedure: ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Version: ' + @VersionTimestamp @@ -7284,6 +7384,32 @@ BEGIN SET @StartMessage = 'Source: https://ola.hallengren.com' RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + SET @StartMessage = 'Command:' + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'EXECUTE ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + DECLARE ParameterCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Name], ValueNvarchar, ValueInt, ValueDatetime, CASE WHEN [ID] = MAX([ID]) OVER() THEN '' ELSE ',' END FROM @Parameters ORDER BY [ID] ASC + + OPEN ParameterCursor + + FETCH ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + + WHILE @@FETCH_STATUS = 0 + BEGIN + SET @CurrentParameterMessage = @CurrentParameterName + ' = ' + CASE WHEN @CurrentParameterValueNvarchar IS NOT NULL THEN '''' + REPLACE(@CurrentParameterValueNvarchar,'''','''''') + '''' WHEN @CurrentParameterValueInt IS NOT NULL THEN CAST(@CurrentParameterValueInt AS nvarchar(max)) WHEN @CurrentParameterValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), @CurrentParameterValueDatetime, 21) + '''' ELSE 'NULL' END + @CurrentParameterDelimiter + + RAISERROR('%s',10,1,@CurrentParameterMessage) WITH NOWAIT + + FETCH NEXT FROM ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + END + + CLOSE ParameterCursor + + DEALLOCATE ParameterCursor RAISERROR(@EmptyLine,10,1) WITH NOWAIT @@ -7294,49 +7420,49 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1 + VALUES('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, [State]) - SELECT 'QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1 + VALUES('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, [State]) - SELECT 'The stored procedure CommandExecute is missing. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The stored procedure CommandExecute needs to be updated. Download https://ola.hallengren.com/scripts/CommandExecute.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1 + VALUES('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, [State]) - SELECT 'The transaction count is not 0.', 16, 1 + VALUES('The transaction count is not 0.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7459,7 +7585,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DATALENGTH(DatabaseName) = 0)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Databases is not supported.', 16, 1 + VALUES('The value for the parameter @Databases is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7554,19 +7680,19 @@ BEGIN IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @IsHadrEnabled = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @AvailabilityGroups is not supported.', 16, 1 + VALUES('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, [State]) - SELECT 'You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2 + VALUES('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, [State]) - SELECT 'You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3 + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -7704,13 +7830,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FragmentationLow is not supported.', 16, 1 + VALUES('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 + VALUES('The value for the parameter @FragmentationLow is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -7718,13 +7844,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FragmentationMedium is not supported.', 16, 1 + VALUES('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 + VALUES('The value for the parameter @FragmentationMedium is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -7732,13 +7858,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'High' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FragmentationHigh is not supported.', 16, 1 + VALUES('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 + VALUES('The value for the parameter @FragmentationHigh is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -7746,13 +7872,13 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @FragmentationLevel1 is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -7760,13 +7886,13 @@ BEGIN 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 + VALUES('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 + VALUES('The value for the parameter @FragmentationLevel2 is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -7774,7 +7900,7 @@ BEGIN IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MinNumberOfPages is not supported.', 16, 1 + VALUES('The value for the parameter @MinNumberOfPages is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7782,7 +7908,7 @@ BEGIN IF @MaxNumberOfPages < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MaxNumberOfPages is not supported.', 16, 1 + VALUES('The value for the parameter @MaxNumberOfPages is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7790,7 +7916,7 @@ BEGIN IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @SortInTempdb is not supported.', 16, 1 + VALUES('The value for the parameter @SortInTempdb is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7798,7 +7924,7 @@ BEGIN IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MaxDOP is not supported.', 16, 1 + VALUES('The value for the parameter @MaxDOP is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7806,7 +7932,7 @@ BEGIN IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @FillFactor is not supported.', 16, 1 + VALUES('The value for the parameter @FillFactor is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7814,7 +7940,7 @@ BEGIN IF @PadIndex NOT IN('Y','N') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @PadIndex is not supported.', 16, 1 + VALUES('The value for the parameter @PadIndex is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7822,7 +7948,7 @@ BEGIN IF @DataCompression NOT IN('NONE', 'PAGE', 'ROW') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DataCompression is not supported.', 16, 1 + VALUES('The value for the parameter @DataCompression is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7830,7 +7956,7 @@ BEGIN IF @WaitAtLowPriorityMaxDuration < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1 + VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7838,7 +7964,7 @@ BEGIN IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16, 1 + VALUES('The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7846,7 +7972,7 @@ BEGIN 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 + VALUES('The parameters @WaitAtLowPriorityMaxDuration and @WaitAtLowPriorityAbortAfterWait can only be used together.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7854,13 +7980,13 @@ BEGIN 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 + VALUES('The value for the parameter @Resumable is not supported.', 16, 1) END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 2 + VALUES('You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -7868,7 +7994,7 @@ BEGIN IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LOBCompaction is not supported.', 16, 1 + VALUES('The value for the parameter @LOBCompaction is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7876,7 +8002,7 @@ BEGIN IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @UpdateStatistics is not supported.', 16, 1 + VALUES('The value for the parameter @UpdateStatistics is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7884,7 +8010,7 @@ BEGIN IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @OnlyModifiedStatistics is not supported.', 16, 1 + VALUES('The value for the parameter @OnlyModifiedStatistics is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7892,7 +8018,7 @@ BEGIN IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsModificationLevel is not supported.', 16, 1 + VALUES('The value for the parameter @StatisticsModificationLevel is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7900,7 +8026,7 @@ BEGIN IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.', 16, 1 + VALUES('You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7908,7 +8034,7 @@ BEGIN IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsSample is not supported.', 16, 1 + VALUES('The value for the parameter @StatisticsSample is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7916,25 +8042,25 @@ BEGIN IF @StatisticsPersistSample NOT IN('Y','N') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 1 + VALUES('The value for the parameter @StatisticsPersistSample is not supported.', 16, 1) END IF @StatisticsPersistSample IS NOT NULL AND @StatisticsSample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameter @StatisticsPersistSample can only be used together with @StatisticsSample.', 16, 2 + VALUES('The parameter @StatisticsPersistSample can only be used together with @StatisticsSample.', 16, 2) END IF @StatisticsPersistSample IS NOT NULL AND @StatisticsResample = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3 + VALUES('The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3) END IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.03006 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsPersistSample is not supported.', 16, 4 + VALUES('The value for the parameter @StatisticsPersistSample is not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -7942,13 +8068,13 @@ BEGIN IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StatisticsResample is not supported.', 16, 1 + VALUES('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 + VALUES('The value for the parameter @StatisticsResample is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -7956,7 +8082,7 @@ BEGIN IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @PartitionLevel is not supported.', 16, 1 + VALUES('The value for the parameter @PartitionLevel is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7964,7 +8090,7 @@ BEGIN IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @MSShippedObjects is not supported.', 16, 1 + VALUES('The value for the parameter @MSShippedObjects is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7972,13 +8098,13 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Indexes is not supported.', 16, 1 + VALUES('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 + VALUES('The value for the parameter @Indexes is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -7986,7 +8112,7 @@ BEGIN IF @TimeLimit < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @TimeLimit is not supported.', 16, 1 + VALUES('The value for the parameter @TimeLimit is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7994,13 +8120,13 @@ BEGIN IF @Delay < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Delay is not supported.', 16, 1 + VALUES('The value for the parameter @Delay is not supported.', 16, 1) END IF @Delay >= 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Delay is not supported.', 16, 2 + VALUES('The value for the parameter @Delay is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -8008,13 +8134,13 @@ BEGIN IF @LockTimeout < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 1 + VALUES('The value for the parameter @LockTimeout is not supported.', 16, 1) END IF @LockTimeout > 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LockTimeout is not supported.', 16, 2 + VALUES('The value for the parameter @LockTimeout is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -8022,7 +8148,7 @@ BEGIN IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LockMessageSeverity is not supported.', 16, 1 + VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8030,7 +8156,7 @@ BEGIN IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @StringDelimiter is not supported.', 16, 1 + VALUES('The value for the parameter @StringDelimiter is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8038,13 +8164,13 @@ BEGIN IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 1 + VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 1) END IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabaseOrder is not supported.', 16, 2 + VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -8052,13 +8178,13 @@ BEGIN IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 1 + VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) END IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @DatabasesInParallel is not supported.', 16, 2 + VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -8066,7 +8192,7 @@ BEGIN IF LEN(@ExecuteAsUser) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @ExecuteAsUser is not supported.', 16, 1 + VALUES('The value for the parameter @ExecuteAsUser is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8074,7 +8200,7 @@ BEGIN IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @LogToTable is not supported.', 16, 1 + VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8082,7 +8208,7 @@ BEGIN IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The value for the parameter @Execute is not supported.', 16, 1 + VALUES('The value for the parameter @Execute is not supported.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8090,7 +8216,7 @@ BEGIN IF EXISTS(SELECT * FROM @Errors) BEGIN 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 + VALUES('The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8106,7 +8232,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -8118,7 +8244,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following databases in the @Indexes parameter do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases in the @Indexes parameter do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') @@ -8130,7 +8256,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - SELECT 'The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -8143,7 +8269,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN 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: ' + @ErrorMessage + '.', 10, 1 + VALUES('The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) END ---------------------------------------------------------------------------------------------------- @@ -8253,7 +8379,7 @@ BEGIN FROM dbo.[Queue] WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName - AND [Parameters] = @Parameters + AND [Parameters] = @ParametersString IF @QueueID IS NULL BEGIN @@ -8263,12 +8389,12 @@ BEGIN FROM dbo.[Queue] WITH (UPDLOCK, HOLDLOCK) WHERE SchemaName = @SchemaName AND ObjectName = @ObjectName - AND [Parameters] = @Parameters + AND [Parameters] = @ParametersString IF @QueueID IS NULL BEGIN INSERT INTO dbo.[Queue] (SchemaName, ObjectName, [Parameters]) - SELECT @SchemaName, @ObjectName, @Parameters + VALUES(@SchemaName, @ObjectName, @ParametersString) SET @QueueID = SCOPE_IDENTITY() END @@ -9225,79 +9351,79 @@ BEGIN 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' + VALUES('SORT_IN_TEMPDB = ON') END 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' + VALUES('SORT_IN_TEMPDB = OFF') END IF @CurrentAction = 'INDEX_REBUILD_ONLINE' 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(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END + VALUES('ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END) END IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 1 AND @WaitAtLowPriorityMaxDuration IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + ')' + VALUES('WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + ')') END IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'ONLINE = OFF' + VALUES('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(max)) + VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) 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) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max)) + VALUES('FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max))) END IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END + VALUES('PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END) END IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,4) AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'DATA_COMPRESSION = ' + @DataCompression + VALUES('DATA_COMPRESSION = ' + @DataCompression) END IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL) THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END + VALUES(CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL) THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END) END IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL)) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max)) + VALUES('MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max))) END IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'LOB_COMPACTION = ON' + VALUES('LOB_COMPACTION = ON') END IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'N' BEGIN INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - SELECT 'LOB_COMPACTION = OFF' + VALUES('LOB_COMPACTION = OFF') END IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) @@ -9510,43 +9636,43 @@ BEGIN IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max)) + VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) END IF @CurrentStatisticsSample = 100 BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'FULLSCAN' + VALUES('FULLSCAN') END IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT' + VALUES('SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT') END IF @CurrentStatisticsPersistSample = 'Y' BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'PERSIST_SAMPLE_PERCENT = ON' + VALUES('PERSIST_SAMPLE_PERCENT = ON') END IF @CurrentStatisticsPersistSample = 'N' BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'PERSIST_SAMPLE_PERCENT = OFF' + VALUES('PERSIST_SAMPLE_PERCENT = OFF') END IF @CurrentNoRecompute = 1 BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'NORECOMPUTE' + VALUES('NORECOMPUTE') END IF @CurrentStatisticsResample = 'Y' BEGIN INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - SELECT 'RESAMPLE' + VALUES('RESAMPLE') END IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) From dc0b1a639ee2bad4c7c57abe812ad8a84bdd9e7f Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 17:31:03 +0200 Subject: [PATCH 079/177] Add files via upload --- .github/workflows/deploy-website.yml | 121 +++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 .github/workflows/deploy-website.yml diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml new file mode 100644 index 00000000..7191c430 --- /dev/null +++ b/.github/workflows/deploy-website.yml @@ -0,0 +1,121 @@ +name: Deploy to website + +# Uploads the released .sql files to the website over FTPS whenever a +# release is merged to main. Runs on the same trigger as the tag workflow; +# the two run independently and in parallel. +# +# BEFORE FIRST USE: +# 1. Change REMOTE_DIR below to the scripts directory on your server. +# 2. Add three repository secrets under +# Settings -> Secrets and variables -> Actions -> New repository secret: +# FTP_SERVER 185.116.236.159 (host only - no ftp:// prefix) +# FTP_USERNAME the same user name as in your FTP client +# FTP_PASSWORD the same password as in your FTP client +# (Note: a password containing a comma would need extra handling - +# tell me if yours has one.) +# +# ALERTING: nothing to configure. If the run fails after all retries, +# GitHub emails you automatically (default is email on failure only - +# successful deploys are silent). Recovery: open the failed run in the +# Actions tab and click "Re-run failed jobs". + +on: + push: + branches: + - main + paths: + - MaintenanceSolution.sql # a release always updates this file + workflow_dispatch: # adds a manual "Run workflow" button, handy for testing + +env: + REMOTE_DIR: "/public_html/scripts" # scripts folder on the server + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - name: Check out the repository + uses: actions/checkout@v4 + + - name: Install lftp (FTPS client) + run: sudo apt-get update -qq && sudo apt-get install -y -qq lftp + + - name: Upload files over FTPS + env: + FTP_SERVER: ${{ secrets.FTP_SERVER }} + FTP_USERNAME: ${{ secrets.FTP_USERNAME }} + FTP_PASSWORD: ${{ secrets.FTP_PASSWORD }} + run: | + set -u + + # Upload order: components first, MaintenanceSolution.sql last, + # so the most-downloaded file only changes once everything else + # is already current. + FILES="CommandLog.sql Queue.sql QueueDatabase.sql CommandExecute.sql DatabaseBackup.sql DatabaseIntegrityCheck.sql IndexOptimize.sql MaintenanceSolution.sql" + + # Explicit FTPS (AUTH TLS) on port 21 - the same protocol settings + # as in your FTP client. verify-certificate is off because the + # server is addressed by IP (185.116.236.159): certificates are + # issued for host names, so the name check cannot succeed against + # an IP. The connection itself is still fully encrypted. + SETTINGS="set ftp:ssl-force true; set ftp:ssl-protect-data true; set ssl:verify-certificate false; set net:max-retries 2; set net:timeout 60" + + run_lftp () { + lftp -p 21 -u "$FTP_USERNAME,$FTP_PASSWORD" -e "$SETTINGS; $1; bye" "$FTP_SERVER" + } + + # Two-phase upload. Phase 1 uploads ALL files under temporary + # names - the slow, interruptible part - while the live site + # stays completely untouched; a failure anywhere in this phase + # leaves the previous release fully intact, not mixed. Phase 2 + # renames the temp files into place, in order, big file last. + # Renames are atomic metadata operations taking milliseconds, + # so the site flips from old release to new near-instantly and + # no live file name ever points at a half-written file. + UPLOAD="" + for f in $FILES; do + UPLOAD="$UPLOAD put $f -o $REMOTE_DIR/$f.tmp;" + done + for f in $FILES; do + UPLOAD="$UPLOAD mv $REMOTE_DIR/$f.tmp $REMOTE_DIR/$f;" + done + + # Verification: list the files on the server and compare each + # size, byte for byte, against the file in the repository. Any + # missing or short file fails the run - a completed-but-corrupted + # transfer cannot pass silently. + verify () { + LISTING=$(run_lftp "cls -s --block-size=1 $REMOTE_DIR/*.sql") || return 1 + for f in $FILES; do + LOCAL=$(stat -c %s "$f") + REMOTE=$(printf '%s\n' "$LISTING" | grep "/$f\$" | awk '{print $1}') + if [ "$LOCAL" != "$REMOTE" ]; then + echo "VERIFY FAILED: $f is $LOCAL bytes in the repo but ${REMOTE:-missing} on the server" + return 1 + fi + echo "Verified $f ($LOCAL bytes)" + done + return 0 + } + + # Try the whole upload-and-verify up to 3 times, a few minutes + # apart. Transient problems (dropped connection, brief outage) + # are absorbed here without you being involved. Because every + # attempt re-uploads the complete set, a failure midway through + # one attempt is healed by the next. Only if all attempts fail + # does the run fail - and GitHub then sends the failure email. + for attempt in 1 2 3; do + echo "=== Upload attempt $attempt of 3 ===" + if run_lftp "$UPLOAD" && verify; then + echo "Deploy succeeded and verified." + exit 0 + fi + if [ "$attempt" -lt 3 ]; then + echo "Attempt $attempt failed - waiting 3 minutes before retrying." + sleep 180 + fi + done + + echo "All attempts failed. The website may be behind or partially updated;" + echo "re-run this workflow when the host is reachable to make it consistent." + exit 1 From c55788fba390ee0dbe98eb34ed51a4256da28815 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 17:40:33 +0200 Subject: [PATCH 080/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 54 +++++++++++++++++++------------------- 5 files changed, 31 insertions(+), 31 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index eb289b47..941978b2 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-19 16:57:12 //-- + --// Version: 2026-07-19 17:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index ae38296f..1870a91a 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 16:57:12 //-- + --// Version: 2026-07-19 17:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index f8a13013..d263eea7 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 16:57:12 //-- + --// Version: 2026-07-19 17:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 36516a4b..36f24280 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 16:57:12 //-- + --// Version: 2026-07-19 17:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 37da46ee..690d1b48 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: 2026-07-19 16:57:12 +Version: 2026-07-19 17:38:27 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 16:57:12 //-- + --// Version: 2026-07-19 17:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 16:57:12 //-- + --// Version: 2026-07-19 17:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4964,7 +4964,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 16:57:12 //-- + --// Version: 2026-07-19 17:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6975,7 +6975,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 16:57:12 //-- + --// Version: 2026-07-19 17:38:27 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -9985,73 +9985,73 @@ BEGIN END INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01, OutputFileNamePart02) - SELECT 'DatabaseBackup - SYSTEM_DATABASES - FULL', + VALUES('DatabaseBackup - SYSTEM_DATABASES - FULL', 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''SYSTEM_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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' + 'FULL') INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01, OutputFileNamePart02) - SELECT 'DatabaseBackup - USER_DATABASES - DIFF', + VALUES('DatabaseBackup - USER_DATABASES - DIFF', 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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' + 'DIFF') INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01, OutputFileNamePart02) - SELECT 'DatabaseBackup - USER_DATABASES - FULL', + VALUES('DatabaseBackup - USER_DATABASES - FULL', 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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' + 'FULL') INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01, OutputFileNamePart02) - SELECT 'DatabaseBackup - USER_DATABASES - LOG', + VALUES('DatabaseBackup - USER_DATABASES - LOG', 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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' + 'LOG') INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) - SELECT 'DatabaseIntegrityCheck - SYSTEM_DATABASES', + VALUES('DatabaseIntegrityCheck - SYSTEM_DATABASES', 'EXECUTE [dbo].[DatabaseIntegrityCheck]' + CHAR(13) + CHAR(10) + '@Databases = ''SYSTEM_DATABASES'',' + CHAR(13) + CHAR(10) + '@NoInformationalMessages = ''Y'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', @DatabaseName, - 'DatabaseIntegrityCheck' + 'DatabaseIntegrityCheck') INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) - SELECT 'DatabaseIntegrityCheck - USER_DATABASES', + VALUES('DatabaseIntegrityCheck - USER_DATABASES', 'EXECUTE [dbo].[DatabaseIntegrityCheck]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + '@NoInformationalMessages = ''Y'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', @DatabaseName, - 'DatabaseIntegrityCheck' + 'DatabaseIntegrityCheck') INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) - SELECT 'IndexOptimize - USER_DATABASES', + VALUES('IndexOptimize - USER_DATABASES', 'EXECUTE [dbo].[IndexOptimize]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', @DatabaseName, - 'IndexOptimize' + 'IndexOptimize') INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) - SELECT 'sp_delete_backuphistory', + VALUES('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' + 'sp_delete_backuphistory') INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) - SELECT 'sp_purge_jobhistory', + VALUES('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' + 'sp_purge_jobhistory') INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) - SELECT 'CommandLog Cleanup', + VALUES('CommandLog Cleanup', 'DELETE FROM [dbo].[CommandLog]' + CHAR(13) + CHAR(10) + 'WHERE StartTime < DATEADD(dd,-30,GETDATE())', @DatabaseName, - 'CommandLogCleanup' + 'CommandLogCleanup') INSERT INTO @Jobs ([Name], CommandCmdExec, OutputFileNamePart01) - SELECT 'Output File Cleanup', + VALUES('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' + 'OutputFileCleanup') IF @AmazonRDS = 1 BEGIN From f031bca312a088264e3c8f75e6f4553dd2704285 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 17:54:11 +0200 Subject: [PATCH 081/177] Update create-tag.yml --- .github/workflows/create-tag.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/create-tag.yml b/.github/workflows/create-tag.yml index cd4b3576..915f6d02 100644 --- a/.github/workflows/create-tag.yml +++ b/.github/workflows/create-tag.yml @@ -21,7 +21,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out the repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 with: fetch-depth: 0 # full history so existing tags are visible From 6a04040e625982e7cb187bea884bff612478078e Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 17:54:25 +0200 Subject: [PATCH 082/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index 7191c430..1ff146ce 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -35,7 +35,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out the repository - uses: actions/checkout@v4 + uses: actions/checkout@v5 - name: Install lftp (FTPS client) run: sudo apt-get update -qq && sudo apt-get install -y -qq lftp From ccca0aa80ca1d8689bcdb3259a518c8253986065 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 17:55:30 +0200 Subject: [PATCH 083/177] Update create-tag.yml --- .github/workflows/create-tag.yml | 3 --- 1 file changed, 3 deletions(-) diff --git a/.github/workflows/create-tag.yml b/.github/workflows/create-tag.yml index 915f6d02..384581d5 100644 --- a/.github/workflows/create-tag.yml +++ b/.github/workflows/create-tag.yml @@ -2,9 +2,6 @@ name: Create tag from version header # Runs every time you push/merge a commit to main. It reads the version # timestamp out of the script header and creates a matching, immutable Git tag. -# Because your header timestamp includes the time down to the second, every -# release gets a unique tag - even several releases on the same day - and a -# quiet stretch with no commits simply produces no tags. on: push: From 25b15b4218ffe6e396742b1f9dfbb0b65261b71d Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 17:56:13 +0200 Subject: [PATCH 084/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index 1ff146ce..f5b2cfa5 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -1,23 +1,6 @@ name: Deploy to website -# Uploads the released .sql files to the website over FTPS whenever a -# release is merged to main. Runs on the same trigger as the tag workflow; -# the two run independently and in parallel. -# -# BEFORE FIRST USE: -# 1. Change REMOTE_DIR below to the scripts directory on your server. -# 2. Add three repository secrets under -# Settings -> Secrets and variables -> Actions -> New repository secret: -# FTP_SERVER 185.116.236.159 (host only - no ftp:// prefix) -# FTP_USERNAME the same user name as in your FTP client -# FTP_PASSWORD the same password as in your FTP client -# (Note: a password containing a comma would need extra handling - -# tell me if yours has one.) -# -# ALERTING: nothing to configure. If the run fails after all retries, -# GitHub emails you automatically (default is email on failure only - -# successful deploys are silent). Recovery: open the failed run in the -# Actions tab and click "Re-run failed jobs". +# Uploads the released .sql files to the website over FTPS whenever a release is merged to main. on: push: From 57aeda089f380b0e1124bc0fffd19ea32cecb363 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 17:56:28 +0200 Subject: [PATCH 085/177] Update create-tag.yml --- .github/workflows/create-tag.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/create-tag.yml b/.github/workflows/create-tag.yml index 384581d5..d5ac89d9 100644 --- a/.github/workflows/create-tag.yml +++ b/.github/workflows/create-tag.yml @@ -1,7 +1,6 @@ name: Create tag from version header -# Runs every time you push/merge a commit to main. It reads the version -# timestamp out of the script header and creates a matching, immutable Git tag. +# Runs every time you push/merge a commit to main. It reads the version timestamp out of the script header and creates a matching, immutable Git tag. on: push: From bab78d9e09e84c66b7ab71ad370c5e6c073e637c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 17:57:55 +0200 Subject: [PATCH 086/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index f5b2cfa5..faa1eda0 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -31,16 +31,10 @@ jobs: run: | set -u - # Upload order: components first, MaintenanceSolution.sql last, - # so the most-downloaded file only changes once everything else - # is already current. + # Upload order: components first, MaintenanceSolution.sql last, so the most-downloaded file only changes once everything else is already current. FILES="CommandLog.sql Queue.sql QueueDatabase.sql CommandExecute.sql DatabaseBackup.sql DatabaseIntegrityCheck.sql IndexOptimize.sql MaintenanceSolution.sql" - # Explicit FTPS (AUTH TLS) on port 21 - the same protocol settings - # as in your FTP client. verify-certificate is off because the - # server is addressed by IP (185.116.236.159): certificates are - # issued for host names, so the name check cannot succeed against - # an IP. The connection itself is still fully encrypted. + # Explicit FTPS (AUTH TLS) on port 21 SETTINGS="set ftp:ssl-force true; set ftp:ssl-protect-data true; set ssl:verify-certificate false; set net:max-retries 2; set net:timeout 60" run_lftp () { From c1e0597c0a2725112dc34beea11b4bfb26baaacb Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 18:02:00 +0200 Subject: [PATCH 087/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 25 ++++++------------------- 1 file changed, 6 insertions(+), 19 deletions(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index faa1eda0..3c85746f 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -41,14 +41,9 @@ jobs: lftp -p 21 -u "$FTP_USERNAME,$FTP_PASSWORD" -e "$SETTINGS; $1; bye" "$FTP_SERVER" } - # Two-phase upload. Phase 1 uploads ALL files under temporary - # names - the slow, interruptible part - while the live site - # stays completely untouched; a failure anywhere in this phase - # leaves the previous release fully intact, not mixed. Phase 2 - # renames the temp files into place, in order, big file last. - # Renames are atomic metadata operations taking milliseconds, - # so the site flips from old release to new near-instantly and - # no live file name ever points at a half-written file. + # Two-phase upload. + # Phase 1 uploads ALL files under temporary names - the slow, interruptible part - while the live site stays completely untouched; a failure anywhere in this phase + # Phase 2 renames the temp files into place, in order, big file last. UPLOAD="" for f in $FILES; do UPLOAD="$UPLOAD put $f -o $REMOTE_DIR/$f.tmp;" @@ -57,10 +52,7 @@ jobs: UPLOAD="$UPLOAD mv $REMOTE_DIR/$f.tmp $REMOTE_DIR/$f;" done - # Verification: list the files on the server and compare each - # size, byte for byte, against the file in the repository. Any - # missing or short file fails the run - a completed-but-corrupted - # transfer cannot pass silently. + # Verification: list the files on the server and compare each size, byte for byte, against the file in the repository. verify () { LISTING=$(run_lftp "cls -s --block-size=1 $REMOTE_DIR/*.sql") || return 1 for f in $FILES; do @@ -75,12 +67,7 @@ jobs: return 0 } - # Try the whole upload-and-verify up to 3 times, a few minutes - # apart. Transient problems (dropped connection, brief outage) - # are absorbed here without you being involved. Because every - # attempt re-uploads the complete set, a failure midway through - # one attempt is healed by the next. Only if all attempts fail - # does the run fail - and GitHub then sends the failure email. + # Try the whole upload-and-verify up to 3 times for attempt in 1 2 3; do echo "=== Upload attempt $attempt of 3 ===" if run_lftp "$UPLOAD" && verify; then @@ -89,7 +76,7 @@ jobs: fi if [ "$attempt" -lt 3 ]; then echo "Attempt $attempt failed - waiting 3 minutes before retrying." - sleep 180 + sleep 120 fi done From c32cdebc0bb7db96844951c00e016f3ee9ab4cda Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 18:03:48 +0200 Subject: [PATCH 088/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index 3c85746f..c7b8ab63 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -80,6 +80,5 @@ jobs: fi done - echo "All attempts failed. The website may be behind or partially updated;" - echo "re-run this workflow when the host is reachable to make it consistent." + echo "All attempts failed. The website may be behind or partially updated; re-run this workflow when the host is reachable to make it consistent." exit 1 From 02ac3e2c31c4481700207cfd06069f26411f5bf8 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 18:07:44 +0200 Subject: [PATCH 089/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index c7b8ab63..bf452fef 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -75,7 +75,7 @@ jobs: exit 0 fi if [ "$attempt" -lt 3 ]; then - echo "Attempt $attempt failed - waiting 3 minutes before retrying." + echo "Attempt $attempt failed - waiting 120 seconds before retrying." sleep 120 fi done From d55803515da4055136935674b6472642b9b19057 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 18:08:33 +0200 Subject: [PATCH 090/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index bf452fef..a3a3826b 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -42,7 +42,7 @@ jobs: } # Two-phase upload. - # Phase 1 uploads ALL files under temporary names - the slow, interruptible part - while the live site stays completely untouched; a failure anywhere in this phase + # Phase 1 uploads ALL files under temporary names - the slow, interruptible part - while the live site stays completely untouched. # Phase 2 renames the temp files into place, in order, big file last. UPLOAD="" for f in $FILES; do From e17980553bd4d2160082d13de3298462f518b994 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 18:12:56 +0200 Subject: [PATCH 091/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index a3a3826b..14941978 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -31,7 +31,7 @@ jobs: run: | set -u - # Upload order: components first, MaintenanceSolution.sql last, so the most-downloaded file only changes once everything else is already current. + # Upload order: components first, MaintenanceSolution.sql last. FILES="CommandLog.sql Queue.sql QueueDatabase.sql CommandExecute.sql DatabaseBackup.sql DatabaseIntegrityCheck.sql IndexOptimize.sql MaintenanceSolution.sql" # Explicit FTPS (AUTH TLS) on port 21 @@ -43,7 +43,7 @@ jobs: # Two-phase upload. # Phase 1 uploads ALL files under temporary names - the slow, interruptible part - while the live site stays completely untouched. - # Phase 2 renames the temp files into place, in order, big file last. + # Phase 2 renames the temp files into place, in order. UPLOAD="" for f in $FILES; do UPLOAD="$UPLOAD put $f -o $REMOTE_DIR/$f.tmp;" From fbf7756b80f9bbf37bd361374b88f5d15e778537 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 18:24:20 +0200 Subject: [PATCH 092/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 3 +-- MaintenanceSolution.sql | 11 +++++------ 5 files changed, 9 insertions(+), 11 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 941978b2..0b3e7d61 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-19 17:38:27 //-- + --// Version: 2026-07-19 18:23:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 1870a91a..38f170ea 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 17:38:27 //-- + --// Version: 2026-07-19 18:23:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index d263eea7..d2f53e3b 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 17:38:27 //-- + --// Version: 2026-07-19 18:23:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 36f24280..ca283c8b 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 17:38:27 //-- + --// Version: 2026-07-19 18:23:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1763,7 +1763,6 @@ BEGIN BEGIN SET @CurrentCommand += ' AND EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes WHERE @ParamDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND schemas.[name] LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND objects.[name] LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND SelectedIndexes.Selected = 1)' END - IF @Indexes IS NOT NULL AND EXISTS(SELECT * FROM @SelectedIndexes WHERE Selected = 0 AND IndexName = '%') BEGIN SET @CurrentCommand += ' AND NOT EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes WHERE @ParamDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND schemas.[name] LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND objects.[name] LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND SelectedIndexes.IndexName = ''%'' AND SelectedIndexes.Selected = 0)' diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 690d1b48..95633293 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: 2026-07-19 17:38:27 +Version: 2026-07-19 18:23:28 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 17:38:27 //-- + --// Version: 2026-07-19 18:23:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 17:38:27 //-- + --// Version: 2026-07-19 18:23:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4964,7 +4964,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 17:38:27 //-- + --// Version: 2026-07-19 18:23:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6975,7 +6975,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 17:38:27 //-- + --// Version: 2026-07-19 18:23:28 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8682,7 +8682,6 @@ BEGIN BEGIN SET @CurrentCommand += ' AND EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes WHERE @ParamDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND schemas.[name] LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND objects.[name] LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND SelectedIndexes.Selected = 1)' END - IF @Indexes IS NOT NULL AND EXISTS(SELECT * FROM @SelectedIndexes WHERE Selected = 0 AND IndexName = '%') BEGIN SET @CurrentCommand += ' AND NOT EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes WHERE @ParamDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND schemas.[name] LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND objects.[name] LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND SelectedIndexes.IndexName = ''%'' AND SelectedIndexes.Selected = 0)' From 0b29c0d05b31c69717f38c4c08b6a01f1a361719 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 18:51:58 +0200 Subject: [PATCH 093/177] Update .gitattributes --- .gitattributes | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitattributes b/.gitattributes index 5bdace7f..5eddf26f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,3 @@ *.sql linguist-language=TSQL +.github export-ignore +.gitattributes export-ignore From 10e93e3499af66866498947564e3071cec72bd04 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 20:19:36 +0200 Subject: [PATCH 094/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index 14941978..1f9e9864 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -35,7 +35,7 @@ jobs: FILES="CommandLog.sql Queue.sql QueueDatabase.sql CommandExecute.sql DatabaseBackup.sql DatabaseIntegrityCheck.sql IndexOptimize.sql MaintenanceSolution.sql" # Explicit FTPS (AUTH TLS) on port 21 - SETTINGS="set ftp:ssl-force true; set ftp:ssl-protect-data true; set ssl:verify-certificate false; set net:max-retries 2; set net:timeout 60" + SETTINGS="set ftp:ssl-force true; set ftp:ssl-protect-data true; set ssl:verify-certificate true; set net:max-retries 2; set net:timeout 60" run_lftp () { lftp -p 21 -u "$FTP_USERNAME,$FTP_PASSWORD" -e "$SETTINGS; $1; bye" "$FTP_SERVER" From beb4d6f9e89bdec8b135edb7f032c16eda065d6e Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 20:25:08 +0200 Subject: [PATCH 095/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index 1f9e9864..14941978 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -35,7 +35,7 @@ jobs: FILES="CommandLog.sql Queue.sql QueueDatabase.sql CommandExecute.sql DatabaseBackup.sql DatabaseIntegrityCheck.sql IndexOptimize.sql MaintenanceSolution.sql" # Explicit FTPS (AUTH TLS) on port 21 - SETTINGS="set ftp:ssl-force true; set ftp:ssl-protect-data true; set ssl:verify-certificate true; set net:max-retries 2; set net:timeout 60" + SETTINGS="set ftp:ssl-force true; set ftp:ssl-protect-data true; set ssl:verify-certificate false; set net:max-retries 2; set net:timeout 60" run_lftp () { lftp -p 21 -u "$FTP_USERNAME,$FTP_PASSWORD" -e "$SETTINGS; $1; bye" "$FTP_SERVER" From 856e567e1fa9b605b7d7943f32c604075c67fed4 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 20:56:56 +0200 Subject: [PATCH 096/177] Create sql-server-backup.md --- docs/sql-server-backup.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 docs/sql-server-backup.md diff --git a/docs/sql-server-backup.md b/docs/sql-server-backup.md new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/docs/sql-server-backup.md @@ -0,0 +1 @@ + From c553566b801feb5a057493a842ebe20445c37a00 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 20:57:15 +0200 Subject: [PATCH 097/177] Add files via upload --- docs/sql-server-backup.md | 963 ++++++++++++++++++ ...server-index-and-statistics-maintenance.md | 522 ++++++++++ docs/sql-server-integrity-check.md | 352 +++++++ 3 files changed, 1837 insertions(+) create mode 100644 docs/sql-server-index-and-statistics-maintenance.md create mode 100644 docs/sql-server-integrity-check.md diff --git a/docs/sql-server-backup.md b/docs/sql-server-backup.md index 8b137891..f2437aa7 100644 --- a/docs/sql-server-backup.md +++ b/docs/sql-server-backup.md @@ -1 +1,964 @@ + +# SQL Server Backup + +This documentation is generated from [ola.hallengren.com/sql-server-backup.html](https://ola.hallengren.com/sql-server-backup.html), which is the primary source. + +DatabaseBackup is the SQL Server Maintenance Solution’s stored procedure for backing up databases. DatabaseBackup is supported on SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, and Azure SQL Managed Instance. + +## Download + +Download [MaintenanceSolution.sql](/MaintenanceSolution.sql). This script creates all the objects and jobs that you need. You can also [download](https://ola.hallengren.com/downloads.html) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). + +## License + +The SQL Server Maintenance Solution is [free](/LICENSE). + +## Parameters + +### Databases + +Select databases. The keywords SYSTEM_DATABASES, USER_DATABASES, ALL_DATABASES, and AVAILABILITY_GROUP_DATABASES are supported. The hyphen character (-) is used to exclude databases, and the percent character (%) is used for wildcard selection. All of these operations can be combined by using the comma (,). + +| Value | Description | +| --- | --- | +| SYSTEM_DATABASES | All system databases (master, msdb, and model) | +| USER_DATABASES | All user databases | +| ALL_DATABASES | All databases | +| AVAILABILITY_GROUP_DATABASES | All databases in availability groups | +| USER_DATABASES, -AVAILABILITY_GROUP_DATABASES | All user databases that are not in availability groups | +| Db1 | The database Db1 | +| Db1, Db2 | The databases Db1 and Db2 | +| USER_DATABASES, -Db1 | All user databases except Db1 | +| %Db% | All databases that have “Db” in the name | +| %Db%, -Db1 | All databases that have “Db” in the name except Db1 | +| ALL_DATABASES, -%Db% | All databases that do not have “Db” in the name | + +### Directory + +Specify backup root directories, which can be local directories or network shares. If you specify multiple directories, then the backup files are striped evenly across the directories. Specify multiple directories by using the comma (,). If no directory is specified, then the SQL Server default backup directory is used. + +| Value | Description | +| --- | --- | +| NULL | Back up to the SQL Server default backup directory. This is the default. | +| C:\Backup | Back up to the directory C:\Backup. | +| C:\Backup, D:\Backup | Back up to the directories C:\Backup and D:\Backup. | +| \\Server1\Backup | Back up to the network share \\Server1\Backup. | +| \\Server1\Backup, \\Server2\Backup | Back up to the network shares \\Server1\Backup and \\Server2\Backup. | +| NUL | Back up to NUL. | + +DatabaseBackup creates a directory structure with server name, instance name, database name, and backup type under the backup root directory. If the database is part of an availability group, then cluster name and availability group name are used instead of server name and instance name. + +### BackupType + +Specify the type of backup: full, differential, or transaction log. + +| Value | Description | +| --- | --- | +| FULL | Full backup | +| DIFF | Differential backup | +| LOG | Transaction log backup | + +DatabaseBackup uses the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command: BACKUP DATABASE for the full backup, BACKUP DATABASE WITH DIFFERENTIAL for the differential backup, and BACKUP LOG for the transaction log backup. + +### Verify + +Verify the backup. + +| Value | Description | +| --- | --- | +| Y | Verify the backup. | +| N | Do not verify the backup. This is the default. | + +The Verify option in DatabaseBackup uses the SQL Server [RESTORE VERIFYONLY](https://learn.microsoft.com/en-us/sql/t-sql/statements/restore-statements-verifyonly-transact-sql) command. + +### CleanupTime + +Specify the time, in hours, after which the backup files are deleted. If no time is specified, then no backup files are deleted. + +DatabaseBackup has a check to verify that transaction log backups that are newer than the most recent full or differential backup are not deleted. + +### CleanupMode + +Specify whether old backup files should be deleted before or after the backup has been performed. + +| Value | Description | +| --- | --- | +| BEFORE_BACKUP | Delete old backup files before the backup has been performed. | +| AFTER_BACKUP | Delete old backup files after the backup and verification have been performed. If the backup or verify fails, then no backup files are deleted. This is the default. | + +### Compress + +Compress the backup. If no value is specified, then the backup compression default in sys.configurations is used. + +| Value | Description | +| --- | --- | +| NULL | Use the backup compression default in sys.configurations. This is the default. | +| Y | Compress the backup. | +| N | Do not compress the backup. | + +The Compress option in DatabaseBackup uses the COMPRESSION and NO_COMPRESSION options in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### CompressionAlgorithm + +Specify the backup compression algorithm. + +| Value | Description | +| --- | --- | +| NULL | Use the backup compression algorithm in sys.configurations. This is the default. | +| MS_XPRESS | SQL Server backup compression | +| QAT_DEFLATE | Intel QuickAssist Technology (QAT) backup compression | +| ZSTD | Zstandard backup compression | + +The CompressionAlgorithm option in DatabaseBackup uses the COMPRESSION ... ALGORITHM option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### CompressionLevel + +Specify the backup compression level. + +| Value | Description | +| --- | --- | +| LOW | Low | +| MEDIUM | Medium | +| HIGH | High | + +The CompressionLevel option in DatabaseBackup uses the COMPRESSION ... LEVEL option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### CopyOnly + +Perform a copy-only backup. + +| Value | Description | +| --- | --- | +| Y | Perform a copy-only backup. | +| N | Perform a normal backup. This is the default. | + +The CopyOnly option in DatabaseBackup uses the COPY_ONLY option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### ChangeBackupType + +Change the backup type if a differential or transaction-log backup cannot be performed. + +| Value | Description | +| --- | --- | +| Y | Change the backup type if a backup cannot be performed. | +| N | Skip the backup if a backup cannot be performed. This is the default. | + +DatabaseBackup checks differential_base_lsn in [sys.master_files](https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-master-files-transact-sql) to determine whether a differential backup can be performed. If a differential backup is not possible, then the database is skipped by default. Alternatively, you can set ChangeBackupType to Y to have a full backup performed instead. + +DatabaseBackup checks last_log_backup_lsn in [sys.database_recovery_status](https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-database-recovery-status-transact-sql) to determine whether a transaction log backup in full or bulk-logged recovery model can be performed. If a transaction log backup is not possible, then the database is skipped by default. Alternatively, you can set ChangeBackupType to Y to have a differential or full backup performed instead. + +### BackupSoftware + +Specify third-party backup software; otherwise, SQL Server native backup is performed. + +| Value | Description | +| --- | --- | +| NULL | SQL Server native backup (the default) | +| DATA_DOMAIN_BOOST | [Dell EMC Data Domain Boost](https://www.dell.com/en-us/shop/storage-servers-and-networking-for-business/sf/powerprotect-data-domain) | +| LITESPEED | [Quest LiteSpeed for SQL Server](https://www.quest.com/products/litespeed-for-sql-server) | +| SQLBACKUP | [Red Gate SQL Backup Pro](https://www.red-gate.com/products/sql-backup/) | +| SQLSAFE | [Idera SQL Safe Backup](https://www.idera.com/products/sql-safe-backup/) | + +### Checksum + +Enable backup checksums. + +| Value | Description | +| --- | --- | +| NULL | Use the checksum default in sys.configurations. This is the default. | +| Y | Enable backup checksums. | +| N | Do not enable backup checksums. | + +The Checksum option in DatabaseBackup uses the CHECKSUM option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### BlockSize + +Specify the physical blocksize in bytes. + +The BlockSize option in DatabaseBackup uses the BLOCKSIZE option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### BufferCount + +Specify the number of I/O buffers to be used for the backup operation. + +The BufferCount option in DatabaseBackup uses the BUFFERCOUNT option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### MaxTransferSize + +Specify the largest unit of transfer, in bytes, to be used between SQL Server and the backup media. + +The MaxTransferSize option in DatabaseBackup uses the MAXTRANSFERSIZE option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### NumberOfFiles + +Specify the number of backup files. The default is the number of backup directories and the maximum is 64 files. + +### MinBackupSizeForMultipleFiles + +Specify a minimum backup size in MB for when DatabaseBackup should back up to multiple files. + +### MaxFileSize + +Specify a maximum backup file size in MB. DatabaseBackup will dynamically calculate the number of backup files. + +### CompressionLevelNumeric + +Set the LiteSpeed, Red Gate SQL Backup Pro, or Idera SQL Safe Backup compression level. + +In LiteSpeed, the compression levels 0 to 8 are supported. In Red Gate SQL Backup Pro, levels 0 to 4 are supported, and in Idera SQL Safe Backup, levels 1 to 4 are supported. + +### Description + +Enter a description for the backup. + +The Description option in DatabaseBackup uses the DESCRIPTION option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### BackupSetName + +Enter a name for the backup set. + +The BackupSetName option in DatabaseBackup uses the NAME option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### Threads + +Specify the LiteSpeed, Red Gate SQL Backup Pro, or Idera SQL Safe Backup number of threads. The maximum number of threads is 32. + +### Throttle + +Specify the LiteSpeed maximum CPU usage, as a percentage. + +### Encrypt + +Encrypt the backup. + +| Value | Description | +| --- | --- | +| Y | Encrypt the backup. | +| N | Do not encrypt the backup. This is the default. | + +The Encrypt option in DatabaseBackup uses the ENCRYPTION option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### EncryptionAlgorithm + +Specify the type of encryption. + +| Value | Description | +| --- | --- | +| NULL | No encryption (the default) | +| RC2_40 | RC2 40-bit encryption (LiteSpeed) | +| RC2_56 | RC2 56-bit encryption (LiteSpeed) | +| RC2_112 | RC2 112-bit encryption (LiteSpeed) | +| RC2_128 | RC2 128-bit encryption (LiteSpeed) | +| TRIPLE_DES_3KEY | Triple DES encryption (SQL Server native encryption or LiteSpeed) | +| RC4_128 | RC4 128-bit encryption (LiteSpeed) | +| AES_128 | AES 128-bit encryption (SQL Server native encryption, LiteSpeed, Red Gate SQL Backup Pro, or Idera SQL Safe Backup) | +| AES_192 | AES 192-bit encryption (SQL Server native encryption or LiteSpeed) | +| AES_256 | AES 256-bit encryption (SQL Server native encryption, LiteSpeed, Red Gate SQL Backup Pro, or Idera SQL Safe Backup) | + +The EncryptionAlgorithm option in DatabaseBackup uses the ENCRYPTION and ALGORITHM options in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### ServerCertificate + +Server certificate that is used to encrypt the backup. + +The ServerCertificate option in DatabaseBackup uses the ENCRYPTION and SERVER CERTIFICATE options in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### ServerAsymmetricKey + +Asymmetric key that is used to encrypt the backup. + +The ServerAsymmetricKey option in DatabaseBackup uses the ENCRYPTION and SERVER ASYMMETRIC KEY options in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### EncryptionKey + +Key that is used to encrypt the backup. This is used with LiteSpeed, Red Gate SQL Backup Pro, and Idera SQL Safe Backup. + +### ReadWriteFileGroups + +Perform a backup of the primary filegroup and any read/write filegroups. + +| Value | Description | +| --- | --- | +| Y | Perform a backup of the primary filegroup and any read/write filegroups. | +| N | Perform a normal backup. This is the default. | + +The ReadWriteFileGroups option in DatabaseBackup uses the READ_WRITE_FILEGROUPS option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### OverrideBackupPreference + +Override the backup preference for availability groups. This option only applies to copy-only full backups and regular transaction log backups. + +| Value | Description | +| --- | --- | +| Y | Override the backup preference for availability groups. | +| N | Do not override the backup preference for availability groups. This is the default. | + +### NoRecovery + +Perform a backup of the tail of the log and leave the database in the RESTORING state. + +| Value | Description | +| --- | --- | +| Y | Perform a backup of the tail of the log. | +| N | Perform a normal backup. This is the default. | + +The NoRecovery option in DatabaseBackup uses the NORECOVERY option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### URL + +Specify the URL for backup to Azure Blob Storage. + +The URL option in DatabaseBackup uses the URL option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### Credential + +Specify a CREDENTIAL for backup to Azure Blob Storage. + +The Credential option in DatabaseBackup uses the CREDENTIAL option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### MirrorDirectory + +Specify one or more directories to perform a mirrored backup. + +The MirrorDirectory option in DatabaseBackup uses the MIRROR TO option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### MirrorCleanupTime + +Specify the time, in hours, after which the backup files are deleted in the mirror directories. If no time is specified, then no backup files are deleted. + +By default, backup files are deleted after each database is backed up and verified. Backup files are deleted only if the backup and verification of the database were successful. + +DatabaseBackup has a check to verify that transaction log backups that are newer than the most recent full or differential backup are not deleted. This is to guarantee that you can always perform a point-in-time restore. + +### MirrorCleanupMode + +Specify whether old backup files in the mirror directory should be deleted before or after the backup has been performed. + +| Value | Description | +| --- | --- | +| BEFORE_BACKUP | Delete old backup files before the backup has been performed. | +| AFTER_BACKUP | Delete old backup files after the backup has been performed. This is the default. | + +### MirrorURL + +Specify the URL for a mirrored backup to Azure Blob Storage. + +The MirrorURL option in DatabaseBackup uses the MIRROR TO URL option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### AvailabilityGroups + +Select availability groups. The keyword ALL_AVAILABILITY_GROUPS is supported. The hyphen character (-) is used to exclude availability groups, and the percent character (%) is used for wildcard selection. All of these operations can be combined by using the comma (,). + +| Value | Description | +| --- | --- | +| ALL_AVAILABILITY_GROUPS | All availability groups | +| AG1 | The availability group AG1 | +| AG1, AG2 | The availability groups AG1 and AG2 | +| ALL_AVAILABILITY_GROUPS, -AG1 | All availability groups except AG1 | +| %AG% | All availability groups that have “AG” in the name | +| %AG%, -AG1 | All availability groups that have “AG” in the name except AG1 | +| ALL_AVAILABILITY_GROUPS, -%AG% | All availability groups that do not have “AG” in the name | + +### Updateability + +Select READ_ONLY/READ_WRITE databases. + +| Value | Description | +| --- | --- | +| ALL | READ_ONLY and READ_WRITE databases. This is the default. | +| READ_ONLY | READ_ONLY databases | +| READ_WRITE | READ_WRITE databases | + +is_read_only in [sys.databases](https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-databases-transact-sql) is used to check if a database is READ_ONLY or READ_WRITE. + +### AdaptiveCompression + +Automatically select the optimal compression level based on CPU usage or disk I/O. This option is only available for LiteSpeed. + +| Value | Description | +| --- | --- | +| SIZE | Optimize the backup compression for size. | +| SPEED | Optimize the backup compression for speed. | + +### MinModificationLevel + +Specify a percentage for when a differential backup will be changed to a full backup. This option can only be used together with @ChangeBackupType = 'Y'. + +DatabaseBackup checks allocated_extent_page_count and modified_extent_page_count in [sys.dm_db_file_space_usage](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-file-space-usage-transact-sql) to calculate how much of a database has been modified. + +### MinDatabaseSizeForDifferentialBackup + +Specify the minimum database size for when a differential backup will be performed. If this parameter is used with @ChangeBackupType = 'Y', the backup type will be changed to a full backup for databases smaller than this size. + +DatabaseBackup checks allocated_extent_page_count in [sys.dm_db_file_space_usage](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-file-space-usage-transact-sql) to get the size of the database. + +### MinLogSizeSinceLastLogBackup + +Specify a minimum size (MB) for the amount of log that has been generated since the last log backup. This option can only be used together with @MinTimeSinceLastLogBackup. + +DatabaseBackup checks log_since_last_log_backup_mb in [sys.dm_db_log_stats](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-log-stats-transact-sql) to determine how much log has been generated since the last log backup. + +If the database is participating in an availability group as a secondary replica, the log will be backed up, regardless of this parameter. + +### MinTimeSinceLastLogBackup + +Specify a minimum time, in seconds, since the last log backup. This option can only be used together with @MinLogSizeSinceLastLogBackup. + +DatabaseBackup checks log_backup_time in [sys.dm_db_log_stats](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-log-stats-transact-sql) to determine when the transaction log was last backed up. + +If the database is participating in an availability group as a secondary replica, the log will be backed up, regardless of this parameter. + +### DataDomainBoostHost + +Specify the name of the Data Domain server. + +### DataDomainBoostUser + +Specify the name of the Data Domain user. + +### DataDomainBoostDevicePath + +Specify the name and the path of the Data Domain storage unit. + +### DataDomainBoostLockboxPath + +Specify the folder that contains the Data Domain lockbox file. + +### DataDomainBoostNoOutputTable + +Specify whether the output table from emc_run_backup is returned. + +| Value | Description | +| --- | --- | +| Y | The output table from emc_run_backup is not returned. | +| N | The output table from emc_run_backup is returned. This is the default. | + +### DirectoryStructure + +Specify the backup sub-directory structure for databases that are not in an availability group. + +You can use the following tokens: + +| Token | Description | +| --- | --- | +| ServerName | Server name | +| InstanceName | Instance name | +| ServiceName | Service name | +| DatabaseName | Database name | +| BackupType | Backup type | +| Partial | PARTIAL for partial backups | +| CopyOnly | COPY_ONLY for copy-only backups | +| Description | Backup description | +| BackupSetName | Backup set name | +| MajorVersion | Major version | +| MinorVersion | Minor version | +| DirectorySeparator | The directory separator | + +Default directory structure: {ServerName}${InstanceName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly} + +Tokens that do not apply will be removed. For example, the token {CopyOnly} (and the associated _) will be removed if it is not a copy-only backup. + +If the parameter is set to NULL, no sub-directories will be created. + +### AvailabilityGroupDirectoryStructure + +Specify the backup sub-directory structure for databases that are in an availability group. + +You can use the following tokens: + +| Token | Description | +| --- | --- | +| ServerName | Server name | +| InstanceName | Instance name | +| ServiceName | Service name | +| ClusterName | Cluster name | +| AvailabilityGroupName | Availability group name | +| DatabaseName | Database name | +| BackupType | Backup type | +| Partial | PARTIAL for partial backups | +| CopyOnly | COPY_ONLY for copy-only backups | +| Description | Backup description | +| BackupSetName | Backup set name | +| MajorVersion | Major version | +| MinorVersion | Minor version | +| DirectorySeparator | The directory separator | + +Default directory structure: {ClusterName}${AvailabilityGroupName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly} + +Tokens that do not apply will be removed. For example, the token {CopyOnly} (and the associated _) will be removed if it is not a copy-only backup. + +If the parameter is set to NULL, no sub-directories will be created. + +### DirectoryStructureCase + +Specify the case of the directory structure. + +| Value | Description | +| --- | --- | +| NULL | Original case | +| LOWER | Lower case | +| UPPER | Upper case | + +### FileName + +Specify the file name for databases that are not in an availability group. + +You can use the following tokens: + +| Token | Description | +| --- | --- | +| ServerName | Server name | +| InstanceName | Instance name | +| ServiceName | Service name | +| DatabaseName | Database name | +| BackupType | Backup type | +| Partial | PARTIAL for partial backups | +| CopyOnly | COPY_ONLY for copy-only backups | +| Description | Backup description | +| BackupSetName | Backup set name | +| Year | Year | +| Month | Month | +| Day | Day | +| Week | Week | +| Weekday | Weekday | +| Hour | Hour | +| Minute | Minute | +| Second | Second | +| Millisecond | Millisecond | +| Microsecond | Microsecond | +| FileNumber | The file number when you are backing up to multiple files | +| NumberOfFiles | The number of files when you are backing up to multiple files | +| FileExtension | The file extension | +| MajorVersion | Major version | +| MinorVersion | Minor version | + +Default file name: {ServerName}${InstanceName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension} + +Tokens that do not apply will be removed. For example, the token {CopyOnly} (and the associated _) will be removed if it is not a copy-only backup. + +### AvailabilityGroupFileName + +Specify the file name for databases that are in an availability group. + +You can use the following tokens: + +| Token | Description | +| --- | --- | +| ServerName | Server name | +| InstanceName | Instance name | +| ServiceName | Service name | +| ClusterName | Cluster name | +| AvailabilityGroupName | Availability group name | +| DatabaseName | Database name | +| BackupType | Backup type | +| Partial | PARTIAL for partial backups | +| CopyOnly | COPY_ONLY for copy-only backups | +| Description | Backup description | +| BackupSetName | Backup set name | +| Year | Year | +| Month | Month | +| Day | Day | +| Week | Week | +| Weekday | Weekday | +| Hour | Hour | +| Minute | Minute | +| Second | Second | +| Millisecond | Millisecond | +| Microsecond | Microsecond | +| FileNumber | The file number when you are backing up to multiple files | +| NumberOfFiles | The number of files when you are backing up to multiple files | +| FileExtension | The file extension | +| MajorVersion | Major version | +| MinorVersion | Minor version | + +Default file name: {ClusterName}${AvailabilityGroupName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension} + +Tokens that do not apply will be removed. For example, the token {CopyOnly} (and the associated _) will be removed if it is not a copy-only backup. + +### FileNameCase + +Specify the case of the file name. + +| Value | Description | +| --- | --- | +| NULL | Original case | +| LOWER | Lower case | +| UPPER | Upper case | + +### TokenTimezone + +Specify the time zone for the tokens in the directory structure and file name. + +| Value | Description | +| --- | --- | +| LOCAL | Local time zone | +| UTC | UTC time zone | + +### FileExtensionFull + +Specify the file extension for full backups. + +By default "bak" is used for SQL Server native backups, "bak" is used for LiteSpeed, "sqb" is used for Red Gate SQL Backup Pro, and "safe" is used for Idera SQL Safe Backup. + +### FileExtensionDiff + +Specify the file extension for differential backups. + +By default "bak" is used for SQL Server native backups, "bak" is used for LiteSpeed, "sqb" is used for Red Gate SQL Backup Pro, and "safe" is used for Idera SQL Safe Backup. + +### FileExtensionLog + +Specify the file extension for log backups. + +By default "trn" is used for SQL Server native backups, "trn" is used for LiteSpeed, "sqb" is used for Red Gate SQL Backup Pro, and "safe" is used for Idera SQL Safe Backup. + +### Init + +Specify whether the backup file should be overwritten. + +| Value | Description | +| --- | --- | +| Y | Overwrite the backup file. | +| N | Append the backup to the backup file. This is the default. | + +The Init option in DatabaseBackup uses the INIT option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### Format + +Specify whether a new media header should be created. + +| Value | Description | +| --- | --- | +| Y | Create a new media header. | +| N | Preserve the existing media header. This is the default. | + +The Format option in DatabaseBackup uses the FORMAT option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### ObjectLevelRecoveryMap + +Generate a map file during a backup for Object Level Recovery. This option is only supported in LiteSpeed. + +| Value | Description | +| --- | --- | +| Y | Generate a map file. | +| N | Do not generate a map file. This is the default. | + +### ExcludeLogShippedFromLogBackup + +Exclude databases configured for log shipping from log backups. + +| Value | Description | +| --- | --- | +| Y | Exclude databases configured for log shipping from log backups. This is the default. | +| N | Do not exclude databases configured for log shipping from log backups. | + +### ExcludeSeedingFromLogBackup + +Exclude databases from log backups while they are being seeded. + +| Value | Description | +| --- | --- | +| Y | Exclude databases from log backups while they are being seeded. | +| N | Do not exclude databases from log backups while they are being seeded. This is the default. | + +DatabaseBackup checks [sys.dm_hadr_physical_seeding_stats](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-objects/sys-dm-hadr-physical-seeding-stats) to determine whether the database is being seeded. + +### DirectoryCheck + +Check if the backup root directory exists. + +| Value | Description | +| --- | --- | +| Y | Check if the backup root directory exists. This is the default. | +| N | Do not check if the backup root directory exists. | + +### BackupOptions + +Options for backup to AWS S3 storage. + +The BackupOptions option in DatabaseBackup uses the BACKUP_OPTIONS option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### Stats + +Display the percentage completion of the backup operation. + +The Stats option in DatabaseBackup uses the STATS option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### ExpireDate + +Specify when the backup set for this backup can be overwritten. + +The ExpireDate option in DatabaseBackup uses the EXPIREDATE option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### RetainDays + +Specify the number of days that must elapse before this backup media set can be overwritten. + +The RetainDays option in DatabaseBackup uses the RETAINDAYS option in the SQL Server [BACKUP](https://learn.microsoft.com/en-us/sql/t-sql/statements/backup-transact-sql) command. + +### AllowNonCopyOnlyBackupsOnForwarder + +Specify whether non-copy-only backups should be allowed on the distributed availability group forwarder. + +| Value | Description | +| --- | --- | +| Y | Non-copy-only backups are allowed on the distributed availability group forwarder. | +| N | Non-copy-only backups are not allowed on the distributed availability group forwarder. This is the default. | + +### StringDelimiter + +Specify the string delimiter. By default, the string delimiter is the comma. + +### DatabaseOrder + +Specify the database order. + +| Value | Description | +| --- | --- | +| NULL | The order in which the databases have been specified. Then ascending by the database name. This is the default. | +| DATABASE_NAME_ASC | Ascending by the database name | +| DATABASE_NAME_DESC | Descending by the database name | +| DATABASE_SIZE_ASC | Ascending by the database size | +| DATABASE_SIZE_DESC | Descending by the database size | +| LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC | Ascending by log_since_last_log_backup_mb in sys.dm_db_log_stats | +| LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC | Descending by log_since_last_log_backup_mb in sys.dm_db_log_stats | + +### DatabasesInParallel + +Process databases in parallel. + +| Value | Description | +| --- | --- | +| Y | Process databases in parallel. | +| N | Process databases one at a time. This is the default. | + +You can process databases in parallel by creating multiple jobs with the same parameters, and adding the parameter @DatabasesInParallel = 'Y'. + +### LogToTable + +Log commands to the table dbo.CommandLog. + +| Value | Description | +| --- | --- | +| Y | Log commands to the table. | +| N | Do not log commands to the table. This is the default. | + +### Execute + +Execute commands. By default, the commands are executed normally. If this parameter is set to N, then the commands are printed only. + +| Value | Description | +| --- | --- | +| Y | Execute commands. This is the default. | +| N | Only print commands. | + +## Examples + +### A. Back up all user databases, using checksums and compression; verify the backup; and delete old backup files + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@Directory = 'C:\Backup', +@BackupType = 'FULL', +@Verify = 'Y', +@Compress = 'Y', +@Checksum = 'Y', +@CleanupTime = 24 +``` + +### B. Back up all user databases to a network share, and verify the backup + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@Directory = '\\Server1\Backup', +@BackupType = 'FULL', +@Verify = 'Y' +``` + +### C. Back up all user databases across four network shares, and verify the backup + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@Directory = '\\Server1\Backup, \\Server2\Backup, \\Server3\Backup, \\Server4\Backup', +@BackupType = 'FULL', +@Verify = 'Y', +@NumberOfFiles = 4 +``` + +### D. Back up all user databases to 64 files, using checksums and compression and setting the buffer count and the maximum transfer size + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@Directory = 'C:\Backup', +@BackupType = 'FULL', +@Compress = 'Y', +@Checksum = 'Y', +@BufferCount = 50, +@MaxTransferSize = 4194304, +@NumberOfFiles = 64 +``` + +### E. Back up all user databases to Azure Blob Storage, using compression + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@URL = 'https://myaccount.blob.core.windows.net/mycontainer', +@Credential = 'MyCredential', +@BackupType = 'FULL', +@Compress = 'Y', +@Verify = 'Y' +``` + +### F. Back up all user databases to S3 storage, using compression + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@URL = 's3://myaccount.s3.us-east-1.amazonaws.com/mybucket', +@BackupType = 'FULL', +@Compress = 'Y', +@Verify = 'Y', +@MaxTransferSize = 20971520, +@BackupOptions = '{"s3": {"region":"us-east-1"}}' +``` + +### G. Back up the transaction log of all user databases, using the option to change the backup type if a log backup cannot be performed + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@Directory = 'C:\Backup', +@BackupType = 'LOG', +@ChangeBackupType = 'Y' +``` + +### H. Back up all user databases, using compression, encryption, and a server certificate + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@Directory = 'C:\Backup', +@BackupType = 'FULL', +@Compress = 'Y', +@Encrypt = 'Y', +@EncryptionAlgorithm = 'AES_256', +@ServerCertificate = 'MyCertificate' +``` + +### I. Back up all user databases, using compression, encryption, and LiteSpeed, and limiting the CPU usage to 10 percent + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@Directory = 'C:\Backup', +@BackupType = 'FULL', +@BackupSoftware = 'LITESPEED', +@Compress = 'Y', +@Encrypt = 'Y', +@EncryptionAlgorithm = 'AES_256', +@EncryptionKey = 'MyPassword', +@Throttle = 10 +``` + +### J. Back up all user databases, using compression, encryption, and Red Gate SQL Backup Pro + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@Directory = 'C:\Backup', +@BackupType = 'FULL', +@BackupSoftware = 'SQLBACKUP', +@Compress = 'Y', +@Encrypt = 'Y', +@EncryptionAlgorithm = 'AES_256', +@EncryptionKey = 'MyPassword' +``` + +### K. Back up all user databases, using compression, encryption, and Idera SQL Safe Backup + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@Directory = 'C:\Backup', +@BackupType = 'FULL', +@BackupSoftware = 'SQLSAFE', +@Compress = 'Y', +@Encrypt = 'Y', +@EncryptionAlgorithm = 'AES_256', +@EncryptionKey = '8tPyzp4i1uF/ydAN1DqevdXDeVoryWRL' +``` + +### L. Back up all user databases, using mirrored backups + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@Directory = 'C:\Backup', +@MirrorDirectory = 'D:\Backup', +@BackupType = 'FULL', +@Compress = 'Y', +@Verify = 'Y', +@CleanupTime = 24, +@MirrorCleanupTime = 48 +``` + +### M. Back up all user databases, using Data Domain Boost + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@BackupType = 'FULL', +@Checksum = 'Y', +@BackupSoftware = 'DATA_DOMAIN_BOOST', +@DataDomainBoostHost = 'Host', +@DataDomainBoostUser = 'User', +@DataDomainBoostDevicePath = '/DevicePath', +@DataDomainBoostLockboxPath = 'C:\Program Files\DPSAPPS\common\lockbox', +@DataDomainBoostNoOutputTable = 'Y', +@CleanupTime = 24 +``` + +### N. Back up all user databases, with the default directory structure and file names + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@Directory = 'C:\Backup', +@BackupType = 'FULL', +@DirectoryStructure = '{ServerName}${InstanceName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}', +@AvailabilityGroupDirectoryStructure = '{ClusterName}${AvailabilityGroupName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}', +@FileName = '{ServerName}${InstanceName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension}', +@AvailabilityGroupFileName = '{ClusterName}${AvailabilityGroupName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension}' +``` + +### O. Back up all user databases, to a directory structure without the server name, instance name, cluster name, and availability group name + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@Directory = 'C:\Backup', +@BackupType = 'FULL', +@DirectoryStructure = '{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}', +@AvailabilityGroupDirectoryStructure = '{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly}' +``` + +### P. Back up all user databases, without creating any sub-directories + +```sql +EXECUTE dbo.DatabaseBackup +@Databases = 'USER_DATABASES', +@Directory = 'C:\Backup', +@BackupType = 'FULL', +@DirectoryStructure = NULL, +@AvailabilityGroupDirectoryStructure = NULL +``` + +## Execution + +You can execute the stored procedures from T-SQL job steps, and use [MaintenanceSolution.sql](/MaintenanceSolution.sql) to create the jobs. diff --git a/docs/sql-server-index-and-statistics-maintenance.md b/docs/sql-server-index-and-statistics-maintenance.md new file mode 100644 index 00000000..47b9b968 --- /dev/null +++ b/docs/sql-server-index-and-statistics-maintenance.md @@ -0,0 +1,522 @@ + + +# SQL Server Index and Statistics Maintenance + +This documentation is generated from [ola.hallengren.com/sql-server-index-and-statistics-maintenance.html](https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html), which is the primary source. + +IndexOptimize is the SQL Server Maintenance Solution’s stored procedure for rebuilding and reorganizing indexes and updating statistics. IndexOptimize is supported on SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, Azure SQL Database, and Azure SQL Managed Instance. + +## Download + +Download [MaintenanceSolution.sql](/MaintenanceSolution.sql). This script creates all the objects and jobs that you need. You can also [download](https://ola.hallengren.com/downloads.html) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). + +## License + +The SQL Server Maintenance Solution is [free](/LICENSE). + +## Parameters + +### Databases + +Select databases. The keywords SYSTEM_DATABASES, USER_DATABASES, ALL_DATABASES, and AVAILABILITY_GROUP_DATABASES are supported. The hyphen character (-) is used to exclude databases, and the percent character (%) is used for wildcard selection. All of these operations can be combined by using the comma (,). + +| Value | Description | +| --- | --- | +| SYSTEM_DATABASES | All system databases (master, msdb, and model) | +| USER_DATABASES | All user databases | +| ALL_DATABASES | All databases | +| AVAILABILITY_GROUP_DATABASES | All databases in availability groups | +| USER_DATABASES, -AVAILABILITY_GROUP_DATABASES | All user databases that are not in availability groups | +| Db1 | The database Db1 | +| Db1, Db2 | The databases Db1 and Db2 | +| USER_DATABASES, -Db1 | All user databases except Db1 | +| %Db% | All databases that have “Db” in the name | +| %Db%, -Db1 | All databases that have “Db” in the name except Db1 | +| ALL_DATABASES, -%Db% | All databases that do not have “Db” in the name | + +### FragmentationLow + +Specify index maintenance operations to be performed on a low-fragmented index. + +| Value | Description | +| --- | --- | +| INDEX_REBUILD_ONLINE | Rebuild index online. | +| INDEX_REBUILD_OFFLINE | Rebuild index offline. | +| INDEX_REORGANIZE | Reorganize index. | +| INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE | Rebuild index online. Rebuild index offline if online rebuilding is not supported on an index. | +| INDEX_REBUILD_ONLINE,INDEX_REORGANIZE | Rebuild index online. Reorganize index if online rebuilding is not supported on an index. | +| INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE | Reorganize index. Rebuild index online if reorganizing is not supported on an index. Rebuild index offline if reorganizing and online rebuilding are not supported on an index. | +| NULL | Do not perform index maintenance. This is the default for a low-fragmented index. | + +An online index rebuild or an index reorganization is not always possible. Because of this, you can specify multiple index-maintenance operations for each fragmentation group. These operations are prioritized from left to right: If the first operation is supported for the index, then that operation is used; if the first operation is not supported, then the second operation is used (if supported), and so on. If none of the specified operations are supported for an index, then that index is not maintained. + +IndexOptimize uses the SQL Server [ALTER INDEX](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-index-transact-sql) command: REBUILD WITH (ONLINE = ON) to rebuild indexes online, REBUILD WITH (ONLINE = OFF) to rebuild indexes offline, and REORGANIZE to reorganize indexes. + +### FragmentationMedium + +Specify index maintenance operations to be performed on a medium-fragmented index. + +| Value | Description | +| --- | --- | +| INDEX_REBUILD_ONLINE | Rebuild index online. | +| INDEX_REBUILD_OFFLINE | Rebuild index offline. | +| INDEX_REORGANIZE | Reorganize index. | +| INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE | Rebuild index online. Rebuild index offline if online rebuilding is not supported on an index. | +| INDEX_REBUILD_ONLINE,INDEX_REORGANIZE | Rebuild index online. Reorganize index if online rebuilding is not supported on an index. | +| INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE | Reorganize index. Rebuild index online if reorganizing is not supported on an index. Rebuild index offline if reorganizing and online rebuilding are not supported on an index. This is the default for a medium-fragmented index. | +| NULL | Do not perform index maintenance. | + +An online index rebuild or an index reorganization is not always possible. Because of this, you can specify multiple index-maintenance operations for each fragmentation group. These operations are prioritized from left to right: If the first operation is supported for the index, then that operation is used; if the first operation is not supported, then the second operation is used (if supported), and so on. If none of the specified operations are supported for an index, then that index is not maintained. + +IndexOptimize uses the SQL Server [ALTER INDEX](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-index-transact-sql) command: REBUILD WITH (ONLINE = ON) to rebuild indexes online, REBUILD WITH (ONLINE = OFF) to rebuild indexes offline, and REORGANIZE to reorganize indexes. + +### FragmentationHigh + +Specify index maintenance operations to be performed on a high-fragmented index. + +| Value | Description | +| --- | --- | +| INDEX_REBUILD_ONLINE | Rebuild index online. | +| INDEX_REBUILD_OFFLINE | Rebuild index offline. | +| INDEX_REORGANIZE | Reorganize index. | +| INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE | Rebuild index online. Rebuild index offline if online rebuilding is not supported on an index.
This is the default for a high-fragmented index. | +| INDEX_REBUILD_ONLINE,INDEX_REORGANIZE | Rebuild index online. Reorganize index if online rebuilding is not supported on an index. | +| INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE | Reorganize index. Rebuild index online if reorganizing is not supported on an index. Rebuild index offline if reorganizing and online rebuilding are not supported on an index. | +| NULL | Do not perform index maintenance. | + +An online index rebuild or an index reorganization is not always possible. Because of this, you can specify multiple index-maintenance operations for each fragmentation group. These operations are prioritized from left to right: If the first operation is supported for the index, then that operation is used; if the first operation is not supported, then the second operation is used (if supported), and so on. If none of the specified operations are supported for an index, then that index is not maintained. + +IndexOptimize uses the SQL Server [ALTER INDEX](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-index-transact-sql) command: REBUILD WITH (ONLINE = ON) to rebuild indexes online, REBUILD WITH (ONLINE = OFF) to rebuild indexes offline, and REORGANIZE to reorganize indexes. + +### FragmentationLevel1 + +Set the lower limit, as a percentage, for medium fragmentation. The default is 5 percent. This is based on Microsoft’s recommendation in [Books Online](https://learn.microsoft.com/en-us/sql/relational-databases/indexes/reorganize-and-rebuild-indexes). + +IndexOptimize checks avg_fragmentation_in_percent in [sys.dm_db_index_physical_stats](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-index-physical-stats-transact-sql) to determine the fragmentation. + +### FragmentationLevel2 + +Set the lower limit, as a percentage, for high fragmentation. The default is 30 percent. This is based on Microsoft’s recommendation in [Books Online](https://learn.microsoft.com/en-us/sql/relational-databases/indexes/reorganize-and-rebuild-indexes). + +IndexOptimize checks avg_fragmentation_in_percent in [sys.dm_db_index_physical_stats](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-index-physical-stats-transact-sql) to determine the fragmentation. + +### MinNumberOfPages + +Set a size, in pages; indexes with a smaller number of pages are skipped for index maintenance. The default is 1000 pages. This is based on Microsoft’s recommendation. + +IndexOptimize checks page_count in [sys.dm_db_index_physical_stats](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-index-physical-stats-transact-sql) to determine the size of the index. + +### MaxNumberOfPages + +Set a size, in pages; indexes with a greater number of pages are skipped for index maintenance. The default is no limitation. + +IndexOptimize checks page_count in [sys.dm_db_index_physical_stats](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-index-physical-stats-transact-sql) to determine the size of the index. + +### SortInTempdb + +Use tempdb for sort operations when rebuilding indexes. + +| Value | Description | +| --- | --- | +| Y | Use tempdb for sort operations when rebuilding indexes. | +| N | Do not use tempdb for sort operations when rebuilding indexes. This is the default. | + +The SortInTempdb option in IndexOptimize uses the SORT_IN_TEMPDB option in the SQL Server [ALTER INDEX](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-index-transact-sql) command. + +### MaxDOP + +Specify the number of CPUs to use when rebuilding indexes. If this number is not specified, the global maximum degree of parallelism is used. + +The MaxDOP option in IndexOptimize uses the MAXDOP option in the SQL Server [ALTER INDEX](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-index-transact-sql) command. + +### FillFactor + +Indicate, as a percentage, how full the pages should be made when rebuilding indexes. If a percentage is not specified, the fill factor in [sys.indexes](https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-indexes-transact-sql) is used. + +The FillFactor option in IndexOptimize uses the FILLFACTOR option in the SQL Server [ALTER INDEX](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-index-transact-sql) command. + +### PadIndex + +Apply the percentage of free space that the fill factor specifies to the intermediate-level pages of the index. + +| Value | Description | +| --- | --- | +| Y | Apply the percentage of free space that the fill factor specifies to the intermediate-level pages of the index. | +| N | The intermediate-level pages of the index are filled to near capacity. | +| NULL | Leave the pad index setting unchanged. This is the default. | + +The PadIndex option in IndexOptimize uses the PAD_INDEX option in the SQL Server [ALTER INDEX](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-index-transact-sql) command. + +### DataCompression + +Set the data compression type that is applied when rebuilding indexes. + +| Value | Description | +| --- | --- | +| NONE | Rebuild the index without data compression, removing any existing compression. | +| ROW | Rebuild the index with row compression. | +| PAGE | Rebuild the index with page compression. | +| NULL | Leave the existing data compression setting unchanged. This is the default. | + +The DataCompression option in IndexOptimize uses the DATA_COMPRESSION option in the SQL Server [ALTER INDEX](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-index-transact-sql) command. + +### WaitAtLowPriorityMaxDuration + +The time, in minutes, that an online index rebuild operation will wait for low-priority locks. + +The WaitAtLowPriorityMaxDuration option in IndexOptimize uses the WAIT_AT_LOW_PRIORITY and MAX_DURATION options in the SQL Server [ALTER INDEX](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-index-transact-sql) command. + +### WaitAtLowPriorityAbortAfterWait + +The action that will be performed after an online index rebuild operation has been waiting for low-priority locks. + +| Value | Description | +| --- | --- | +| NONE | Continue waiting for locks with normal priority. | +| SELF | Abort the online index rebuild operation. | +| BLOCKERS | Kill user transactions that block the online index rebuild operation. | + +The WaitAtLowPriorityAbortAfterWait option in IndexOptimize uses the WAIT_AT_LOW_PRIORITY and ABORT_AFTER_WAIT options in the SQL Server [ALTER INDEX](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-index-transact-sql) command. + +### Resumable + +Specify whether an online index operation is resumable. + +| Value | Description | +| --- | --- | +| Y | Index operation is resumable. | +| N | Index operation is not resumable. This is the default. | + +The Resumable option in IndexOptimize uses the RESUMABLE option in the SQL Server [ALTER INDEX](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-index-transact-sql) command. + +### LOBCompaction + +Compact pages that contain large object (LOB) columns when reorganizing indexes. + +| Value | Description | +| --- | --- | +| Y | Compact pages that contain LOB columns when reorganizing indexes. This is the default. | +| N | Do not compact pages that contain LOB columns when reorganizing indexes. | + +The LOBCompaction option in IndexOptimize uses the LOB_COMPACTION option in the SQL Server [ALTER INDEX](https://learn.microsoft.com/en-us/sql/t-sql/statements/alter-index-transact-sql) command. + +### UpdateStatistics + +Update statistics. + +| Value | Description | +| --- | --- | +| ALL | Update index and column statistics. | +| INDEX | Update index statistics. | +| COLUMNS | Update column statistics. | +| NULL | Do not perform statistics maintenance. This is the default. | + +IndexOptimize uses the SQL Server [UPDATE STATISTICS](https://learn.microsoft.com/en-us/sql/t-sql/statements/update-statistics-transact-sql) command to update statistics. + +### OnlyModifiedStatistics + +Update statistics only if any rows have been modified since the most recent statistics update. + +| Value | Description | +| --- | --- | +| Y | Update statistics only if any rows have been modified since the most recent statistics update. | +| N | Update statistics regardless of whether any rows have been modified. This is the default. | + +IndexOptimize checks modification_counter in [sys.dm_db_stats_properties](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-stats-properties-transact-sql). For incremental statistics it checks modification_counter in [sys.dm_db_incremental_stats_properties](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-incremental-stats-properties-transact-sql). + +### StatisticsModificationLevel + +Specify a percentage of modified rows for when the statistics should be updated. Statistics will also be updated when the number of modified rows has reached a decreasing, dynamic threshold, SQRT(number of rows * 1000). + +IndexOptimize checks the columns modification_counter and rows in [sys.dm_db_stats_properties](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-stats-properties-transact-sql). For incremental statistics it checks the columns modification_counter and rows in [sys.dm_db_incremental_stats_properties](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-incremental-stats-properties-transact-sql). + +### StatisticsSample + +Indicate, as a percentage, how much of a table is gathered when updating statistics. A value of 100 is equivalent to a full scan. If no value is specified, then SQL Server automatically computes the required sample. + +The StatisticsSample option in IndexOptimize uses the SAMPLE and FULLSCAN options in the SQL Server [UPDATE STATISTICS](https://learn.microsoft.com/en-us/sql/t-sql/statements/update-statistics-transact-sql) command. + +### StatisticsPersistSample + +Specify whether the sampling percentage is persisted for subsequent statistics updates. + +| Value | Description | +| --- | --- | +| Y | Persist the sampling percentage. | +| N | Remove any existing sampling persistence. | +| NULL | Leave the existing persistence setting unchanged. This is the default. | + +The StatisticsPersistSample option in IndexOptimize uses the PERSIST_SAMPLE_PERCENT option in the SQL Server [UPDATE STATISTICS](https://learn.microsoft.com/en-us/sql/t-sql/statements/update-statistics-transact-sql) command. + +StatisticsPersistSample can only be used together with StatisticsSample. + +### StatisticsResample + +Update statistics with the most recent sample. + +| Value | Description | +| --- | --- | +| Y | Update statistics with the most recent sample. | +| N | Let SQL Server automatically compute the required sample. This is the default. | + +The StatisticsResample option in IndexOptimize uses the RESAMPLE option in the SQL Server [UPDATE STATISTICS](https://learn.microsoft.com/en-us/sql/t-sql/statements/update-statistics-transact-sql) command. + +You cannot combine the options StatisticsSample and StatisticsResample. + +### PartitionLevel + +Maintain partitioned indexes on the partition level. If this parameter is set to Y, the fragmentation level and page count are checked for each partition. The appropriate index maintenance (reorganize or rebuild) is then performed for each partition. + +| Value | Description | +| --- | --- | +| Y | Maintain partitioned indexes on the partition level. This is the default. | +| N | Maintain partitioned indexes on the index level. | + +### MSShippedObjects + +Maintain indexes and statistics on objects that are created by internal SQL Server components. + +| Value | Description | +| --- | --- | +| Y | Maintain indexes and statistics on objects that are created by internal SQL Server components. | +| N | Do not maintain indexes and statistics on objects that are created by internal SQL Server components. This is the default. | + +IndexOptimize checks is_ms_shipped in [sys.objects](https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-objects-transact-sql) to determine whether an object was created by an internal SQL Server component. + +### Indexes + +Select indexes. If this parameter is not specified, all indexes are selected. The ALL_INDEXES keyword is supported. The hyphen character (-) is used to exclude indexes, and the percent character (%) is used for wildcard selection. All of these operations can be combined by using the comma (,). + +| Value | Description | +| --- | --- | +| ALL_INDEXES | All indexes | +| Db1.Schema1.Tbl1.Idx1 | The index Idx1 on the object Schema1.Tbl1 in the database Db1 | +| Db1.Schema1.Tbl1.Idx1, Db2.Schema2.Tbl2.Idx2 | The index Idx1 on the object Schema1.Tbl1 in the database Db1 and the index Idx2 on the object Schema2.Tbl2 in the database Db2 | +| Db1.Schema1.Tbl1 | All indexes on the object Schema1.Tbl1 in the database Db1 | +| Db1.Schema1.Tbl1, Db2.Schema2.Tbl2 | All indexes on the object Schema1.Tbl1 in the database Db1 and all indexes on the object Schema2.Tbl2 in the database Db2 | +| Db1.Schema1.% | All indexes in the schema Schema1 in the database Db1 | +| %.Schema1.% | All indexes in the schema Schema1 in all databases | +| ALL_INDEXES, -Db1.Schema1.Tbl1.Idx1 | All indexes except the index Idx1 on the object Schema1.Tbl1 in the database Db1 | +| ALL_INDEXES, -Db1.Schema1.Tbl1 | All indexes except indexes on the object Schema1.Tbl1 in the database Db1 | + +### TimeLimit + +Set the time, in seconds, after which no commands are executed. By default, the time is not limited. + +### Delay + +Set the delay, in seconds, between index commands. By default, there is no delay. + +### AvailabilityGroups + +Select availability groups. The keyword ALL_AVAILABILITY_GROUPS is supported. The hyphen character (-) is used to exclude availability groups, and the percent character (%) is used for wildcard selection. All of these operations can be combined by using the comma (,). + +| Value | Description | +| --- | --- | +| ALL_AVAILABILITY_GROUPS | All availability groups | +| AG1 | The availability group AG1 | +| AG1, AG2 | The availability groups AG1 and AG2 | +| ALL_AVAILABILITY_GROUPS, -AG1 | All availability groups except AG1 | +| %AG% | All availability groups that have “AG” in the name | +| %AG%, -AG1 | All availability groups that have “AG” in the name except AG1 | +| ALL_AVAILABILITY_GROUPS, -%AG% | All availability groups that do not have “AG” in the name | + +### LockTimeout + +Set the time, in seconds, that a command waits for a lock to be released. By default, the time is not limited. + +The LockTimeout option uses the [SET LOCK_TIMEOUT](https://learn.microsoft.com/en-us/sql/t-sql/statements/set-lock-timeout-transact-sql) statement in SQL Server. + +### LockMessageSeverity + +Set the severity for lock timeouts and deadlocks. + +| Value | Description | +| --- | --- | +| 10 | This is an informational message. | +| 16 | This is an error message. This is the default. | + +### StringDelimiter + +Specify the string delimiter. By default, the string delimiter is the comma. + +### DatabaseOrder + +Specify the database order. + +| Value | Description | +| --- | --- | +| NULL | The order in which the databases have been specified. Then ascending by the database name. This is the default. | +| DATABASE_NAME_ASC | Ascending by the database name | +| DATABASE_NAME_DESC | Descending by the database name | +| DATABASE_SIZE_ASC | Ascending by the database size | +| DATABASE_SIZE_DESC | Descending by the database size | + +### DatabasesInParallel + +Process databases in parallel. + +| Value | Description | +| --- | --- | +| Y | Process databases in parallel. | +| N | Process databases one at a time. This is the default. | + +You can process databases in parallel by creating multiple jobs with the same parameters, and adding the parameter @DatabasesInParallel = 'Y'. + +### ExecuteAsUser + +Change the execution context to a user. The user can be dbo or any other user. The user has to exist in all databases that you are working with. + +The ExecuteAsUser option in IndexOptimize uses the [EXECUTE AS](https://learn.microsoft.com/en-us/sql/t-sql/statements/execute-as-transact-sql) command in SQL Server. + +### LogToTable + +Log commands to the table dbo.CommandLog. + +| Value | Description | +| --- | --- | +| Y | Log commands to the table. | +| N | Do not log commands to the table. This is the default. | + +### Execute + +Execute commands. By default, the commands are executed normally. If this parameter is set to N, then the commands are printed only. + +| Value | Description | +| --- | --- | +| Y | Execute commands. This is the default. | +| N | Only print commands. | + +## Examples + +### A. Rebuild or reorganize all indexes with fragmentation on all user databases + +```sql +EXECUTE dbo.IndexOptimize +@Databases = 'USER_DATABASES', +@FragmentationLow = NULL, +@FragmentationMedium = 'INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationHigh = 'INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationLevel1 = 5, +@FragmentationLevel2 = 30 +``` + +### B. Rebuild or reorganize all indexes with fragmentation and update modified statistics on all user databases + +```sql +EXECUTE dbo.IndexOptimize +@Databases = 'USER_DATABASES', +@FragmentationLow = NULL, +@FragmentationMedium = 'INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationHigh = 'INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationLevel1 = 5, +@FragmentationLevel2 = 30, +@UpdateStatistics = 'ALL', +@OnlyModifiedStatistics = 'Y' +``` + +### C. Update statistics on all user databases + +```sql +EXECUTE dbo.IndexOptimize +@Databases = 'USER_DATABASES', +@FragmentationLow = NULL, +@FragmentationMedium = NULL, +@FragmentationHigh = NULL, +@UpdateStatistics = 'ALL' +``` + +### D. Update modified statistics on all user databases + +```sql +EXECUTE dbo.IndexOptimize +@Databases = 'USER_DATABASES', +@FragmentationLow = NULL, +@FragmentationMedium = NULL, +@FragmentationHigh = NULL, +@UpdateStatistics = 'ALL', +@OnlyModifiedStatistics = 'Y' +``` + +### E. Rebuild or reorganize all indexes with fragmentation on all user databases, performing sort operations in tempdb and using all available CPUs + +```sql +EXECUTE dbo.IndexOptimize +@Databases = 'USER_DATABASES', +@FragmentationLow = NULL, +@FragmentationMedium = 'INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationHigh = 'INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationLevel1 = 5, +@FragmentationLevel2 = 30, +@SortInTempdb = 'Y', +@MaxDOP = 0 +``` + +### F. Rebuild or reorganize all indexes with fragmentation on all user databases, using the option to maintain partitioned indexes on the partition level + +```sql +EXECUTE dbo.IndexOptimize +@Databases = 'USER_DATABASES', +@FragmentationLow = NULL, +@FragmentationMedium = 'INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationHigh = 'INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationLevel1 = 5, +@FragmentationLevel2 = 30, +@PartitionLevel = 'Y' +``` + +### G. Rebuild or reorganize all indexes with fragmentation on all user databases, with a time limit so that no commands are executed after 3600 seconds + +```sql +EXECUTE dbo.IndexOptimize +@Databases = 'USER_DATABASES', +@FragmentationLow = NULL, +@FragmentationMedium = 'INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationHigh = 'INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationLevel1 = 5, +@FragmentationLevel2 = 30, +@TimeLimit = 3600 +``` + +### H. Rebuild or reorganize all indexes with fragmentation on the table Production.Product in the database AdventureWorks + +```sql +EXECUTE dbo.IndexOptimize +@Databases = 'AdventureWorks', +@FragmentationLow = NULL, +@FragmentationMedium = 'INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationHigh = 'INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationLevel1 = 5, +@FragmentationLevel2 = 30, +@Indexes = 'AdventureWorks.Production.Product' +``` + +### I. Rebuild or reorganize all indexes with fragmentation except indexes on the table Production.Product in the database AdventureWorks + +```sql +EXECUTE dbo.IndexOptimize +@Databases = 'USER_DATABASES', +@FragmentationLow = NULL, +@FragmentationMedium = 'INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationHigh = 'INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationLevel1 = 5, +@FragmentationLevel2 = 30, +@Indexes = 'ALL_INDEXES, -AdventureWorks.Production.Product' +``` + +### J. Rebuild or reorganize all indexes with fragmentation on all user databases and log the results to a table + +```sql +EXECUTE dbo.IndexOptimize +@Databases = 'USER_DATABASES', +@FragmentationLow = NULL, +@FragmentationMedium = 'INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationHigh = 'INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationLevel1 = 5, +@FragmentationLevel2 = 30, +@LogToTable = 'Y' +``` + +## Execution + +You can execute the stored procedures from T-SQL job steps, and use [MaintenanceSolution.sql](/MaintenanceSolution.sql) to create the jobs. diff --git a/docs/sql-server-integrity-check.md b/docs/sql-server-integrity-check.md new file mode 100644 index 00000000..e6373c3e --- /dev/null +++ b/docs/sql-server-integrity-check.md @@ -0,0 +1,352 @@ + + +# SQL Server Integrity Check + +This documentation is generated from [ola.hallengren.com/sql-server-integrity-check.html](https://ola.hallengren.com/sql-server-integrity-check.html), which is the primary source. + +DatabaseIntegrityCheck is the SQL Server Maintenance Solution’s stored procedure for checking the integrity of databases. DatabaseIntegrityCheck is supported on SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, Azure SQL Database, and Azure SQL Managed Instance. + +## Download + +Download [MaintenanceSolution.sql](/MaintenanceSolution.sql). This script creates all the objects and jobs that you need. You can also [download](https://ola.hallengren.com/downloads.html) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). + +## License + +The SQL Server Maintenance Solution is [free](/LICENSE). + +## Parameters + +### Databases + +Select databases. The keywords SYSTEM_DATABASES, USER_DATABASES, ALL_DATABASES, and AVAILABILITY_GROUP_DATABASES are supported. The hyphen character (-) is used to exclude databases, and the percent character (%) is used for wildcard selection. All of these operations can be combined by using the comma (,). + +| Value | Description | +| --- | --- | +| SYSTEM_DATABASES | All system databases (master, msdb, and model) | +| USER_DATABASES | All user databases | +| ALL_DATABASES | All databases | +| AVAILABILITY_GROUP_DATABASES | All databases in availability groups | +| USER_DATABASES, -AVAILABILITY_GROUP_DATABASES | All user databases that are not in availability groups | +| Db1 | The database Db1 | +| Db1, Db2 | The databases Db1 and Db2 | +| USER_DATABASES, -Db1 | All user databases except Db1 | +| %Db% | All databases that have “Db” in the name | +| %Db%, -Db1 | All databases that have “Db” in the name except Db1 | +| ALL_DATABASES, -%Db% | All databases that do not have “Db” in the name | + +### CheckCommands + +Specify the integrity check commands to be performed. + +| Value | Description | +| --- | --- | +| CHECKDB | Check the database. This is the default. | +| CHECKFILEGROUP | Check the filegroups. | +| CHECKTABLE | Check the tables and the indexed views. | +| CHECKALLOC | Check the disk space allocation structures. | +| CHECKCATALOG | Check the catalog consistency. | +| CHECKALLOC,CHECKCATALOG | Check the disk space allocation structures and the catalog consistency. | +| CHECKFILEGROUP,CHECKCATALOG | Check the filegroups and the catalog consistency. | +| CHECKALLOC,CHECKTABLE,CHECKCATALOG | Check the disk space allocation structures, the tables and the indexed views, and the catalog consistency. | + +DatabaseIntegrityCheck uses these SQL Server DBCC commands: [DBCC CHECKDB](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkdb-transact-sql) to check the database, [DBCC CHECKFILEGROUP](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkfilegroup-transact-sql) to check the filegroups, [DBCC CHECKTABLE](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checktable-transact-sql) to check the tables and the indexed views, [DBCC CHECKALLOC](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkalloc-transact-sql) to check the disk space allocation structures, and [DBCC CHECKCATALOG](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkcatalog-transact-sql) to check the catalog consistency. + +### PhysicalOnly + +Limit the checks to the physical structures of the database. + +| Value | Description | +| --- | --- | +| Y | Limit the checks to the physical structures of the database. | +| N | Do not limit the checks to the physical structures of the database. This is the default. | + +The PhysicalOnly option in DatabaseIntegrityCheck uses the PHYSICAL_ONLY option in the SQL Server [DBCC CHECKDB](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkdb-transact-sql), [DBCC CHECKFILEGROUP](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkfilegroup-transact-sql), and [DBCC CHECKTABLE](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checktable-transact-sql) commands. + +### DataPurity + +Check for column values that are not valid or out of range. + +| Value | Description | +| --- | --- | +| Y | Check for column values that are not valid or out of range. | +| N | Do not check for column values that are not valid or out of range. This is the default. | + +The DataPurity option in DatabaseIntegrityCheck uses the DATA_PURITY option in the SQL Server [DBCC CHECKDB](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkdb-transact-sql) and [DBCC CHECKTABLE](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checktable-transact-sql) commands. + +### NoIndex + +Do not check nonclustered indexes. + +| Value | Description | +| --- | --- | +| Y | Do not check nonclustered indexes. | +| N | Check nonclustered indexes. This is the default. | + +The NoIndex option in DatabaseIntegrityCheck uses the NOINDEX option in the SQL Server [DBCC CHECKDB](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkdb-transact-sql), [DBCC CHECKFILEGROUP](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkfilegroup-transact-sql), [DBCC CHECKTABLE](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checktable-transact-sql), and [DBCC CHECKALLOC](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkalloc-transact-sql) commands. + +### ExtendedLogicalChecks + +Perform extended logical checks. + +| Value | Description | +| --- | --- | +| Y | Perform extended logical checks. | +| N | Do not perform extended logical checks. This is the default. | + +The ExtendedLogicalChecks option in DatabaseIntegrityCheck uses the EXTENDED_LOGICAL_CHECKS option in the SQL Server [DBCC CHECKDB](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkdb-transact-sql) command. + +You cannot combine the options PhysicalOnly and ExtendedLogicalChecks. + +### NoInformationalMessages + +Suppress all informational messages. + +| Value | Description | +| --- | --- | +| Y | Suppress all informational messages. | +| N | Do not suppress informational messages. This is the default. | + +The NoInformationalMessages option in DatabaseIntegrityCheck uses the NO_INFOMSGS option in the SQL Server [DBCC CHECKDB](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkdb-transact-sql), [DBCC CHECKFILEGROUP](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkfilegroup-transact-sql), [DBCC CHECKTABLE](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checktable-transact-sql), [DBCC CHECKALLOC](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkalloc-transact-sql), and [DBCC CHECKCATALOG](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkcatalog-transact-sql) commands. + +### TabLock + +Use locks instead of an internal database snapshot. + +| Value | Description | +| --- | --- | +| Y | Use locks to perform the consistency checks. | +| N | Use an internal database snapshot to perform the consistency checks. This is the default. | + +The TabLock option in DatabaseIntegrityCheck uses the TABLOCK option in the SQL Server [DBCC CHECKDB](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkdb-transact-sql), [DBCC CHECKFILEGROUP](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkfilegroup-transact-sql), [DBCC CHECKTABLE](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checktable-transact-sql), and [DBCC CHECKALLOC](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkalloc-transact-sql) commands. + +### FileGroups + +Select filegroups. The ALL_FILEGROUPS keyword is supported. The hyphen character (-) is used to exclude filegroups, and the percent character (%) is used for wildcard selection. All of these operations can be combined by using the comma (,). + +| Value | Description | +| --- | --- | +| ALL_FILEGROUPS | All filegroups | +| Db1.FileGroup1 | The filegroup FileGroup1 in the database Db1 | +| Db1.FileGroup1, Db2.FileGroup2 | The filegroup FileGroup1 in the database Db1 and the filegroup FileGroup2 in the database Db2 | +| ALL_FILEGROUPS, -Db1.FileGroup1 | All filegroups except the filegroup FileGroup1 in the database Db1 | +| Db1.%FileGroup% | All filegroups in the database Db1 that have “FileGroup” in the name | + +This option can be used only if CHECKFILEGROUP is specified in the CheckCommands option. + +### Objects + +Select objects. The ALL_OBJECTS keyword is supported. The hyphen character (-) is used to exclude objects, and the percent character (%) is used for wildcard selection. All of these operations can be combined by using the comma (,). + +| Value | Description | +| --- | --- | +| ALL_OBJECTS | All objects | +| Db1.Schema1.Tbl1 | The object Schema1.Tbl1 in the database Db1 | +| Db1.Schema1.Object1, Db2.Schema2.Object2 | The object Schema1.Object1 in the database Db1 and the object Schema2.Object2 in the database Db2 | +| ALL_OBJECTS, -Db1.Schema1.Object1 | All objects except the object Schema1.Object1 in the database Db1 | +| Db1.Schema1.% | All objects in the schema Schema1 in the database Db1 | + +This option can be used only if CHECKTABLE is specified in the CheckCommands option. + +### MaxDOP + +Specify the number of CPUs to use when checking the database, filegroup, or table. If this number is not specified, the global maximum degree of parallelism is used. + +The MaxDOP option in DatabaseIntegrityCheck uses the MAXDOP option in the SQL Server [DBCC CHECKDB](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkdb-transact-sql), [DBCC CHECKFILEGROUP](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkfilegroup-transact-sql), and [DBCC CHECKTABLE](https://learn.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checktable-transact-sql) commands. + +### AvailabilityGroups + +Select availability groups. The keyword ALL_AVAILABILITY_GROUPS is supported. The hyphen character (-) is used to exclude availability groups, and the percent character (%) is used for wildcard selection. All of these operations can be combined by using the comma (,). + +| Value | Description | +| --- | --- | +| ALL_AVAILABILITY_GROUPS | All availability groups | +| AG1 | The availability group AG1 | +| AG1, AG2 | The availability groups AG1 and AG2 | +| ALL_AVAILABILITY_GROUPS, -AG1 | All availability groups except AG1 | +| %AG% | All availability groups that have “AG” in the name | +| %AG%, -AG1 | All availability groups that have “AG” in the name except AG1 | +| ALL_AVAILABILITY_GROUPS, -%AG% | All availability groups that do not have “AG” in the name | + +### AvailabilityGroupReplicas + +Specify which replicas in availability groups should be checked. + +| Value | Description | +| --- | --- | +| ALL | Perform the checks on all replicas. This is the default. | +| PRIMARY | Perform the checks on the primary replica. | +| SECONDARY | Perform the checks on the secondary replicas. | +| PREFERRED_BACKUP_REPLICA | Perform the checks on the preferred backup replica. | + +### Updateability + +Select READ_ONLY/READ_WRITE databases. + +| Value | Description | +| --- | --- | +| ALL | READ_ONLY and READ_WRITE databases. This is the default. | +| READ_ONLY | READ_ONLY databases | +| READ_WRITE | READ_WRITE databases | + +is_read_only in [sys.databases](https://learn.microsoft.com/en-us/sql/relational-databases/system-catalog-views/sys-databases-transact-sql) is used to check if a database is READ_ONLY or READ_WRITE. + +### TimeLimit + +Set the time, in seconds, after which no commands are executed. By default, the time is not limited. + +### LockTimeout + +Set the time, in seconds, that a command waits for a lock to be released. By default, the time is not limited. + +The LockTimeout option uses the [SET LOCK_TIMEOUT](https://learn.microsoft.com/en-us/sql/t-sql/statements/set-lock-timeout-transact-sql) statement in SQL Server. + +### LockMessageSeverity + +Set the severity for lock timeouts and deadlocks. + +| Value | Description | +| --- | --- | +| 10 | This is an informational message. | +| 16 | This is an error message. This is the default. | + +### StringDelimiter + +Specify the string delimiter. By default, the string delimiter is the comma. + +### DatabaseOrder + +Specify the database order. + +| Value | Description | +| --- | --- | +| NULL | The order in which the databases have been specified. Then ascending by the database name. This is the default. | +| DATABASE_NAME_ASC | Ascending by the database name | +| DATABASE_NAME_DESC | Descending by the database name | +| DATABASE_SIZE_ASC | Ascending by the database size | +| DATABASE_SIZE_DESC | Descending by the database size | +| DATABASE_LAST_GOOD_CHECK_ASC | Ascending by LastGoodCheckDbTime in DATABASEPROPERTYEX | +| DATABASE_LAST_GOOD_CHECK_DESC | Descending by LastGoodCheckDbTime in DATABASEPROPERTYEX | +| REPLICA_LAST_GOOD_CHECK_ASC | Ascending by the last successful checkdb in the dbo.CommandLog table | +| REPLICA_LAST_GOOD_CHECK_DESC | Descending by the last successful checkdb in the dbo.CommandLog table | + +### DatabasesInParallel + +Process databases in parallel. + +| Value | Description | +| --- | --- | +| Y | Process databases in parallel. | +| N | Process databases one at a time. This is the default. | + +You can process databases in parallel by creating multiple jobs with the same parameters, and adding the parameter @DatabasesInParallel = 'Y'. + +### LogToTable + +Log commands to the table dbo.CommandLog. + +| Value | Description | +| --- | --- | +| Y | Log commands to the table. | +| N | Do not log commands to the table. This is the default. | + +### Execute + +Execute commands. By default, the commands are executed normally. If this parameter is set to N, then the commands are printed only. + +| Value | Description | +| --- | --- | +| Y | Execute commands. This is the default. | +| N | Only print commands. | + +## Examples + +### A. Check the integrity of all user databases + +```sql +EXECUTE dbo.DatabaseIntegrityCheck +@Databases = 'USER_DATABASES', +@CheckCommands = 'CHECKDB' +``` + +### B. Check the physical integrity of all user databases + +```sql +EXECUTE dbo.DatabaseIntegrityCheck +@Databases = 'USER_DATABASES', +@CheckCommands = 'CHECKDB', +@PhysicalOnly = 'Y' +``` + +### C. Check the integrity of all user databases, using the option not to check nonclustered indexes + +```sql +EXECUTE dbo.DatabaseIntegrityCheck +@Databases = 'USER_DATABASES', +@CheckCommands = 'CHECKDB', +@NoIndex = 'Y' +``` + +### D. Check the integrity of all user databases, using the option to perform extended logical checks + +```sql +EXECUTE dbo.DatabaseIntegrityCheck +@Databases = 'USER_DATABASES', +@CheckCommands = 'CHECKDB', +@ExtendedLogicalChecks = 'Y' +``` + +### E. Check the integrity of the filegroup PRIMARY in the database AdventureWorks + +```sql +EXECUTE dbo.DatabaseIntegrityCheck +@Databases = 'AdventureWorks', +@CheckCommands = 'CHECKFILEGROUP', +@FileGroups = 'AdventureWorks.PRIMARY' +``` + +### F. Check the integrity of all filegroups except the filegroup PRIMARY in the database AdventureWorks + +```sql +EXECUTE dbo.DatabaseIntegrityCheck +@Databases = 'USER_DATABASES', +@CheckCommands = 'CHECKFILEGROUP', +@FileGroups = 'ALL_FILEGROUPS, -AdventureWorks.PRIMARY' +``` + +### G. Check the integrity of the table Production.Product in the database AdventureWorks + +```sql +EXECUTE dbo.DatabaseIntegrityCheck +@Databases = 'AdventureWorks', +@CheckCommands = 'CHECKTABLE', +@Objects = 'AdventureWorks.Production.Product' +``` + +### H. Check the integrity of all tables except the table Production.Product in the database AdventureWorks + +```sql +EXECUTE dbo.DatabaseIntegrityCheck +@Databases = 'USER_DATABASES', +@CheckCommands = 'CHECKTABLE', +@Objects = 'ALL_OBJECTS, -AdventureWorks.Production.Product' +``` + +### I. Check the disk-space allocation structures of all user databases + +```sql +EXECUTE dbo.DatabaseIntegrityCheck +@Databases = 'USER_DATABASES', +@CheckCommands = 'CHECKALLOC' +``` + +### J. Check the catalog consistency of all user databases + +```sql +EXECUTE dbo.DatabaseIntegrityCheck +@Databases = 'USER_DATABASES', +@CheckCommands = 'CHECKCATALOG' +``` + +## Execution + +You can execute the stored procedures from T-SQL job steps, and use [MaintenanceSolution.sql](/MaintenanceSolution.sql) to create the jobs. From 578f1db3783de87d8911ec30f904724fb7009170 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 21:08:58 +0200 Subject: [PATCH 098/177] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 8fb03bdd..6d41390d 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,8 @@ Supported versions: SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Serve - [Frequently Asked Questions](https://ola.hallengren.com/frequently-asked-questions.html) - [Version History](https://ola.hallengren.com/versions.html) +A copy of the documentation is also available in this repository: [docs](/docs). + [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 From c8a0ad9bf1ce075040deddfd5326e580852b016f Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 21:20:24 +0200 Subject: [PATCH 099/177] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6d41390d..2b3c1854 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Supported versions: SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Serve - [Frequently Asked Questions](https://ola.hallengren.com/frequently-asked-questions.html) - [Version History](https://ola.hallengren.com/versions.html) -A copy of the documentation is also available in this repository: [docs](/docs). +A copy of the stored procedure documentation is also available in this repository: [docs](/docs). [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 From 9a13acda224687401c30e9dff7dcc2aef3712873 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 21:31:03 +0200 Subject: [PATCH 100/177] Add files via upload --- docs/sql-server-backup.md | 2 +- docs/sql-server-index-and-statistics-maintenance.md | 2 +- docs/sql-server-integrity-check.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/sql-server-backup.md b/docs/sql-server-backup.md index f2437aa7..1adea1aa 100644 --- a/docs/sql-server-backup.md +++ b/docs/sql-server-backup.md @@ -8,7 +8,7 @@ DatabaseBackup is the SQL Server Maintenance Solution’s stored procedure for b ## Download -Download [MaintenanceSolution.sql](/MaintenanceSolution.sql). This script creates all the objects and jobs that you need. You can also [download](https://ola.hallengren.com/downloads.html) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). +Download [MaintenanceSolution.sql](/MaintenanceSolution.sql). This script creates all the objects and jobs that you need. You can also [download](https://github.com/olahallengren/sql-server-maintenance-solution) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). ## License diff --git a/docs/sql-server-index-and-statistics-maintenance.md b/docs/sql-server-index-and-statistics-maintenance.md index 47b9b968..1349fd73 100644 --- a/docs/sql-server-index-and-statistics-maintenance.md +++ b/docs/sql-server-index-and-statistics-maintenance.md @@ -8,7 +8,7 @@ IndexOptimize is the SQL Server Maintenance Solution’s stored procedure for re ## Download -Download [MaintenanceSolution.sql](/MaintenanceSolution.sql). This script creates all the objects and jobs that you need. You can also [download](https://ola.hallengren.com/downloads.html) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). +Download [MaintenanceSolution.sql](/MaintenanceSolution.sql). This script creates all the objects and jobs that you need. You can also [download](https://github.com/olahallengren/sql-server-maintenance-solution) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). ## License diff --git a/docs/sql-server-integrity-check.md b/docs/sql-server-integrity-check.md index e6373c3e..4973a887 100644 --- a/docs/sql-server-integrity-check.md +++ b/docs/sql-server-integrity-check.md @@ -8,7 +8,7 @@ DatabaseIntegrityCheck is the SQL Server Maintenance Solution’s stored procedu ## Download -Download [MaintenanceSolution.sql](/MaintenanceSolution.sql). This script creates all the objects and jobs that you need. You can also [download](https://ola.hallengren.com/downloads.html) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). +Download [MaintenanceSolution.sql](/MaintenanceSolution.sql). This script creates all the objects and jobs that you need. You can also [download](https://github.com/olahallengren/sql-server-maintenance-solution) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). ## License From 99bee64d4f8c6c1211a20e7623f6e5c19b1db842 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 21:35:11 +0200 Subject: [PATCH 101/177] Add files via upload --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2b3c1854..4d0047f2 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ A copy of the stored procedure documentation is also available in this repositor [SQL Server bug badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/SQL%20Server%20Bug.svg [feature request badge]:https://img.shields.io/github/issues/olahallengren/sql-server-maintenance-solution/Feature%20Request.svg -[licence]:https://github.com/olahallengren/sql-server-maintenance-solution/blob/master/LICENSE +[licence]:/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 b43504876a6daa6783606ce682a69c6477463b25 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 22:05:06 +0200 Subject: [PATCH 102/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index 14941978..1729b75e 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -42,8 +42,8 @@ jobs: } # Two-phase upload. - # Phase 1 uploads ALL files under temporary names - the slow, interruptible part - while the live site stays completely untouched. - # Phase 2 renames the temp files into place, in order. + # Phase 1 uploads ALL files under temporary names. + # Phase 2 renames the temp files into place. UPLOAD="" for f in $FILES; do UPLOAD="$UPLOAD put $f -o $REMOTE_DIR/$f.tmp;" From 3843b77e77e8031c2c4e94c3921e352f6c9b9341 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 19 Jul 2026 22:31:44 +0200 Subject: [PATCH 103/177] Add files via upload --- docs/sql-server-backup.md | 24 +++++++++---------- ...server-index-and-statistics-maintenance.md | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/sql-server-backup.md b/docs/sql-server-backup.md index 1adea1aa..4fda75ee 100644 --- a/docs/sql-server-backup.md +++ b/docs/sql-server-backup.md @@ -41,10 +41,10 @@ Specify backup root directories, which can be local directories or network share | Value | Description | | --- | --- | | NULL | Back up to the SQL Server default backup directory. This is the default. | -| C:\Backup | Back up to the directory C:\Backup. | -| C:\Backup, D:\Backup | Back up to the directories C:\Backup and D:\Backup. | -| \\Server1\Backup | Back up to the network share \\Server1\Backup. | -| \\Server1\Backup, \\Server2\Backup | Back up to the network shares \\Server1\Backup and \\Server2\Backup. | +| C:\\Backup | Back up to the directory C:\\Backup. | +| C:\\Backup, D:\\Backup | Back up to the directories C:\\Backup and D:\\Backup. | +| \\\\Server1\\Backup | Back up to the network share \\\\Server1\\Backup. | +| \\\\Server1\\Backup, \\\\Server2\\Backup | Back up to the network shares \\\\Server1\\Backup and \\\\Server2\\Backup. | | NUL | Back up to NUL. | DatabaseBackup creates a directory structure with server name, instance name, database name, and backup type under the backup root directory. If the database is part of an availability group, then cluster name and availability group name are used instead of server name and instance name. @@ -455,9 +455,9 @@ You can use the following tokens: | MinorVersion | Minor version | | DirectorySeparator | The directory separator | -Default directory structure: {ServerName}${InstanceName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly} +Default directory structure: {ServerName}${InstanceName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}\_{Partial}\_{CopyOnly} -Tokens that do not apply will be removed. For example, the token {CopyOnly} (and the associated _) will be removed if it is not a copy-only backup. +Tokens that do not apply will be removed. For example, the token {CopyOnly} (and the associated \_) will be removed if it is not a copy-only backup. If the parameter is set to NULL, no sub-directories will be created. @@ -484,9 +484,9 @@ You can use the following tokens: | MinorVersion | Minor version | | DirectorySeparator | The directory separator | -Default directory structure: {ClusterName}${AvailabilityGroupName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}_{Partial}_{CopyOnly} +Default directory structure: {ClusterName}${AvailabilityGroupName}{DirectorySeparator}{DatabaseName}{DirectorySeparator}{BackupType}\_{Partial}\_{CopyOnly} -Tokens that do not apply will be removed. For example, the token {CopyOnly} (and the associated _) will be removed if it is not a copy-only backup. +Tokens that do not apply will be removed. For example, the token {CopyOnly} (and the associated \_) will be removed if it is not a copy-only backup. If the parameter is set to NULL, no sub-directories will be created. @@ -533,9 +533,9 @@ You can use the following tokens: | MajorVersion | Major version | | MinorVersion | Minor version | -Default file name: {ServerName}${InstanceName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension} +Default file name: {ServerName}${InstanceName}\_{DatabaseName}\_{BackupType}\_{Partial}\_{CopyOnly}\_{Year}{Month}{Day}\_{Hour}{Minute}{Second}\_{FileNumber}.{FileExtension} -Tokens that do not apply will be removed. For example, the token {CopyOnly} (and the associated _) will be removed if it is not a copy-only backup. +Tokens that do not apply will be removed. For example, the token {CopyOnly} (and the associated \_) will be removed if it is not a copy-only backup. ### AvailabilityGroupFileName @@ -572,9 +572,9 @@ You can use the following tokens: | MajorVersion | Major version | | MinorVersion | Minor version | -Default file name: {ClusterName}${AvailabilityGroupName}_{DatabaseName}_{BackupType}_{Partial}_{CopyOnly}_{Year}{Month}{Day}_{Hour}{Minute}{Second}_{FileNumber}.{FileExtension} +Default file name: {ClusterName}${AvailabilityGroupName}\_{DatabaseName}\_{BackupType}\_{Partial}\_{CopyOnly}\_{Year}{Month}{Day}\_{Hour}{Minute}{Second}\_{FileNumber}.{FileExtension} -Tokens that do not apply will be removed. For example, the token {CopyOnly} (and the associated _) will be removed if it is not a copy-only backup. +Tokens that do not apply will be removed. For example, the token {CopyOnly} (and the associated \_) will be removed if it is not a copy-only backup. ### FileNameCase diff --git a/docs/sql-server-index-and-statistics-maintenance.md b/docs/sql-server-index-and-statistics-maintenance.md index 1349fd73..fb0dd971 100644 --- a/docs/sql-server-index-and-statistics-maintenance.md +++ b/docs/sql-server-index-and-statistics-maintenance.md @@ -226,7 +226,7 @@ IndexOptimize checks modification_counter in [sys.dm_db_stats_properties](https: ### StatisticsModificationLevel -Specify a percentage of modified rows for when the statistics should be updated. Statistics will also be updated when the number of modified rows has reached a decreasing, dynamic threshold, SQRT(number of rows * 1000). +Specify a percentage of modified rows for when the statistics should be updated. Statistics will also be updated when the number of modified rows has reached a decreasing, dynamic threshold, SQRT(number of rows \* 1000). IndexOptimize checks the columns modification_counter and rows in [sys.dm_db_stats_properties](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-stats-properties-transact-sql). For incremental statistics it checks the columns modification_counter and rows in [sys.dm_db_incremental_stats_properties](https://learn.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-db-incremental-stats-properties-transact-sql). From f307ae1d85ad89e780534dd6b4be65cc51a50bf6 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 20 Jul 2026 14:05:51 +0200 Subject: [PATCH 104/177] Add files via upload --- README.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 4d0047f2..c0655fd6 100644 --- a/README.md +++ b/README.md @@ -31,13 +31,11 @@ Supported versions: SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Serve ## Documentation - - [SQL Server Backup](https://ola.hallengren.com/sql-server-backup.html) - - [SQL Server Integrity Check](https://ola.hallengren.com/sql-server-integrity-check.html) - - [SQL Server Index and Statistics Maintenance](https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html) - - [Frequently Asked Questions](https://ola.hallengren.com/frequently-asked-questions.html) - - [Version History](https://ola.hallengren.com/versions.html) - -A copy of the stored procedure documentation is also available in this repository: [docs](/docs). + - SQL Server Backup: [website](https://ola.hallengren.com/sql-server-backup.html) · [repository](/docs/sql-server-backup.md) + - SQL Server Integrity Check: [website](https://ola.hallengren.com/sql-server-integrity-check.html) · [repository](/docs/sql-server-integrity-check.md) + - SQL Server Index and Statistics Maintenance: [website](https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html) · [repository](/docs/sql-server-index-and-statistics-maintenance.md) + - Frequently Asked Questions: [website](https://ola.hallengren.com/frequently-asked-questions.html) + - Version History: [website](https://ola.hallengren.com/versions.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 From 37c4d0ea12c9371981fc80494b3e752b74c61ddb Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 20 Jul 2026 14:29:38 +0200 Subject: [PATCH 105/177] Add files via upload --- .github/workflows/create-tag.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/create-tag.yml b/.github/workflows/create-tag.yml index d5ac89d9..645b34fa 100644 --- a/.github/workflows/create-tag.yml +++ b/.github/workflows/create-tag.yml @@ -46,7 +46,11 @@ jobs: exit 0 fi - # 4. Create the tag on this commit and push it. - git tag "$TAG" + # 4. Create an annotated tag on this commit and push it. + # Annotated tags carry a tagger and date, so the runner needs a git identity. + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + + git tag -a "$TAG" -m "Version: $VERSION" git push origin "refs/tags/$TAG" echo "Created tag $TAG" From 92dd444b7f490b71376537376d4b6500ce15ef89 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 20 Jul 2026 15:06:19 +0200 Subject: [PATCH 106/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 4 +--- MaintenanceSolution.sql | 12 +++++------- 5 files changed, 9 insertions(+), 13 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 0b3e7d61..eb0e6ae4 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-19 18:23:28 //-- + --// Version: 2026-07-20 15:04:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 38f170ea..f5c8c29b 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 18:23:28 //-- + --// Version: 2026-07-20 15:04:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index d2f53e3b..d53da27b 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 18:23:28 //-- + --// Version: 2026-07-20 15:04:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index ca283c8b..3f57b3df 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 18:23:28 //-- + --// Version: 2026-07-20 15:04:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2232,7 +2232,6 @@ BEGIN IF ((@CurrentInRowDataPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (@CurrentInRowDataPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL)) OR @CurrentInRowDataPageCount IS NULL BEGIN - -- Does the index exist? IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) BEGIN @@ -2385,7 +2384,6 @@ BEGIN BEGIN SET @CurrentMaxDOP = 1 END - END -- Create index comment diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 95633293..4690314c 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: 2026-07-19 18:23:28 +Version: 2026-07-20 15:04:58 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 18:23:28 //-- + --// Version: 2026-07-20 15:04:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 18:23:28 //-- + --// Version: 2026-07-20 15:04:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4964,7 +4964,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 18:23:28 //-- + --// Version: 2026-07-20 15:04:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6975,7 +6975,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-19 18:23:28 //-- + --// Version: 2026-07-20 15:04:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -9151,7 +9151,6 @@ BEGIN IF ((@CurrentInRowDataPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (@CurrentInRowDataPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL)) OR @CurrentInRowDataPageCount IS NULL BEGIN - -- Does the index exist? IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) BEGIN @@ -9304,7 +9303,6 @@ BEGIN BEGIN SET @CurrentMaxDOP = 1 END - END -- Create index comment From cdedd32614878044b6cd2ad7dee1f5c8ffa8aba6 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 20 Jul 2026 15:20:54 +0200 Subject: [PATCH 107/177] Add files via upload --- .github/workflows/create-tag.yml | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/.github/workflows/create-tag.yml b/.github/workflows/create-tag.yml index 645b34fa..1bff6a7a 100644 --- a/.github/workflows/create-tag.yml +++ b/.github/workflows/create-tag.yml @@ -22,6 +22,8 @@ jobs: fetch-depth: 0 # full history so existing tags are visible - name: Read version from header and create tag + env: + GH_TOKEN: ${{ github.token }} run: | set -euo pipefail @@ -46,11 +48,18 @@ jobs: exit 0 fi - # 4. Create an annotated tag on this commit and push it. - # Annotated tags carry a tagger and date, so the runner needs a git identity. - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + # 4. Create an annotated tag on this commit through the API. + # Tag objects created server-side are signed by GitHub's web-flow key, + # so the tag shows as Verified (a runner-side "git tag" cannot sign). + TAG_SHA=$(gh api "repos/$GITHUB_REPOSITORY/git/tags" \ + -f tag="$TAG" \ + -f message="Version: $VERSION" \ + -f object="$GITHUB_SHA" \ + -f type="commit" \ + --jq .sha) + + gh api "repos/$GITHUB_REPOSITORY/git/refs" \ + -f ref="refs/tags/$TAG" \ + -f sha="$TAG_SHA" - git tag -a "$TAG" -m "Version: $VERSION" - git push origin "refs/tags/$TAG" echo "Created tag $TAG" From ccf3599ededd5dba58c4048824c77c21efbe7371 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 20 Jul 2026 15:23:32 +0200 Subject: [PATCH 108/177] Update create-tag.yml --- .github/workflows/create-tag.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.github/workflows/create-tag.yml b/.github/workflows/create-tag.yml index 1bff6a7a..f83e1f2c 100644 --- a/.github/workflows/create-tag.yml +++ b/.github/workflows/create-tag.yml @@ -49,8 +49,6 @@ jobs: fi # 4. Create an annotated tag on this commit through the API. - # Tag objects created server-side are signed by GitHub's web-flow key, - # so the tag shows as Verified (a runner-side "git tag" cannot sign). TAG_SHA=$(gh api "repos/$GITHUB_REPOSITORY/git/tags" \ -f tag="$TAG" \ -f message="Version: $VERSION" \ From 8374563c586891cd5839ef100e5e113fadafb013 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 20 Jul 2026 15:33:44 +0200 Subject: [PATCH 109/177] 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 eb0e6ae4..dc90362f 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-20 15:04:58 //-- + --// Version: 2026-07-20 15:32:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index f5c8c29b..008d2c87 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 15:04:58 //-- + --// Version: 2026-07-20 15:32:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1410,19 +1410,19 @@ BEGIN IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.', 16, 4) + VALUES('Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/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, [State]) - VALUES('Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.', 16, 5) + VALUES('Idera SQL Safe Backup is not installed. Download https://www.idera.com/products/sql-safe-backup/.', 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, [State]) - VALUES('EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.', 16, 6) + VALUES('EMC Data Domain Boost is not installed. Download https://www.dell.com/en-us/shop/storage-servers-and-networking-for-business/sf/powerprotect-data-domain.', 16, 6) END ---------------------------------------------------------------------------------------------------- diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index d53da27b..d1fd8d73 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 15:04:58 //-- + --// Version: 2026-07-20 15:32:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 3f57b3df..cfa8f3cf 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 15:04:58 //-- + --// Version: 2026-07-20 15:32:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 4690314c..c929de11 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: 2026-07-20 15:04:58 +Version: 2026-07-20 15:32:25 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 15:04:58 //-- + --// Version: 2026-07-20 15:32:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 15:04:58 //-- + --// Version: 2026-07-20 15:32:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1809,19 +1809,19 @@ BEGIN IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/dba/sql-backup/.', 16, 4) + VALUES('Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/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, [State]) - VALUES('Idera SQL Safe Backup is not installed. Download https://www.idera.com/productssolutions/sqlserver/sqlsafebackup.', 16, 5) + VALUES('Idera SQL Safe Backup is not installed. Download https://www.idera.com/products/sql-safe-backup/.', 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, [State]) - VALUES('EMC Data Domain Boost is not installed. Download https://www.emc.com/en-us/data-protection/data-domain.htm.', 16, 6) + VALUES('EMC Data Domain Boost is not installed. Download https://www.dell.com/en-us/shop/storage-servers-and-networking-for-business/sf/powerprotect-data-domain.', 16, 6) END ---------------------------------------------------------------------------------------------------- @@ -4964,7 +4964,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 15:04:58 //-- + --// Version: 2026-07-20 15:32:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6975,7 +6975,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 15:04:58 //-- + --// Version: 2026-07-20 15:32:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 6460688515b6552d089464a854e8481c36ed5ee5 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 20 Jul 2026 15:45:47 +0200 Subject: [PATCH 110/177] Update create-tag.yml --- .github/workflows/create-tag.yml | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/.github/workflows/create-tag.yml b/.github/workflows/create-tag.yml index f83e1f2c..645b34fa 100644 --- a/.github/workflows/create-tag.yml +++ b/.github/workflows/create-tag.yml @@ -22,8 +22,6 @@ jobs: fetch-depth: 0 # full history so existing tags are visible - name: Read version from header and create tag - env: - GH_TOKEN: ${{ github.token }} run: | set -euo pipefail @@ -48,16 +46,11 @@ jobs: exit 0 fi - # 4. Create an annotated tag on this commit through the API. - TAG_SHA=$(gh api "repos/$GITHUB_REPOSITORY/git/tags" \ - -f tag="$TAG" \ - -f message="Version: $VERSION" \ - -f object="$GITHUB_SHA" \ - -f type="commit" \ - --jq .sha) - - gh api "repos/$GITHUB_REPOSITORY/git/refs" \ - -f ref="refs/tags/$TAG" \ - -f sha="$TAG_SHA" + # 4. Create an annotated tag on this commit and push it. + # Annotated tags carry a tagger and date, so the runner needs a git identity. + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git tag -a "$TAG" -m "Version: $VERSION" + git push origin "refs/tags/$TAG" echo "Created tag $TAG" From 5be56bdf43bb234f6d7066ce186a4f12e79d0bbd Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 20 Jul 2026 16:10:27 +0200 Subject: [PATCH 111/177] 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 dc90362f..831efc38 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-20 15:32:25 //-- + --// Version: 2026-07-20 16:09:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 008d2c87..cecdf2f1 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 15:32:25 //-- + --// Version: 2026-07-20 16:09:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1456,7 +1456,7 @@ BEGIN IF @BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('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) + VALUES('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' @@ -1508,7 +1508,7 @@ BEGIN IF @MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('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) + VALUES('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' @@ -1546,7 +1546,7 @@ BEGIN IF @URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('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) + VALUES('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) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index d1fd8d73..3841c51f 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 15:32:25 //-- + --// Version: 2026-07-20 16:09:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index cfa8f3cf..98b2f24f 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 15:32:25 //-- + --// Version: 2026-07-20 16:09:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index c929de11..428749f2 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: 2026-07-20 15:32:25 +Version: 2026-07-20 16:09:48 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 15:32:25 //-- + --// Version: 2026-07-20 16:09:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 15:32:25 //-- + --// Version: 2026-07-20 16:09:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1855,7 +1855,7 @@ BEGIN IF @BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('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) + VALUES('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' @@ -1907,7 +1907,7 @@ BEGIN IF @MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('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) + VALUES('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' @@ -1945,7 +1945,7 @@ BEGIN IF @URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('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) + VALUES('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) @@ -4964,7 +4964,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 15:32:25 //-- + --// Version: 2026-07-20 16:09:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6975,7 +6975,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 15:32:25 //-- + --// Version: 2026-07-20 16:09:48 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON From 82c5ca39c4a39ad65272c0be5cc556f23b367478 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 20 Jul 2026 19:21:31 +0200 Subject: [PATCH 112/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index 1729b75e..6de78bfe 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -35,7 +35,7 @@ jobs: FILES="CommandLog.sql Queue.sql QueueDatabase.sql CommandExecute.sql DatabaseBackup.sql DatabaseIntegrityCheck.sql IndexOptimize.sql MaintenanceSolution.sql" # Explicit FTPS (AUTH TLS) on port 21 - SETTINGS="set ftp:ssl-force true; set ftp:ssl-protect-data true; set ssl:verify-certificate false; set net:max-retries 2; set net:timeout 60" + SETTINGS="set ftp:ssl-force true; set ftp:ssl-protect-data true; set ssl:verify-certificate true; set net:max-retries 2; set net:timeout 60" run_lftp () { lftp -p 21 -u "$FTP_USERNAME,$FTP_PASSWORD" -e "$SETTINGS; $1; bye" "$FTP_SERVER" From 53b7d9779f25204ccb9ae07097d82e4fe00ca838 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 21 Jul 2026 11:26:33 +0200 Subject: [PATCH 113/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 4 +- MaintenanceSolution.sql | 14 +- MaintenanceSolutionAzureSQLDatabase.sql | 5292 +++++++++++++++++++++++ SHA256SUMS.txt | 9 + 7 files changed, 5313 insertions(+), 12 deletions(-) create mode 100644 MaintenanceSolutionAzureSQLDatabase.sql create mode 100644 SHA256SUMS.txt diff --git a/CommandExecute.sql b/CommandExecute.sql index 831efc38..6176097c 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-20 16:09:48 //-- + --// Version: 2026-07-21 11:25:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index cecdf2f1..901c39c5 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 16:09:48 //-- + --// Version: 2026-07-21 11:25:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 3841c51f..85d3427a 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 16:09:48 //-- + --// Version: 2026-07-21 11:25:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 98b2f24f..c6cf0477 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 16:09:48 //-- + --// Version: 2026-07-21 11:25:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2761,7 +2761,7 @@ BEGIN IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @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 diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 428749f2..409510b3 100644 --- a/MaintenanceSolution.sql +++ b/MaintenanceSolution.sql @@ -1,6 +1,6 @@ /* -SQL Server Maintenance Solution - SQL Server 2017, SQL Server 2019, SQL Server 2022, and SQL Server 2025 +SQL Server Maintenance Solution - SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, and Azure SQL Managed Instance 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: 2026-07-20 16:09:48 +Version: 2026-07-21 11:25:14 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 16:09:48 //-- + --// Version: 2026-07-21 11:25:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 16:09:48 //-- + --// Version: 2026-07-21 11:25:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4964,7 +4964,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 16:09:48 //-- + --// Version: 2026-07-21 11:25:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6975,7 +6975,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-20 16:09:48 //-- + --// Version: 2026-07-21 11:25:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -9680,7 +9680,7 @@ BEGIN IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @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 diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql new file mode 100644 index 00000000..ab4c4f38 --- /dev/null +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -0,0 +1,5292 @@ +/* + +SQL Server Maintenance Solution - Azure SQL Database + +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 + +License: https://ola.hallengren.com/license.html + +GitHub: https://github.com/olahallengren/sql-server-maintenance-solution + +Version: 2026-07-21 11:25:14 + +You can contact me by e-mail at ola@hallengren.com. + +Ola Hallengren +https://ola.hallengren.com + +*/ + +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, + [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] [datetime2](7) NOT NULL, + [EndTime] [datetime2](7) 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 +SET ANSI_NULLS ON +GO +SET QUOTED_IDENTIFIER ON +GO +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] + +@DatabaseContext nvarchar(max), +@Command nvarchar(max), +@CommandType nvarchar(max), +@Mode int, +@Comment nvarchar(max) = NULL, +@DatabaseName nvarchar(max) = NULL, +@SchemaName nvarchar(max) = NULL, +@ObjectName nvarchar(max) = NULL, +@ObjectType nvarchar(max) = NULL, +@IndexName nvarchar(max) = NULL, +@IndexType int = NULL, +@StatisticsName nvarchar(max) = NULL, +@PartitionNumber int = NULL, +@EncryptionKey nvarchar(max) = NULL, +@EncryptionKeyPlaceholder nvarchar(max) = NULL, +@ExtendedInfo xml = NULL, +@LockMessageSeverity int = 16, +@ExecuteAsUser nvarchar(max) = NULL, +@LogToTable nvarchar(max), +@Execute nvarchar(max) + +AS + +BEGIN + + ---------------------------------------------------------------------------------------------------- + --// Source: https://ola.hallengren.com //-- + --// License: https://ola.hallengren.com/license.html //-- + --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- + --// Version: 2026-07-21 11:25:14 //-- + ---------------------------------------------------------------------------------------------------- + + SET NOCOUNT ON + + DECLARE @StartMessage nvarchar(max) + DECLARE @EndMessage nvarchar(max) + DECLARE @ErrorMessage nvarchar(max) + DECLARE @ErrorMessageOriginal nvarchar(max) + DECLARE @Severity int + + DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, + [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' + + DECLARE @StartTime datetime2 + DECLARE @EndTime datetime2 + + DECLARE @ID int + + DECLARE @Error int = 0 + DECLARE @ReturnCode int = 0 + + DECLARE @EmptyLine nvarchar(max) = CHAR(9) + + DECLARE @RevertCommand nvarchar(max) + + DECLARE @CommandMasked nvarchar(max) + + ---------------------------------------------------------------------------------------------------- + --// Check core requirements //-- + ---------------------------------------------------------------------------------------------------- + + IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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, [State]) + VALUES('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], Severity, [State]) + VALUES('The table CommandLog is missing. Download https://ola.hallengren.com/scripts/CommandLog.sql.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + --// Check input parameters //-- + ---------------------------------------------------------------------------------------------------- + + IF @DatabaseContext IS NULL OR NOT EXISTS (SELECT * FROM sys.databases WHERE name = @DatabaseContext) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @DatabaseContext is not supported.', 16, 1) + END + + IF @Command IS NULL OR @Command = '' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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], Severity, [State]) + VALUES('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], Severity, [State]) + VALUES('The value for the parameter @Mode is not supported.', 16, 1) + END + + IF (@EncryptionKey IS NULL AND @EncryptionKeyPlaceholder IS NOT NULL) OR (@EncryptionKey IS NOT NULL AND @EncryptionKeyPlaceholder IS NULL) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameters @EncryptionKey and @EncryptionKeyPlaceholder must be specified together.', 16, 1) + END + + IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) + END + + IF LEN(@ExecuteAsUser) > 128 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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]) + VALUES('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, [State]) + VALUES('The value for the parameter @Execute is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + --// Raise errors //-- + ---------------------------------------------------------------------------------------------------- + + DECLARE ErrorCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC + + OPEN ErrorCursor + + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState + + WHILE @@FETCH_STATUS = 0 + BEGIN + RAISERROR('%s', @CurrentSeverity, @CurrentState, @CurrentMessage) WITH NOWAIT + RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT + + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState + END + + CLOSE ErrorCursor + + DEALLOCATE ErrorCursor + + IF EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) + BEGIN + SET @ReturnCode = 50000 + GOTO ReturnCode + END + + ---------------------------------------------------------------------------------------------------- + --// Execute as user //-- + ---------------------------------------------------------------------------------------------------- + + IF @ExecuteAsUser IS NOT NULL + BEGIN + SET @Command = 'EXECUTE AS USER = ''' + REPLACE(@ExecuteAsUser,'''','''''') + '''; ' + @Command + '; REVERT;' + + SET @RevertCommand = 'REVERT' + END + + ---------------------------------------------------------------------------------------------------- + --// Mask encryption key //-- + ---------------------------------------------------------------------------------------------------- + + SET @CommandMasked = CASE WHEN @EncryptionKeyPlaceholder IS NULL THEN @Command ELSE REPLACE(@Command,@EncryptionKeyPlaceholder,'********') END + + SET @Command = CASE WHEN @EncryptionKeyPlaceholder IS NULL THEN @Command ELSE REPLACE(@Command,@EncryptionKeyPlaceholder,REPLACE(ISNULL(@EncryptionKey,''),'''','''''')) END + + ---------------------------------------------------------------------------------------------------- + --// Log initial information //-- + ---------------------------------------------------------------------------------------------------- + + SET @StartTime = SYSDATETIME() + + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'Database context: ' + QUOTENAME(@DatabaseContext) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'Command: ' + @CommandMasked + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + IF @Comment IS NOT NULL + BEGIN + SET @StartMessage = 'Comment: ' + @Comment + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + + IF @LogToTable = 'Y' + BEGIN + INSERT INTO dbo.CommandLog (DatabaseName, SchemaName, ObjectName, ObjectType, IndexName, IndexType, StatisticsName, PartitionNumber, ExtendedInfo, CommandType, Command, StartTime) + VALUES (@DatabaseName, @SchemaName, @ObjectName, @ObjectType, @IndexName, @IndexType, @StatisticsName, @PartitionNumber, @ExtendedInfo, @CommandType, @CommandMasked, @StartTime) + + SET @ID = SCOPE_IDENTITY() + END + + ---------------------------------------------------------------------------------------------------- + --// Execute command //-- + ---------------------------------------------------------------------------------------------------- + + IF @Mode = 1 AND @Execute = 'Y' + BEGIN + EXECUTE @sp_executesql @stmt = @Command + SET @Error = @@ERROR + SET @ReturnCode = @Error + END + + IF @Mode = 2 AND @Execute = 'Y' + BEGIN + BEGIN TRY + EXECUTE @sp_executesql @stmt = @Command + END TRY + BEGIN CATCH + SET @Error = ERROR_NUMBER() + SET @ErrorMessageOriginal = ERROR_MESSAGE() + + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') + SET @Severity = CASE WHEN ERROR_NUMBER() IN(1205, 1222, 5245) THEN @LockMessageSeverity ELSE ERROR_SEVERITY() END + RAISERROR('%s',@Severity,1,@ErrorMessage) WITH NOWAIT + + IF NOT (ERROR_NUMBER() IN(1205, 1222, 5245) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END + + IF @ExecuteAsUser IS NOT NULL + BEGIN + EXECUTE @sp_executesql @RevertCommand + END + END CATCH + END + + ---------------------------------------------------------------------------------------------------- + --// Log completing information //-- + ---------------------------------------------------------------------------------------------------- + + 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(SECOND,@StartTime,@EndTime) / (24 * 3600)) > 0 THEN CAST((DATEDIFF(SECOND,@StartTime,@EndTime) / (24 * 3600)) AS nvarchar(max)) + '.' ELSE '' END + CONVERT(nvarchar(max),DATEADD(SECOND,DATEDIFF(SECOND,@StartTime,@EndTime),'1900-01-01'),108) + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT + + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar(max),@EndTime,120) + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT + + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + IF @LogToTable = 'Y' + BEGIN + UPDATE dbo.CommandLog + SET EndTime = @EndTime, + ErrorNumber = CASE WHEN @Execute = 'N' THEN NULL ELSE @Error END, + ErrorMessage = @ErrorMessageOriginal + WHERE ID = @ID + END + + ReturnCode: + IF @ReturnCode <> 0 + BEGIN + RETURN @ReturnCode + END + + ---------------------------------------------------------------------------------------------------- + +END +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].[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', +@PhysicalOnly nvarchar(max) = 'N', +@DataPurity nvarchar(max) = 'N', +@NoIndex nvarchar(max) = 'N', +@ExtendedLogicalChecks nvarchar(max) = 'N', +@NoInformationalMessages nvarchar(max) = 'N', +@TabLock nvarchar(max) = 'N', +@FileGroups nvarchar(max) = NULL, +@Objects nvarchar(max) = NULL, +@MaxDOP int = NULL, +@AvailabilityGroups nvarchar(max) = NULL, +@AvailabilityGroupReplicas nvarchar(max) = 'ALL', +@Updateability nvarchar(max) = 'ALL', +@TimeLimit int = NULL, +@LockTimeout int = NULL, +@LockMessageSeverity int = 16, +@StringDelimiter nvarchar(max) = ',', +@DatabaseOrder nvarchar(max) = NULL, +@DatabasesInParallel nvarchar(max) = 'N', +@LogToTable nvarchar(max) = 'N', +@Execute nvarchar(max) = 'Y' + +AS + +BEGIN + + ---------------------------------------------------------------------------------------------------- + --// Source: https://ola.hallengren.com //-- + --// License: https://ola.hallengren.com/license.html //-- + --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- + --// Version: 2026-07-21 11:25:14 //-- + ---------------------------------------------------------------------------------------------------- + + SET NOCOUNT ON + + DECLARE @StartMessage nvarchar(max) + DECLARE @EndMessage nvarchar(max) + DECLARE @DatabaseMessage nvarchar(max) + DECLARE @ErrorMessage nvarchar(max) + DECLARE @Severity int + + 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 TABLE (ID int IDENTITY PRIMARY KEY, + [Name] nvarchar(max) NOT NULL, + ValueNvarchar nvarchar(max), + ValueInt int, + ValueDatetime datetime2) + + DECLARE @ParametersString nvarchar(max) + DECLARE @CurrentParameterName nvarchar(max) + DECLARE @CurrentParameterValueNvarchar nvarchar(max) + DECLARE @CurrentParameterValueInt int + DECLARE @CurrentParameterValueDatetime datetime2 + DECLARE @CurrentParameterDelimiter nvarchar(max) + DECLARE @CurrentParameterMessage nvarchar(max) + + DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 + + DECLARE @QueueID int + DECLARE @QueueStartTime datetime2 + + DECLARE @CurrentDBID int + DECLARE @CurrentDatabaseName nvarchar(max) + + DECLARE @CurrentDatabase_sp_executesql nvarchar(max) + + DECLARE @CurrentUserAccess nvarchar(max) + DECLARE @CurrentIsReadOnly bit + DECLARE @CurrentDatabaseState nvarchar(max) + DECLARE @CurrentInStandby bit + DECLARE @CurrentRecoveryModel nvarchar(max) + + DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier + DECLARE @CurrentAvailabilityGroupID uniqueidentifier + DECLARE @CurrentAvailabilityGroup nvarchar(max) + DECLARE @CurrentAvailabilityGroupRole nvarchar(max) + DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) + DECLARE @CurrentSecondaryRoleAllowConnections nvarchar(max) + DECLARE @CurrentIsPreferredBackupReplica bit + DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) + DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier + DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) + DECLARE @CurrentDatabaseMirroringRole nvarchar(max) + + DECLARE @CurrentFGID int + DECLARE @CurrentFileGroupID int + DECLARE @CurrentFileGroupName nvarchar(max) + DECLARE @CurrentFileGroupExists bit + + DECLARE @CurrentOID int + DECLARE @CurrentSchemaID int + DECLARE @CurrentSchemaName nvarchar(max) + DECLARE @CurrentObjectID int + DECLARE @CurrentObjectName nvarchar(max) + DECLARE @CurrentObjectType nvarchar(max) + DECLARE @CurrentObjectExists bit + + 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) 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(128), + DatabaseType nvarchar(1), + AvailabilityGroup bit, + [Snapshot] bit, + StartPosition int, + LastCommandTime datetime2, + DatabaseSize bigint, + LastGoodCheckDbTime datetime2, + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) + + DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, + AvailabilityGroupName nvarchar(128), + StartPosition int, + Selected bit DEFAULT 0) + + DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(128), + AvailabilityGroupName nvarchar(128)) + + DECLARE @tmpFileGroups TABLE (ID int IDENTITY, + FileGroupID int, + FileGroupName nvarchar(128), + StartPosition int, + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) + + DECLARE @tmpObjects TABLE (ID int IDENTITY, + SchemaID int, + SchemaName nvarchar(128), + ObjectID int, + ObjectName nvarchar(128), + ObjectType nvarchar(2), + StartPosition int, + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) + + DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), + DatabaseType nvarchar(1), + AvailabilityGroup bit, + 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)) + + DECLARE @Error int = 0 + DECLARE @ReturnCode int = 0 + + DECLARE @EmptyLine nvarchar(max) = CHAR(9) + + DECLARE @ProductVersion nvarchar(max) = CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + DECLARE @ProductUpdateType nvarchar(max) = CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + DECLARE @EngineEdition int = CAST(SERVERPROPERTY('EngineEdition') AS int) + DECLARE @Edition nvarchar(max) = CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + DECLARE @IsHadrEnabled bit = CAST(SERVERPROPERTY('IsHadrEnabled') AS bit) + DECLARE @IsClustered bit = CAST(SERVERPROPERTY('IsClustered') AS bit) + DECLARE @ServerName nvarchar(max) = CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + + DECLARE @Version numeric(18,10) = CAST(PARSENAME(@ProductVersion,4) + '.' + PARSENAME(@ProductVersion,3) + PARSENAME(@ProductVersion,2) AS numeric(18,10)) + + IF @EngineEdition = 8 AND @ProductVersion = '12.0.2000.8' AND @ProductUpdateType = 'CU' + BEGIN + SET @Version = 16.01000 + END + + IF @EngineEdition <> 5 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END + + IF @EngineEdition <> 5 + BEGIN + IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) + BEGIN + SET @ContainedAvailabilityGroupListenerConnection = 1 + END + END + + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + + ---------------------------------------------------------------------------------------------------- + --// Log initial information //-- + ---------------------------------------------------------------------------------------------------- + + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Databases', @Databases) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@CheckCommands', @CheckCommands) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@PhysicalOnly', @PhysicalOnly) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataPurity', @DataPurity) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@NoIndex', @NoIndex) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ExtendedLogicalChecks', @ExtendedLogicalChecks) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@NoInformationalMessages', @NoInformationalMessages) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@TabLock', @TabLock) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FileGroups', @FileGroups) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Objects', @Objects) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MaxDOP', @MaxDOP) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroups', @AvailabilityGroups) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroupReplicas', @AvailabilityGroupReplicas) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Updateability', @Updateability) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@TimeLimit', @TimeLimit) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@LockTimeout', @LockTimeout) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@LockMessageSeverity', @LockMessageSeverity) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@StringDelimiter', @StringDelimiter) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabaseOrder', @DatabaseOrder) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabasesInParallel', @DatabasesInParallel) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@LogToTable', @LogToTable) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Execute', @Execute) + + SELECT @ParametersString = STRING_AGG(CAST([Name] + ' = ' + CASE WHEN ValueNvarchar IS NOT NULL THEN '''' + REPLACE(ValueNvarchar,'''','''''') + '''' WHEN ValueInt IS NOT NULL THEN CAST(ValueInt AS nvarchar(max)) WHEN ValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), ValueDatetime, 21) + '''' ELSE 'NULL' END AS nvarchar(max)), ', ') WITHIN GROUP (ORDER BY [ID] ASC) + FROM @Parameters + + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'Server: ' + @ServerName + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'Version: ' + @ProductVersion + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'Edition: ' + @Edition + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + IF @EngineEdition = 8 + BEGIN + SET @StartMessage = 'Update type: ' + @ProductUpdateType + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + + IF @EngineEdition <> 5 + BEGIN + SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + + IF @EngineEdition <> 5 + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'Procedure: ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'Version: ' + @VersionTimestamp + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'Source: https://ola.hallengren.com' + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + SET @StartMessage = 'Command:' + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'EXECUTE ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + DECLARE ParameterCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Name], ValueNvarchar, ValueInt, ValueDatetime, CASE WHEN [ID] = MAX([ID]) OVER() THEN '' ELSE ',' END FROM @Parameters ORDER BY [ID] ASC + + OPEN ParameterCursor + + FETCH ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + + WHILE @@FETCH_STATUS = 0 + BEGIN + SET @CurrentParameterMessage = @CurrentParameterName + ' = ' + CASE WHEN @CurrentParameterValueNvarchar IS NOT NULL THEN '''' + REPLACE(@CurrentParameterValueNvarchar,'''','''''') + '''' WHEN @CurrentParameterValueInt IS NOT NULL THEN CAST(@CurrentParameterValueInt AS nvarchar(max)) WHEN @CurrentParameterValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), @CurrentParameterValueDatetime, 21) + '''' ELSE 'NULL' END + @CurrentParameterDelimiter + + RAISERROR('%s',10,1,@CurrentParameterMessage) WITH NOWAIT + + FETCH NEXT FROM ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + END + + CLOSE ParameterCursor + + DEALLOCATE ParameterCursor + + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + ---------------------------------------------------------------------------------------------------- + --// Check core requirements //-- + ---------------------------------------------------------------------------------------------------- + + IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('The transaction count is not 0.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + --// Select databases //-- + ---------------------------------------------------------------------------------------------------- + + SET @Databases = REPLACE(@Databases, CHAR(10), '') + SET @Databases = REPLACE(@Databases, CHAR(13), '') + + 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(@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(@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 + ), + 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, 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, 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, StartPosition, Selected) + SELECT DatabaseName, + DatabaseType, + AvailabilityGroup, + StartPosition, + Selected + FROM Databases4 + OPTION (MAXRECURSION 0) + + IF @IsHadrEnabled = 1 + BEGIN + INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName) + SELECT name AS AvailabilityGroupName + FROM sys.availability_groups + + INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) + SELECT databases.name, + availability_groups.name + FROM sys.databases databases + 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]) + SELECT [name] AS DatabaseName, + 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] + 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 + INNER JOIN @SelectedDatabases SelectedDatabases + ON tmpDatabases.DatabaseName LIKE REPLACE(REPLACE(SelectedDatabases.DatabaseName,'[','[[]'),'_','[_]') + AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL) + AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) + AND NOT ((tmpDatabases.DatabaseName = 'tempdb' OR tmpDatabases.[Snapshot] = 1) AND tmpDatabases.DatabaseName <> SelectedDatabases.DatabaseName) + WHERE SelectedDatabases.Selected = 1 + + UPDATE tmpDatabases + SET tmpDatabases.Selected = SelectedDatabases.Selected + FROM @tmpDatabases tmpDatabases + INNER JOIN @SelectedDatabases SelectedDatabases + ON tmpDatabases.DatabaseName LIKE REPLACE(REPLACE(SelectedDatabases.DatabaseName,'[','[[]'),'_','[_]') + AND (tmpDatabases.DatabaseType = SelectedDatabases.DatabaseType OR SelectedDatabases.DatabaseType IS NULL) + AND (tmpDatabases.AvailabilityGroup = SelectedDatabases.AvailabilityGroup OR SelectedDatabases.AvailabilityGroup IS NULL) + 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(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 DATALENGTH(DatabaseName) = 0)) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @Databases is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + --// Select availability groups //-- + ---------------------------------------------------------------------------------------------------- + + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 1 + BEGIN + + SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') + SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(13), '') + + 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(@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(@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 + ), + 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, StartPosition, Selected) AS + ( + SELECT CASE WHEN AvailabilityGroupItem = 'ALL_AVAILABILITY_GROUPS' THEN '%' ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, + Selected + FROM AvailabilityGroups2 + ), + 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, StartPosition, Selected) + SELECT AvailabilityGroupName, StartPosition, Selected + FROM AvailabilityGroups4 + OPTION (MAXRECURSION 0) + + UPDATE tmpAvailabilityGroups + SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') + WHERE SelectedAvailabilityGroups.Selected = 1 + + UPDATE tmpAvailabilityGroups + SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(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(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') + WHERE SelectedAvailabilityGroups.Selected = 1 + GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2 + ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName + + UPDATE tmpDatabases + 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 + WHERE tmpAvailabilityGroups.Selected = 1 + + END + + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @IsHadrEnabled = 0) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) + END + + ---------------------------------------------------------------------------------------------------- + --// Select filegroups //-- + ---------------------------------------------------------------------------------------------------- + + SET @FileGroups = REPLACE(@FileGroups, CHAR(10), '') + SET @FileGroups = REPLACE(@FileGroups, CHAR(13), '') + + 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(@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(@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 + ), + 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, StartPosition, Selected) AS + ( + SELECT CASE WHEN FileGroupItem = 'ALL_FILEGROUPS' THEN '%.%' ELSE FileGroupItem END AS FileGroupItem, + StartPosition, + Selected + FROM FileGroups2 + ), + 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, StartPosition, Selected) + SELECT DatabaseName, FileGroupName, StartPosition, Selected + FROM FileGroups4 + OPTION (MAXRECURSION 0) + + ---------------------------------------------------------------------------------------------------- + --// Select objects //-- + ---------------------------------------------------------------------------------------------------- + + SET @Objects = REPLACE(@Objects, CHAR(10), '') + SET @Objects = REPLACE(@Objects, CHAR(13), '') + + 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(@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(@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 + ), + 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, StartPosition, Selected) AS + ( + SELECT CASE WHEN ObjectItem = 'ALL_OBJECTS' THEN '%.%.%' ELSE ObjectItem END AS ObjectItem, + StartPosition, + Selected + FROM Objects2 + ), + 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, StartPosition, Selected) + SELECT DatabaseName, SchemaName, ObjectName, StartPosition, Selected + FROM Objects4 + OPTION (MAXRECURSION 0) + + ---------------------------------------------------------------------------------------------------- + --// Select check commands //-- + ---------------------------------------------------------------------------------------------------- + + SET @CheckCommands = REPLACE(@CheckCommands, @StringDelimiter + ' ', @StringDelimiter); + + WITH CheckCommands (StartPosition, EndPosition, CheckCommand) AS + ( + SELECT 1 AS StartPosition, + 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(@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 + ) + INSERT INTO @SelectedCheckCommands (CheckCommand) + SELECT CheckCommand + FROM CheckCommands + OPTION (MAXRECURSION 0) + + ---------------------------------------------------------------------------------------------------- + --// Check input parameters //-- + ---------------------------------------------------------------------------------------------------- + + IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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]) + VALUES('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]) + VALUES('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]) + VALUES('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]) + VALUES('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, [State]) + VALUES('The value for the parameter @PhysicalOnly is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @DataPurity NOT IN ('Y','N') OR @DataPurity IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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]) + VALUES('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]) + VALUES('The value for the parameter @NoIndex is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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]) + VALUES('The parameters @PhysicalOnly and @ExtendedLogicalChecks cannot be used together.', 16, 2) + END + + ---------------------------------------------------------------------------------------------------- + + IF @NoInformationalMessages NOT IN ('Y','N') OR @NoInformationalMessages IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @NoInformationalMessages is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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]) + VALUES('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]) + VALUES('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) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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]) + VALUES('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]) + VALUES('The value for the parameter @Objects is not supported.', 16, 3) + END + + ---------------------------------------------------------------------------------------------------- + + IF @MaxDOP < 0 OR @MaxDOP > 64 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxDOP is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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, [State]) + VALUES('The value for the parameter @Updateability is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @TimeLimit < 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @TimeLimit is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @LockTimeout < 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @LockTimeout is not supported.', 16, 1) + END + + IF @LockTimeout > 86400 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @LockTimeout is not supported.', 16, 2) + END + + ---------------------------------------------------------------------------------------------------- + + IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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, [State]) + VALUES('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') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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 >= 14.03029 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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]) + VALUES('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]) + VALUES('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 @EngineEdition = 5 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) + END + + IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('The value for the parameter @Execute is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF EXISTS(SELECT * FROM @Errors) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + --// Check that selected databases and availability groups exist //-- + ---------------------------------------------------------------------------------------------------- + + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) + FROM @SelectedDatabases + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + + IF @ErrorMessage IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + END + + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) + FROM @SelectedFileGroups + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + + IF @ErrorMessage IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The following databases in the @FileGroups parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + END + + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) + FROM @SelectedObjects + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + + IF @ErrorMessage IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The following databases in the @Objects parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + END + + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY AvailabilityGroupName ASC) + FROM @SelectedAvailabilityGroups + WHERE AvailabilityGroupName NOT LIKE '%[%]%' + AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) + + IF @ErrorMessage IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) + END + + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) + 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 @ErrorMessage IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) + END + + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) + 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 @ErrorMessage IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) + END + + ---------------------------------------------------------------------------------------------------- + --// Check @@SERVERNAME //-- + ---------------------------------------------------------------------------------------------------- + + IF UPPER(@@SERVERNAME) <> UPPER(@ServerName) AND @IsHadrEnabled = 1 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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 LOCAL FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC + + OPEN ErrorCursor + + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState + + WHILE @@FETCH_STATUS = 0 + BEGIN + RAISERROR('%s', @CurrentSeverity, @CurrentState, @CurrentMessage) WITH NOWAIT + RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT + + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState + END + + CLOSE ErrorCursor + + DEALLOCATE ErrorCursor + + IF EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) + BEGIN + SET @ReturnCode = 50000 + GOTO Logging + END + + ---------------------------------------------------------------------------------------------------- + --// Update database order //-- + ---------------------------------------------------------------------------------------------------- + + IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + BEGIN + UPDATE tmpDatabases + 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 + + IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') + BEGIN + UPDATE tmpDatabases + SET LastGoodCheckDbTime = NULLIF(CAST(DATABASEPROPERTYEX (DatabaseName,'LastGoodCheckDbTime') AS datetime2),'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 + 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 COLLATE DATABASE_DEFAULT + 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 + + ---------------------------------------------------------------------------------------------------- + --// Update the queue //-- + ---------------------------------------------------------------------------------------------------- + + IF @DatabasesInParallel = 'Y' + BEGIN + + BEGIN TRY + + SELECT @QueueID = QueueID + FROM dbo.[Queue] + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @ParametersString + + IF @QueueID IS NULL + BEGIN + BEGIN TRANSACTION + + SELECT @QueueID = QueueID + FROM dbo.[Queue] WITH (UPDLOCK, HOLDLOCK) + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @ParametersString + + IF @QueueID IS NULL + BEGIN + INSERT INTO dbo.[Queue] (SchemaName, ObjectName, [Parameters]) + VALUES(@SchemaName, @ObjectName, @ParametersString) + + SET @QueueID = SCOPE_IDENTITY() + END + + COMMIT TRANSACTION + END + + BEGIN TRANSACTION + + UPDATE [Queue] + 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) + 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 COLLATE DATABASE_DEFAULT = 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 COLLATE DATABASE_DEFAULT AND Selected = 1) + + UPDATE QueueDatabase + SET DatabaseOrder = tmpDatabases.[Order] + FROM dbo.QueueDatabase QueueDatabase + INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT = tmpDatabases.DatabaseName + WHERE QueueID = @QueueID + 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(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + SET @ReturnCode = ERROR_NUMBER() + GOTO Logging + END CATCH + + END + + ---------------------------------------------------------------------------------------------------- + --// Execute commands //-- + ---------------------------------------------------------------------------------------------------- + + WHILE (1 = 1) + BEGIN -- Start of database loop + + IF @DatabasesInParallel = 'Y' + 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 = SYSDATETIME(), + 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 + BREAK + END + + SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + + BEGIN + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar(max),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, + @CurrentInStandby = is_in_standby, + @CurrentRecoveryModel = recovery_model_desc + 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 @IsHadrEnabled = 1 + BEGIN + SELECT @CurrentAvailabilityGroupReplicaID = 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 @CurrentAvailabilityGroupID = group_id, + @CurrentSecondaryRoleAllowConnections = secondary_role_allow_connections_desc + FROM sys.availability_replicas + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + + SELECT @CurrentAvailabilityGroupRole = role_desc + FROM sys.dm_hadr_availability_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + + SELECT @CurrentAvailabilityGroup = [name], + @CurrentAvailabilityGroupBackupPreference = UPPER(automated_backup_preference_desc) + FROM sys.availability_groups + WHERE group_id = @CurrentAvailabilityGroupID + END + + IF @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 @IsHadrEnabled = 1 AND @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], + @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id + FROM sys.availability_groups availability_groups + INNER JOIN sys.availability_replicas availability_replicas ON availability_groups.group_id = availability_replicas.group_id + INNER JOIN sys.availability_groups availability_groups_local ON availability_replicas.replica_server_name = availability_groups_local.[name] + WHERE availability_groups.is_distributed = 1 + AND availability_groups_local.group_id = @CurrentAvailabilityGroupID + + SELECT @CurrentDistributedAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc + FROM sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states + WHERE dm_hadr_availability_replica_states.replica_id = @CurrentDistributedAvailabilityGroupReplicaID + END + + IF @EngineEdition <> 5 + BEGIN + SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) + FROM sys.database_mirroring database_mirroring + INNER JOIN sys.databases databases ON database_mirroring.database_id = databases.database_id + WHERE databases.[name] = @CurrentDatabaseName + END + + IF @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + 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') + 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('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + END + + IF @CurrentDistributedAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Distributed availability group: ' + ISNULL(@CurrentDistributedAvailabilityGroup,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Distributed availability group role: ' + ISNULL(@CurrentDistributedAvailabilityGroupRole,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Replica role in distributed availability group: ' + CASE WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Global primary' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Forwarder' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in secondary availability group' + WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in primary availability group' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + + IF @CurrentDatabaseMirroringRole IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + IF @CurrentDatabaseState IN('ONLINE','EMERGENCY') + AND NOT (@CurrentUserAccess = 'SINGLE_USER') + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR @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') + AND NOT (@CurrentIsReadOnly = 0 AND @Updateability = 'READ_ONLY') + AND NOT (@AmazonRDS = 1 AND @CurrentDatabaseName = 'rdsadmin') + BEGIN + + -- Check database + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKDB') AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + BEGIN + SET @CurrentDatabaseContext = CASE WHEN @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(max)) + '; ' + SET @CurrentCommand += 'DBCC CHECKDB (' + QUOTENAME(@CurrentDatabaseName) + IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' + SET @CurrentCommand += ') WITH ALL_ERRORMSGS' + IF @DataPurity = 'Y' SET @CurrentCommand += ', DATA_PURITY' + IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' + IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand += ', EXTENDED_LOGICAL_CHECKS' + IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ', NO_INFOMSGS' + IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar(max)) + + 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 @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput + END + + -- Check filegroups + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') + 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 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) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 SET @ReturnCode = @Error + + IF @FileGroups IS NULL + BEGIN + UPDATE tmpFileGroups + SET tmpFileGroups.Selected = 1 + FROM @tmpFileGroups tmpFileGroups + END + ELSE + BEGIN + UPDATE tmpFileGroups + SET tmpFileGroups.Selected = SelectedFileGroups.Selected + FROM @tmpFileGroups tmpFileGroups + INNER JOIN @SelectedFileGroups SelectedFileGroups + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedFileGroups.DatabaseName,'[','[[]'),'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(REPLACE(SelectedFileGroups.FileGroupName,'[','[[]'),'_','[_]') + WHERE SelectedFileGroups.Selected = 1 + + UPDATE tmpFileGroups + SET tmpFileGroups.Selected = SelectedFileGroups.Selected + FROM @tmpFileGroups tmpFileGroups + INNER JOIN @SelectedFileGroups SelectedFileGroups + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedFileGroups.DatabaseName,'[','[[]'),'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(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(REPLACE(SelectedFileGroups.DatabaseName,'[','[[]'),'_','[_]') AND tmpFileGroups.FileGroupName LIKE REPLACE(REPLACE(SelectedFileGroups.FileGroupName,'[','[[]'),'_','[_]') + WHERE SelectedFileGroups.Selected = 1 + GROUP BY tmpFileGroups.FileGroupName) SelectedFileGroups2 + 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 + + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)) + '.' + QUOTENAME(FileGroupName), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC, FileGroupName ASC) + FROM @SelectedFileGroups SelectedFileGroups + WHERE DatabaseName = @CurrentDatabaseName + AND FileGroupName NOT LIKE '%[%]%' + AND NOT EXISTS (SELECT * FROM @tmpFileGroups WHERE FileGroupName = SelectedFileGroups.FileGroupName) + + IF @ErrorMessage IS NOT NULL + BEGIN + SET @ErrorMessage = 'The following file groups do not exist: ' + @ErrorMessage + '.' + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + + WHILE (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + BEGIN + SELECT TOP 1 @CurrentFGID = ID, + @CurrentFileGroupID = FileGroupID, + @CurrentFileGroupName = FileGroupName + FROM @tmpFileGroups + WHERE Selected = 1 + AND Completed = 0 + ORDER BY [Order] ASC + + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + + -- Does the filegroup exist? + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + 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 = @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 + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + END CATCH + + IF @CurrentFileGroupExists = 1 + BEGIN + SET @CurrentDatabaseContext = @CurrentDatabaseName + + SET @CurrentCommandType = 'DBCC_CHECKFILEGROUP' + + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + SET @CurrentCommand += 'DBCC CHECKFILEGROUP (' + QUOTENAME(@CurrentFileGroupName) + IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' + SET @CurrentCommand += ') WITH ALL_ERRORMSGS' + IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' + IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ', NO_INFOMSGS' + IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar(max)) + + 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 @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput + END + + UPDATE @tmpFileGroups + SET Completed = 1 + WHERE Selected = 1 + AND Completed = 0 + AND ID = @CurrentFGID + + SET @CurrentFGID = NULL + SET @CurrentFileGroupID = NULL + SET @CurrentFileGroupName = NULL + SET @CurrentFileGroupExists = 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 @CurrentDatabaseContext = CASE WHEN @EngineEdition = 5 THEN @CurrentDatabaseName ELSE 'master' END + + SET @CurrentCommandType = 'DBCC_CHECKALLOC' + + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + SET @CurrentCommand += 'DBCC CHECKALLOC (' + QUOTENAME(@CurrentDatabaseName) + IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' + SET @CurrentCommand += ') WITH ALL_ERRORMSGS' + IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ', NO_INFOMSGS' + IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' + + 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 @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput + END + + -- Check objects + IF EXISTS(SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE') + 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 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) AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL) ORDER BY schemas.name ASC, objects.name ASC' + + INSERT INTO @tmpObjects (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 SET @ReturnCode = @Error + + IF @Objects IS NULL + BEGIN + UPDATE tmpObjects + SET tmpObjects.Selected = 1 + FROM @tmpObjects tmpObjects + END + ELSE + BEGIN + UPDATE tmpObjects + SET tmpObjects.Selected = SelectedObjects.Selected + FROM @tmpObjects tmpObjects + INNER JOIN @SelectedObjects SelectedObjects + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedObjects.DatabaseName,'[','[[]'),'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(REPLACE(SelectedObjects.SchemaName,'[','[[]'),'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(REPLACE(SelectedObjects.ObjectName,'[','[[]'),'_','[_]') + WHERE SelectedObjects.Selected = 1 + + UPDATE tmpObjects + SET tmpObjects.Selected = SelectedObjects.Selected + FROM @tmpObjects tmpObjects + INNER JOIN @SelectedObjects SelectedObjects + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedObjects.DatabaseName,'[','[[]'),'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(REPLACE(SelectedObjects.SchemaName,'[','[[]'),'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(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(REPLACE(SelectedObjects.DatabaseName,'[','[[]'),'_','[_]') AND tmpObjects.SchemaName LIKE REPLACE(REPLACE(SelectedObjects.SchemaName,'[','[[]'),'_','[_]') AND tmpObjects.ObjectName LIKE REPLACE(REPLACE(SelectedObjects.ObjectName,'[','[[]'),'_','[_]') + WHERE SelectedObjects.Selected = 1 + GROUP BY tmpObjects.SchemaName, tmpObjects.ObjectName) SelectedObjects2 + 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 + + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC, SchemaName ASC, ObjectName ASC) + 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 @ErrorMessage IS NOT NULL + BEGIN + SET @ErrorMessage = 'The following objects do not exist: ' + @ErrorMessage + '.' + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + + WHILE (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + BEGIN + SELECT TOP 1 @CurrentOID = ID, + @CurrentSchemaID = SchemaID, + @CurrentSchemaName = SchemaName, + @CurrentObjectID = ObjectID, + @CurrentObjectName = ObjectName, + @CurrentObjectType = ObjectType + FROM @tmpObjects + WHERE Selected = 1 + AND Completed = 0 + ORDER BY [Order] ASC + + IF @@ROWCOUNT = 0 + BEGIN + BREAK + END + + -- Does the object exist? + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + 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) AND (tables.is_memory_optimized = 0 OR is_memory_optimized IS NULL) 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 = @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 + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + END CATCH + + IF @CurrentObjectExists = 1 + BEGIN + SET @CurrentDatabaseContext = @CurrentDatabaseName + + SET @CurrentCommandType = 'DBCC_CHECKTABLE' + + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + SET @CurrentCommand += 'DBCC CHECKTABLE (N''' + REPLACE(QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName),'''','''''') + '''' + IF @NoIndex = 'Y' SET @CurrentCommand += ', NOINDEX' + SET @CurrentCommand += ') WITH ALL_ERRORMSGS' + IF @DataPurity = 'Y' SET @CurrentCommand += ', DATA_PURITY' + IF @PhysicalOnly = 'Y' SET @CurrentCommand += ', PHYSICAL_ONLY' + IF @ExtendedLogicalChecks = 'Y' SET @CurrentCommand += ', EXTENDED_LOGICAL_CHECKS' + IF @NoInformationalMessages = 'Y' SET @CurrentCommand += ', NO_INFOMSGS' + IF @TabLock = 'Y' SET @CurrentCommand += ', TABLOCK' + IF @MaxDOP IS NOT NULL SET @CurrentCommand += ', MAXDOP = ' + CAST(@MaxDOP AS nvarchar(max)) + + 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 @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput + END + + UPDATE @tmpObjects + SET Completed = 1 + WHERE Selected = 1 + AND Completed = 0 + AND ID = @CurrentOID + + SET @CurrentOID = NULL + SET @CurrentSchemaID = NULL + SET @CurrentSchemaName = NULL + SET @CurrentObjectID = NULL + SET @CurrentObjectName = NULL + SET @CurrentObjectType = NULL + SET @CurrentObjectExists = 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 (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + BEGIN + SET @CurrentDatabaseContext = CASE WHEN @EngineEdition = 5 THEN @CurrentDatabaseName ELSE 'master' END + + SET @CurrentCommandType = 'DBCC_CHECKCATALOG' + + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + SET @CurrentCommand += 'DBCC CHECKCATALOG (' + QUOTENAME(@CurrentDatabaseName) + SET @CurrentCommand += ')' + IF @NoInformationalMessages = 'Y' 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 @CurrentCommandOutput = @Error + IF @CurrentCommandOutput <> 0 SET @ReturnCode = @CurrentCommandOutput + END + + END + + IF @CurrentDatabaseState = 'SUSPECT' + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + SET @ReturnCode = @Error + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + + -- Update that the database is completed + IF @DatabasesInParallel = 'Y' + BEGIN + UPDATE dbo.QueueDatabase + SET DatabaseEndTime = SYSDATETIME() + 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 + SET @CurrentDatabaseName = NULL + + SET @CurrentDatabase_sp_executesql = NULL + + SET @CurrentUserAccess = NULL + SET @CurrentIsReadOnly = NULL + SET @CurrentDatabaseState = NULL + SET @CurrentInStandby = NULL + SET @CurrentRecoveryModel = NULL + + SET @CurrentAvailabilityGroupReplicaID = NULL + SET @CurrentAvailabilityGroupID = NULL + SET @CurrentAvailabilityGroup = NULL + SET @CurrentAvailabilityGroupRole = NULL + SET @CurrentAvailabilityGroupBackupPreference = NULL + SET @CurrentSecondaryRoleAllowConnections = NULL + SET @CurrentIsPreferredBackupReplica = NULL + SET @CurrentDistributedAvailabilityGroup = NULL + SET @CurrentDistributedAvailabilityGroupReplicaID = NULL + SET @CurrentDistributedAvailabilityGroupRole = NULL + SET @CurrentDatabaseMirroringRole = NULL + + SET @CurrentDatabaseContext = NULL + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL + + DELETE FROM @tmpFileGroups + DELETE FROM @tmpObjects + + END -- End of database loop + + ---------------------------------------------------------------------------------------------------- + --// Log completing information //-- + ---------------------------------------------------------------------------------------------------- + + Logging: + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar(max),SYSDATETIME(),120) + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT + + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + IF @ReturnCode <> 0 + BEGIN + RETURN @ReturnCode + END + + ---------------------------------------------------------------------------------------------------- + +END + +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].[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, +@FragmentationMedium nvarchar(max) = 'INDEX_REORGANIZE,INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationHigh nvarchar(max) = 'INDEX_REBUILD_ONLINE,INDEX_REBUILD_OFFLINE', +@FragmentationLevel1 int = 5, +@FragmentationLevel2 int = 30, +@MinNumberOfPages int = 1000, +@MaxNumberOfPages int = NULL, +@SortInTempdb nvarchar(max) = 'N', +@MaxDOP int = NULL, +@FillFactor int = NULL, +@PadIndex nvarchar(max) = NULL, +@DataCompression nvarchar(max) = NULL, +@WaitAtLowPriorityMaxDuration int = NULL, +@WaitAtLowPriorityAbortAfterWait nvarchar(max) = NULL, +@Resumable nvarchar(max) = 'N', +@LOBCompaction nvarchar(max) = 'Y', +@UpdateStatistics nvarchar(max) = NULL, +@OnlyModifiedStatistics nvarchar(max) = 'N', +@StatisticsModificationLevel int = NULL, +@StatisticsSample int = NULL, +@StatisticsPersistSample nvarchar(max) = NULL, +@StatisticsResample nvarchar(max) = 'N', +@PartitionLevel nvarchar(max) = 'Y', +@MSShippedObjects nvarchar(max) = 'N', +@Indexes nvarchar(max) = NULL, +@TimeLimit int = NULL, +@Delay int = NULL, +@AvailabilityGroups nvarchar(max) = NULL, +@LockTimeout int = NULL, +@LockMessageSeverity int = 16, +@StringDelimiter nvarchar(max) = ',', +@DatabaseOrder nvarchar(max) = NULL, +@DatabasesInParallel nvarchar(max) = 'N', +@ExecuteAsUser nvarchar(max) = NULL, +@LogToTable nvarchar(max) = 'N', +@Execute nvarchar(max) = 'Y' + +AS + +BEGIN + + ---------------------------------------------------------------------------------------------------- + --// Source: https://ola.hallengren.com //-- + --// License: https://ola.hallengren.com/license.html //-- + --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- + --// Version: 2026-07-21 11:25:14 //-- + ---------------------------------------------------------------------------------------------------- + + SET NOCOUNT ON + + SET ARITHABORT ON + + SET NUMERIC_ROUNDABORT OFF + + DECLARE @StartMessage nvarchar(max) + DECLARE @EndMessage nvarchar(max) + DECLARE @DatabaseMessage nvarchar(max) + DECLARE @ErrorMessage nvarchar(max) + DECLARE @Severity int + + 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 TABLE (ID int IDENTITY PRIMARY KEY, + [Name] nvarchar(max) NOT NULL, + ValueNvarchar nvarchar(max), + ValueInt int, + ValueDatetime datetime2) + + DECLARE @ParametersString nvarchar(max) + DECLARE @CurrentParameterName nvarchar(max) + DECLARE @CurrentParameterValueNvarchar nvarchar(max) + DECLARE @CurrentParameterValueInt int + DECLARE @CurrentParameterValueDatetime datetime2 + DECLARE @CurrentParameterDelimiter nvarchar(max) + DECLARE @CurrentParameterMessage nvarchar(max) + + DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 + + DECLARE @QueueID int + DECLARE @QueueStartTime datetime2 + + DECLARE @CurrentDBID int + DECLARE @CurrentDatabaseName nvarchar(max) + + DECLARE @CurrentDatabase_sp_executesql nvarchar(max) + + DECLARE @CurrentExecuteAsUserExists bit + DECLARE @CurrentUserAccess nvarchar(max) + DECLARE @CurrentIsReadOnly bit + DECLARE @CurrentDatabaseState nvarchar(max) + DECLARE @CurrentInStandby bit + DECLARE @CurrentRecoveryModel nvarchar(max) + DECLARE @CurrentDatabaseHasReadOnlyFileGroup bit + + DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier + DECLARE @CurrentAvailabilityGroupID uniqueidentifier + DECLARE @CurrentAvailabilityGroup nvarchar(max) + DECLARE @CurrentAvailabilityGroupRole nvarchar(max) + DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) + DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier + DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) + DECLARE @CurrentDatabaseMirroringRole nvarchar(max) + + 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) NOT NULL, + Severity int NOT NULL, + [State] int) + + DECLARE @CurrentMessage nvarchar(max) + DECLARE @CurrentSeverity int + DECLARE @CurrentState int + + DECLARE @CurrentIxID int + DECLARE @CurrentIxOrder int + DECLARE @CurrentSchemaID int + DECLARE @CurrentSchemaName nvarchar(max) + DECLARE @CurrentObjectID int + DECLARE @CurrentObjectName nvarchar(max) + DECLARE @CurrentObjectType nvarchar(max) + DECLARE @CurrentIsMemoryOptimized bit + DECLARE @CurrentIndexID int + DECLARE @CurrentIndexName nvarchar(max) + DECLARE @CurrentIndexType int + DECLARE @CurrentStatisticsID int + DECLARE @CurrentStatisticsName nvarchar(max) + DECLARE @CurrentPartitionID bigint + DECLARE @CurrentPartitionNumber int + DECLARE @CurrentPartitionCount int + DECLARE @CurrentInRowDataPageCount bigint + DECLARE @CurrentIsPartition bit + DECLARE @CurrentIndexExists bit + DECLARE @CurrentStatisticsExists bit + DECLARE @CurrentIsImageText bit + DECLARE @CurrentIsFileStream bit + DECLARE @CurrentHasClusteredColumnstore bit + DECLARE @CurrentIsColumnstoreOrdered bit + DECLARE @CurrentIsComputed bit + DECLARE @CurrentIsClusteredIndexComputed bit + DECLARE @CurrentIsTimestamp bit + DECLARE @CurrentAllowPageLocks bit + DECLARE @CurrentHasFilter bit + DECLARE @CurrentNoRecompute bit + DECLARE @CurrentIsIncremental bit + DECLARE @CurrentObjectHasRows bit + DECLARE @CurrentRowCount bigint + DECLARE @CurrentModificationCounter bigint + DECLARE @CurrentOnReadOnlyFileGroup bit + DECLARE @CurrentResumableIndexOperation bit + DECLARE @CurrentFragmentationLevel float + DECLARE @CurrentPageCount bigint + DECLARE @CurrentFragmentationGroup nvarchar(max) + DECLARE @CurrentAction nvarchar(max) + DECLARE @CurrentMaxDOP int + DECLARE @CurrentUpdateStatistics nvarchar(max) + DECLARE @CurrentStatisticsSample int + DECLARE @CurrentStatisticsPersistSample nvarchar(max) + DECLARE @CurrentStatisticsResample nvarchar(max) + DECLARE @CurrentDelay datetime + + DECLARE @tmpDatabases TABLE (ID int IDENTITY, + DatabaseName nvarchar(128), + DatabaseType nvarchar(1), + AvailabilityGroup bit, + StartPosition int, + DatabaseSize bigint, + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID)) + + DECLARE @tmpAvailabilityGroups TABLE (ID int IDENTITY PRIMARY KEY, + AvailabilityGroupName nvarchar(128), + StartPosition int, + Selected bit DEFAULT 0) + + DECLARE @tmpDatabasesAvailabilityGroups TABLE (DatabaseName nvarchar(128), + AvailabilityGroupName nvarchar(128)) + + DECLARE @tmpIndexesStatistics TABLE (ID int IDENTITY, + SchemaID int, + SchemaName nvarchar(128), + ObjectID int, + ObjectName nvarchar(128), + ObjectType nvarchar(2), + IsMemoryOptimized bit, + IndexID int, + IndexName nvarchar(128), + IndexType int, + AllowPageLocks bit, + HasFilter bit, + IsImageText bit, + IsFileStream bit, + HasClusteredColumnstore bit, + IsColumnstoreOrdered bit, + IsComputed bit, + IsClusteredIndexComputed bit, + IsTimestamp bit, + OnReadOnlyFileGroup bit, + ResumableIndexOperation bit, + StatisticsID int, + StatisticsName nvarchar(128), + [NoRecompute] bit, + IsIncremental bit, + PartitionID bigint, + PartitionNumber int, + PartitionCount int, + InRowDataPageCount bigint, + StartPosition int, + [Order] int DEFAULT 0, + Selected bit DEFAULT 0, + Completed bit DEFAULT 0, + PRIMARY KEY (Selected, Completed, [Order], ID), + INDEX IX_ObjectID_StatisticsID_PartitionNumber NONCLUSTERED (ObjectID, StatisticsID, PartitionNumber)) + + DROP TABLE IF EXISTS #SelectedIndexes + + CREATE TABLE #SelectedIndexes (DatabaseName nvarchar(max) COLLATE DATABASE_DEFAULT, + SchemaName nvarchar(max) COLLATE DATABASE_DEFAULT, + ObjectName nvarchar(max) COLLATE DATABASE_DEFAULT, + IndexName nvarchar(max) COLLATE DATABASE_DEFAULT, + StartPosition int, + Selected bit) + + DROP TABLE IF EXISTS #Objects + + CREATE TABLE #Objects (ObjectID int NOT NULL, + SchemaID int, + SchemaName nvarchar(128) COLLATE DATABASE_DEFAULT, + ObjectName nvarchar(128) COLLATE DATABASE_DEFAULT, + ObjectType nvarchar(2) COLLATE DATABASE_DEFAULT, + IsMemoryOptimized bit, + HasClusteredColumnstore bit, + IsClusteredIndexComputed bit, + IsClusteredIndexDisabled bit, + PRIMARY KEY (ObjectID)) + + DROP TABLE IF EXISTS #Indexes + + CREATE TABLE #Indexes (ObjectID int NOT NULL, + IndexID int NOT NULL, + IndexName nvarchar(128) COLLATE DATABASE_DEFAULT, + IndexType int, + DataSpaceID int, + AllowPageLocks bit, + HasFilter bit, + IsImageText bit, + IsFileStream bit, + IsColumnstoreOrdered bit, + IsComputed bit, + IsTimestamp bit, + PRIMARY KEY (ObjectID, IndexID)) + + DROP TABLE IF EXISTS #Stats + + CREATE TABLE #Stats (ObjectID int NOT NULL, + StatisticsID int NOT NULL, + StatisticsName nvarchar(128) COLLATE DATABASE_DEFAULT, + [NoRecompute] bit, + IsIncremental bit, + IsIndex bit, + PRIMARY KEY (ObjectID, StatisticsID)) + + DROP TABLE IF EXISTS #ExistingObjects + + CREATE TABLE #ExistingObjects (SchemaName nvarchar(max) COLLATE DATABASE_DEFAULT, + ObjectName nvarchar(max) COLLATE DATABASE_DEFAULT) + + DROP TABLE IF EXISTS #ExistingIndexes + + CREATE TABLE #ExistingIndexes (SchemaName nvarchar(max) COLLATE DATABASE_DEFAULT, + ObjectName nvarchar(max) COLLATE DATABASE_DEFAULT, + IndexName nvarchar(max) COLLATE DATABASE_DEFAULT) + + DECLARE @tmpResumableOperations TABLE (ObjectID int NOT NULL, + IndexID int NOT NULL, + PartitionNumber int) + + DECLARE @SelectedDatabases TABLE (DatabaseName nvarchar(max), + DatabaseType nvarchar(1), + AvailabilityGroup bit, + 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 @IncrementalStatsProperties TABLE (ObjectID int, + StatisticsID int, + PartitionNumber int, + [Rows] bigint, + ModificationCounter bigint, + PRIMARY KEY (ObjectID, StatisticsID, PartitionNumber)) + + DECLARE @Actions TABLE ([Action] nvarchar(max)) + + INSERT INTO @Actions([Action]) VALUES('INDEX_REBUILD_ONLINE') + INSERT INTO @Actions([Action]) VALUES('INDEX_REBUILD_OFFLINE') + INSERT INTO @Actions([Action]) VALUES('INDEX_REORGANIZE') + + DECLARE @ActionsPreferred TABLE (FragmentationGroup nvarchar(max), + [Priority] int, + [Action] nvarchar(max)) + + DECLARE @CurrentActionsAllowed TABLE ([Action] nvarchar(max)) + + DECLARE @CurrentAlterIndexWithClauseArguments TABLE (ID int IDENTITY, + Argument nvarchar(max)) + + DECLARE @CurrentUpdateStatisticsWithClauseArguments TABLE (ID int IDENTITY, + Argument nvarchar(max)) + + DECLARE @Error int = 0 + DECLARE @ReturnCode int = 0 + + DECLARE @EmptyLine nvarchar(max) = CHAR(9) + + DECLARE @ProductVersion nvarchar(max) = CAST(SERVERPROPERTY('ProductVersion') AS nvarchar(max)) + DECLARE @ProductUpdateType nvarchar(max) = CAST(SERVERPROPERTY('ProductUpdateType') AS nvarchar(max)) + DECLARE @EngineEdition int = CAST(SERVERPROPERTY('EngineEdition') AS int) + DECLARE @Edition nvarchar(max) = CAST(SERVERPROPERTY('Edition') AS nvarchar(max)) + DECLARE @IsHadrEnabled bit = CAST(SERVERPROPERTY('IsHadrEnabled') AS bit) + DECLARE @ServerName nvarchar(max) = CAST(SERVERPROPERTY('ServerName') AS nvarchar(max)) + + DECLARE @Collation nvarchar(128) = CAST(DATABASEPROPERTYEX(DB_NAME(),'Collation') AS nvarchar(128)) + + DECLARE @Version numeric(18,10) = CAST(PARSENAME(@ProductVersion,4) + '.' + PARSENAME(@ProductVersion,3) + PARSENAME(@ProductVersion,2) AS numeric(18,10)) + + IF @EngineEdition = 8 AND @ProductVersion = '12.0.2000.8' AND @ProductUpdateType = 'CU' + BEGIN + SET @Version = 16.01000 + END + + IF @EngineEdition <> 5 + BEGIN + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + END + + IF @EngineEdition <> 5 + BEGIN + IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) + AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) + BEGIN + SET @ContainedAvailabilityGroupListenerConnection = 1 + END + END + + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + + ---------------------------------------------------------------------------------------------------- + --// Log initial information //-- + ---------------------------------------------------------------------------------------------------- + + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Databases', @Databases) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FragmentationLow', @FragmentationLow) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FragmentationMedium', @FragmentationMedium) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@FragmentationHigh', @FragmentationHigh) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@FragmentationLevel1', @FragmentationLevel1) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@FragmentationLevel2', @FragmentationLevel2) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MinNumberOfPages', @MinNumberOfPages) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MaxNumberOfPages', @MaxNumberOfPages) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@SortInTempdb', @SortInTempdb) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@MaxDOP', @MaxDOP) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@FillFactor', @FillFactor) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@PadIndex', @PadIndex) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DataCompression', @DataCompression) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@WaitAtLowPriorityMaxDuration', @WaitAtLowPriorityMaxDuration) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@WaitAtLowPriorityAbortAfterWait', @WaitAtLowPriorityAbortAfterWait) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Resumable', @Resumable) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@LOBCompaction', @LOBCompaction) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@UpdateStatistics', @UpdateStatistics) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@OnlyModifiedStatistics', @OnlyModifiedStatistics) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@StatisticsModificationLevel', @StatisticsModificationLevel) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@StatisticsSample', @StatisticsSample) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@StatisticsPersistSample', @StatisticsPersistSample) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@StatisticsResample', @StatisticsResample) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@PartitionLevel', @PartitionLevel) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@MSShippedObjects', @MSShippedObjects) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Indexes', @Indexes) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@TimeLimit', @TimeLimit) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@Delay', @Delay) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@AvailabilityGroups', @AvailabilityGroups) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@LockTimeout', @LockTimeout) + INSERT INTO @Parameters ([Name], ValueInt) VALUES('@LockMessageSeverity', @LockMessageSeverity) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@StringDelimiter', @StringDelimiter) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabaseOrder', @DatabaseOrder) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@DatabasesInParallel', @DatabasesInParallel) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@ExecuteAsUser', @ExecuteAsUser) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@LogToTable', @LogToTable) + INSERT INTO @Parameters ([Name], ValueNvarchar) VALUES('@Execute', @Execute) + + SELECT @ParametersString = STRING_AGG(CAST([Name] + ' = ' + CASE WHEN ValueNvarchar IS NOT NULL THEN '''' + REPLACE(ValueNvarchar,'''','''''') + '''' WHEN ValueInt IS NOT NULL THEN CAST(ValueInt AS nvarchar(max)) WHEN ValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), ValueDatetime, 21) + '''' ELSE 'NULL' END AS nvarchar(max)), ', ') WITHIN GROUP (ORDER BY [ID] ASC) + FROM @Parameters + + SET @StartMessage = 'Date and time: ' + CONVERT(nvarchar(max),@StartTime,120) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'Server: ' + @ServerName + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'Version: ' + @ProductVersion + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'Edition: ' + @Edition + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + IF @EngineEdition = 8 + BEGIN + SET @StartMessage = 'Update type: ' + @ProductUpdateType + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + + IF @EngineEdition <> 5 + BEGIN + SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + + IF @EngineEdition <> 5 + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'Procedure: ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'Version: ' + @VersionTimestamp + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'Source: https://ola.hallengren.com' + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + SET @StartMessage = 'Command:' + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + SET @StartMessage = 'EXECUTE ' + QUOTENAME(@SchemaName) + '.' + QUOTENAME(@ObjectName) + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + + DECLARE ParameterCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Name], ValueNvarchar, ValueInt, ValueDatetime, CASE WHEN [ID] = MAX([ID]) OVER() THEN '' ELSE ',' END FROM @Parameters ORDER BY [ID] ASC + + OPEN ParameterCursor + + FETCH ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + + WHILE @@FETCH_STATUS = 0 + BEGIN + SET @CurrentParameterMessage = @CurrentParameterName + ' = ' + CASE WHEN @CurrentParameterValueNvarchar IS NOT NULL THEN '''' + REPLACE(@CurrentParameterValueNvarchar,'''','''''') + '''' WHEN @CurrentParameterValueInt IS NOT NULL THEN CAST(@CurrentParameterValueInt AS nvarchar(max)) WHEN @CurrentParameterValueDatetime IS NOT NULL THEN '''' + CONVERT(nvarchar(max), @CurrentParameterValueDatetime, 21) + '''' ELSE 'NULL' END + @CurrentParameterDelimiter + + RAISERROR('%s',10,1,@CurrentParameterMessage) WITH NOWAIT + + FETCH NEXT FROM ParameterCursor INTO @CurrentParameterName, @CurrentParameterValueNvarchar, @CurrentParameterValueInt, @CurrentParameterValueDatetime, @CurrentParameterDelimiter + END + + CLOSE ParameterCursor + + DEALLOCATE ParameterCursor + + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + ---------------------------------------------------------------------------------------------------- + --// Check core requirements //-- + ---------------------------------------------------------------------------------------------------- + + IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('The transaction count is not 0.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + --// Select databases //-- + ---------------------------------------------------------------------------------------------------- + + SET @Databases = REPLACE(@Databases, CHAR(10), '') + SET @Databases = REPLACE(@Databases, CHAR(13), '') + + 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(@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(@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 + ), + 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, 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, 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, StartPosition, Selected) + SELECT DatabaseName, + DatabaseType, + AvailabilityGroup, + StartPosition, + Selected + FROM Databases4 + OPTION (MAXRECURSION 0) + + IF @IsHadrEnabled = 1 + BEGIN + INSERT INTO @tmpAvailabilityGroups (AvailabilityGroupName) + SELECT name AS AvailabilityGroupName + FROM sys.availability_groups + + INSERT INTO @tmpDatabasesAvailabilityGroups (DatabaseName, AvailabilityGroupName) + SELECT databases.name, + availability_groups.name + FROM sys.databases databases + 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) + SELECT [name] AS DatabaseName, + CASE WHEN name IN('master','msdb','model') OR is_distributor = 1 THEN 'S' ELSE 'U' END AS DatabaseType, + NULL AS AvailabilityGroup + 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 + INNER JOIN @SelectedDatabases SelectedDatabases + ON tmpDatabases.DatabaseName LIKE REPLACE(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 + + UPDATE tmpDatabases + SET tmpDatabases.Selected = SelectedDatabases.Selected + FROM @tmpDatabases tmpDatabases + INNER JOIN @SelectedDatabases SelectedDatabases + ON tmpDatabases.DatabaseName LIKE REPLACE(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 = 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(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 DATALENGTH(DatabaseName) = 0)) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @Databases is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + --// Select availability groups //-- + ---------------------------------------------------------------------------------------------------- + + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 1 + BEGIN + + SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(10), '') + SET @AvailabilityGroups = REPLACE(@AvailabilityGroups, CHAR(13), '') + + 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(@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(@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 + ), + 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, StartPosition, Selected) AS + ( + SELECT CASE WHEN AvailabilityGroupItem = 'ALL_AVAILABILITY_GROUPS' THEN '%' ELSE AvailabilityGroupItem END AS AvailabilityGroupItem, + StartPosition, + Selected + FROM AvailabilityGroups2 + ), + 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, StartPosition, Selected) + SELECT AvailabilityGroupName, StartPosition, Selected + FROM AvailabilityGroups4 + OPTION (MAXRECURSION 0) + + UPDATE tmpAvailabilityGroups + SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') + WHERE SelectedAvailabilityGroups.Selected = 1 + + UPDATE tmpAvailabilityGroups + SET tmpAvailabilityGroups.Selected = SelectedAvailabilityGroups.Selected + FROM @tmpAvailabilityGroups tmpAvailabilityGroups + INNER JOIN @SelectedAvailabilityGroups SelectedAvailabilityGroups + ON tmpAvailabilityGroups.AvailabilityGroupName LIKE REPLACE(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(REPLACE(SelectedAvailabilityGroups.AvailabilityGroupName,'[','[[]'),'_','[_]') + WHERE SelectedAvailabilityGroups.Selected = 1 + GROUP BY tmpAvailabilityGroups.AvailabilityGroupName) SelectedAvailabilityGroups2 + ON tmpAvailabilityGroups.AvailabilityGroupName = SelectedAvailabilityGroups2.AvailabilityGroupName + + UPDATE tmpDatabases + 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 + WHERE tmpAvailabilityGroups.Selected = 1 + + END + + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '') OR @IsHadrEnabled = 0) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) + END + + ---------------------------------------------------------------------------------------------------- + --// Select indexes //-- + ---------------------------------------------------------------------------------------------------- + + SET @Indexes = REPLACE(@Indexes, CHAR(10), '') + SET @Indexes = REPLACE(@Indexes, CHAR(13), '') + + 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(@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(@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 + ), + 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, StartPosition, Selected) AS + ( + SELECT CASE WHEN IndexItem = 'ALL_INDEXES' THEN '%.%.%.%' ELSE IndexItem END AS IndexItem, + StartPosition, + Selected + FROM Indexes2 + ), + 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, StartPosition, Selected) + SELECT DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected + FROM Indexes4 + OPTION (MAXRECURSION 0) + + INSERT INTO #SelectedIndexes (DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected) + SELECT DatabaseName, SchemaName, ObjectName, IndexName, StartPosition, Selected + FROM @SelectedIndexes + + ---------------------------------------------------------------------------------------------------- + --// Select actions //-- + ---------------------------------------------------------------------------------------------------- + + SET @FragmentationLow = REPLACE(@FragmentationLow, @StringDelimiter + ' ', @StringDelimiter); + + WITH FragmentationLow (StartPosition, EndPosition, [Action]) AS + ( + SELECT 1 AS StartPosition, + 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(@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 + ) + INSERT INTO @ActionsPreferred(FragmentationGroup, [Priority], [Action]) + SELECT 'Low' AS FragmentationGroup, + ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS [Priority], + [Action] + FROM FragmentationLow + OPTION (MAXRECURSION 0) + + SET @FragmentationMedium = REPLACE(@FragmentationMedium, @StringDelimiter + ' ', @StringDelimiter); + + WITH FragmentationMedium (StartPosition, EndPosition, [Action]) AS + ( + SELECT 1 AS StartPosition, + 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(@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 + ) + INSERT INTO @ActionsPreferred(FragmentationGroup, [Priority], [Action]) + SELECT 'Medium' AS FragmentationGroup, + ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS [Priority], + [Action] + FROM FragmentationMedium + OPTION (MAXRECURSION 0) + + SET @FragmentationHigh = REPLACE(@FragmentationHigh, @StringDelimiter + ' ', @StringDelimiter); + + WITH FragmentationHigh (StartPosition, EndPosition, [Action]) AS + ( + SELECT 1 AS StartPosition, + 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(@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 + ) + INSERT INTO @ActionsPreferred(FragmentationGroup, [Priority], [Action]) + SELECT 'High' AS FragmentationGroup, + ROW_NUMBER() OVER(ORDER BY StartPosition ASC) AS [Priority], + [Action] + FROM FragmentationHigh + OPTION (MAXRECURSION 0) + + ---------------------------------------------------------------------------------------------------- + --// Check input parameters //-- + ---------------------------------------------------------------------------------------------------- + + IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' AND [Action] NOT IN(SELECT * FROM @Actions)) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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]) + VALUES('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)) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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]) + VALUES('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)) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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]) + VALUES('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]) + VALUES('The value for the parameter @FragmentationLevel1 is not supported.', 16, 1) + END + + IF @FragmentationLevel1 >= @FragmentationLevel2 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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]) + VALUES('The value for the parameter @FragmentationLevel2 is not supported.', 16, 1) + END + + IF @FragmentationLevel2 <= @FragmentationLevel1 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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, [State]) + VALUES('The value for the parameter @MinNumberOfPages is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @MaxNumberOfPages < 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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, [State]) + VALUES('The value for the parameter @SortInTempdb is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @MaxDOP < 0 OR @MaxDOP > 64 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxDOP is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @FillFactor <= 0 OR @FillFactor > 100 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @FillFactor is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @PadIndex NOT IN('Y','N') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @PadIndex is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @DataCompression NOT IN('NONE', 'PAGE', 'ROW') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @DataCompression is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @WaitAtLowPriorityMaxDuration < 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16, 1) + 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]) + VALUES('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]) + VALUES('The value for the parameter @Resumable is not supported.', 16, 1) + END + + IF @Resumable = 'Y' AND @SortInTempdb = 'Y' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 2) + END + + ---------------------------------------------------------------------------------------------------- + + IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('The value for the parameter @OnlyModifiedStatistics is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('The value for the parameter @StatisticsSample is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @StatisticsPersistSample NOT IN('Y','N') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @StatisticsPersistSample is not supported.', 16, 1) + END + + IF @StatisticsPersistSample IS NOT NULL AND @StatisticsSample IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameter @StatisticsPersistSample can only be used together with @StatisticsSample.', 16, 2) + END + + IF @StatisticsPersistSample IS NOT NULL AND @StatisticsResample = 'Y' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3) + END + + IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.03006 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @StatisticsPersistSample is not supported.', 16, 4) + END + + ---------------------------------------------------------------------------------------------------- + + IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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]) + VALUES('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, [State]) + VALUES('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, [State]) + VALUES('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) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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]) + VALUES('The value for the parameter @Indexes is not supported.', 16, 2) + END + + ---------------------------------------------------------------------------------------------------- + + IF @TimeLimit < 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @TimeLimit is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF @Delay < 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @Delay is not supported.', 16, 1) + END + + IF @Delay >= 86400 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @Delay is not supported.', 16, 2) + END + + ---------------------------------------------------------------------------------------------------- + + IF @LockTimeout < 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @LockTimeout is not supported.', 16, 1) + END + + IF @LockTimeout > 86400 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @LockTimeout is not supported.', 16, 2) + END + + ---------------------------------------------------------------------------------------------------- + + IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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, [State]) + VALUES('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') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 1) + END + + IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 2) + END + + ---------------------------------------------------------------------------------------------------- + + IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) + END + + IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 2) + END + + ---------------------------------------------------------------------------------------------------- + + IF LEN(@ExecuteAsUser) > 128 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('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]) + VALUES('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, [State]) + VALUES('The value for the parameter @Execute is not supported.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + + IF EXISTS(SELECT * FROM @Errors) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + --// Check that selected databases and availability groups exist //-- + ---------------------------------------------------------------------------------------------------- + + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) + FROM @SelectedDatabases + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + + IF @ErrorMessage IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + END + + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) + FROM @SelectedIndexes + WHERE DatabaseName NOT LIKE '%[%]%' + AND DatabaseName NOT IN (SELECT DatabaseName FROM @tmpDatabases) + + IF @ErrorMessage IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The following databases in the @Indexes parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + END + + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY AvailabilityGroupName ASC) + FROM @SelectedAvailabilityGroups + WHERE AvailabilityGroupName NOT LIKE '%[%]%' + AND AvailabilityGroupName NOT IN (SELECT AvailabilityGroupName FROM @tmpAvailabilityGroups) + + IF @ErrorMessage IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) + END + + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC) + 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 @ErrorMessage IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) + END + + ---------------------------------------------------------------------------------------------------- + --// Raise errors //-- + ---------------------------------------------------------------------------------------------------- + + DECLARE ErrorCursor CURSOR LOCAL FAST_FORWARD FOR SELECT [Message], Severity, [State] FROM @Errors ORDER BY [ID] ASC + + OPEN ErrorCursor + + FETCH ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState + + WHILE @@FETCH_STATUS = 0 + BEGIN + RAISERROR('%s', @CurrentSeverity, @CurrentState, @CurrentMessage) WITH NOWAIT + RAISERROR(@EmptyLine, 10, 1) WITH NOWAIT + + FETCH NEXT FROM ErrorCursor INTO @CurrentMessage, @CurrentSeverity, @CurrentState + END + + CLOSE ErrorCursor + + DEALLOCATE ErrorCursor + + IF EXISTS (SELECT * FROM @Errors WHERE Severity >= 16) + BEGIN + SET @ReturnCode = 50000 + GOTO Logging + END + + ---------------------------------------------------------------------------------------------------- + --// Update database order //-- + ---------------------------------------------------------------------------------------------------- + + IF @DatabaseOrder IN('DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') + BEGIN + UPDATE tmpDatabases + 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 + + 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 + + ---------------------------------------------------------------------------------------------------- + --// Update the queue //-- + ---------------------------------------------------------------------------------------------------- + + IF @DatabasesInParallel = 'Y' + BEGIN + + BEGIN TRY + + SELECT @QueueID = QueueID + FROM dbo.[Queue] + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @ParametersString + + IF @QueueID IS NULL + BEGIN + BEGIN TRANSACTION + + SELECT @QueueID = QueueID + FROM dbo.[Queue] WITH (UPDLOCK, HOLDLOCK) + WHERE SchemaName = @SchemaName + AND ObjectName = @ObjectName + AND [Parameters] = @ParametersString + + IF @QueueID IS NULL + BEGIN + INSERT INTO dbo.[Queue] (SchemaName, ObjectName, [Parameters]) + VALUES(@SchemaName, @ObjectName, @ParametersString) + + SET @QueueID = SCOPE_IDENTITY() + END + + COMMIT TRANSACTION + END + + BEGIN TRANSACTION + + UPDATE [Queue] + 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) + 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 COLLATE DATABASE_DEFAULT = 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 COLLATE DATABASE_DEFAULT AND Selected = 1) + + UPDATE QueueDatabase + SET DatabaseOrder = tmpDatabases.[Order] + FROM dbo.QueueDatabase QueueDatabase + INNER JOIN @tmpDatabases tmpDatabases ON QueueDatabase.DatabaseName COLLATE DATABASE_DEFAULT = tmpDatabases.DatabaseName + WHERE QueueID = @QueueID + 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(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + SET @ReturnCode = ERROR_NUMBER() + GOTO Logging + END CATCH + + END + + ---------------------------------------------------------------------------------------------------- + --// Execute commands //-- + ---------------------------------------------------------------------------------------------------- + + WHILE (1 = 1) + BEGIN -- Start of database loop + + IF @DatabasesInParallel = 'Y' + 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 = SYSDATETIME(), + 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 + BREAK + END + + SET @CurrentDatabase_sp_executesql = QUOTENAME(@CurrentDatabaseName) + '.sys.sp_executesql' + + BEGIN + SET @DatabaseMessage = 'Date and time: ' + CONVERT(nvarchar(max),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, + @CurrentInStandby = is_in_standby, + @CurrentRecoveryModel = recovery_model_desc + 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 @IsHadrEnabled = 1 + BEGIN + SELECT @CurrentAvailabilityGroupReplicaID = 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 @CurrentAvailabilityGroupID = group_id + FROM sys.availability_replicas + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + + SELECT @CurrentAvailabilityGroupRole = role_desc + FROM sys.dm_hadr_availability_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + + SELECT @CurrentAvailabilityGroup = [name] + FROM sys.availability_groups + WHERE group_id = @CurrentAvailabilityGroupID + END + + IF @IsHadrEnabled = 1 AND @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SELECT @CurrentDistributedAvailabilityGroup = availability_groups.[name], + @CurrentDistributedAvailabilityGroupReplicaID = availability_replicas.replica_id + FROM sys.availability_groups availability_groups + INNER JOIN sys.availability_replicas availability_replicas ON availability_groups.group_id = availability_replicas.group_id + INNER JOIN sys.availability_groups availability_groups_local ON availability_replicas.replica_server_name = availability_groups_local.[name] + WHERE availability_groups.is_distributed = 1 + AND availability_groups_local.group_id = @CurrentAvailabilityGroupID + + SELECT @CurrentDistributedAvailabilityGroupRole = dm_hadr_availability_replica_states.role_desc + FROM sys.dm_hadr_availability_replica_states dm_hadr_availability_replica_states + WHERE dm_hadr_availability_replica_states.replica_id = @CurrentDistributedAvailabilityGroupReplicaID + END + + IF @EngineEdition <> 5 + BEGIN + SELECT @CurrentDatabaseMirroringRole = UPPER(mirroring_role_desc) + FROM sys.database_mirroring database_mirroring + INNER JOIN sys.databases databases ON database_mirroring.database_id = databases.database_id + WHERE databases.[name] = @CurrentDatabaseName + END + + IF @CurrentAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + + IF @CurrentDistributedAvailabilityGroup IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Distributed availability group: ' + ISNULL(@CurrentDistributedAvailabilityGroup,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Distributed availability group role: ' + ISNULL(@CurrentDistributedAvailabilityGroupRole,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Replica role in distributed availability group: ' + CASE WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Global primary' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'PRIMARY' THEN 'Forwarder' + WHEN @CurrentDistributedAvailabilityGroupRole = 'SECONDARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in secondary availability group' + WHEN @CurrentDistributedAvailabilityGroupRole = 'PRIMARY' AND @CurrentAvailabilityGroupRole = 'SECONDARY' THEN 'Secondary replica in primary availability group' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + + IF @CurrentDatabaseMirroringRole IS NOT NULL + BEGIN + SET @DatabaseMessage = 'Database mirroring role: ' + @CurrentDatabaseMirroringRole + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + END + + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + IF @ExecuteAsUser IS NOT NULL + AND @CurrentDatabaseState = 'ONLINE' + AND NOT (@CurrentUserAccess = 'SINGLE_USER') + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) + AND NOT (@AmazonRDS = 1 AND @CurrentDatabaseName = 'rdsadmin') + 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 + + 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 + SET @Error = @@ERROR + SET @ReturnCode = @Error + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + + IF @CurrentDatabaseState = 'ONLINE' + AND NOT (@CurrentUserAccess = 'SINGLE_USER') + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) + AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) + AND NOT (@AmazonRDS = 1 AND @CurrentDatabaseName = 'rdsadmin') + AND NOT (@CurrentIsReadOnly = 1) + AND (@CurrentExecuteAsUserExists = 1 OR @CurrentExecuteAsUserExists IS NULL) + BEGIN + + IF (EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IS NOT NULL) AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + BEGIN + -- Select objects + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT objects.[object_id] AS ObjectID' + + ', objects.[schema_id] AS SchemaID' + + ', schemas.[name] AS SchemaName' + + ', objects.[name] AS ObjectName' + + ', RTRIM(objects.[type]) AS ObjectType' + + ', ISNULL(tables.is_memory_optimized, 0) AS IsMemoryOptimized' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') THEN 'CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 5) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS HasClusteredColumnstore' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') AND @Resumable = 'Y' THEN '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.indexes indexes2 ON index_columns.object_id = indexes2.object_id AND index_columns.index_id = indexes2.index_id WHERE (index_columns.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND columns.is_computed = 1 AND indexes2.[type] = 1 AND index_columns.object_id = objects.object_id) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsClusteredIndexComputed' + + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = objects.object_id AND [type] = 1 AND is_disabled = 1) THEN 1 ELSE 0 END AS IsClusteredIndexDisabled' + + ' 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 (tables.is_external = 0 OR tables.is_external IS NULL)' + + CASE WHEN @MSShippedObjects = 'N' THEN ' AND objects.is_ms_shipped = 0' ELSE '' END + IF @Indexes IS NOT NULL AND EXISTS(SELECT * FROM @SelectedIndexes WHERE Selected = 1) AND NOT EXISTS(SELECT * FROM @SelectedIndexes WHERE Selected = 1 AND DatabaseName = '%' AND SchemaName = '%' AND ObjectName = '%') + BEGIN + SET @CurrentCommand += ' AND EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes WHERE @ParamDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND schemas.[name] LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND objects.[name] LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND SelectedIndexes.Selected = 1)' + END + IF @Indexes IS NOT NULL AND EXISTS(SELECT * FROM @SelectedIndexes WHERE Selected = 0 AND IndexName = '%') + BEGIN + SET @CurrentCommand += ' AND NOT EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes WHERE @ParamDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND schemas.[name] LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND objects.[name] LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,''['',''[[]''),''_'',''[_]'') COLLATE ' + @Collation + ' AND SelectedIndexes.IndexName = ''%'' AND SelectedIndexes.Selected = 0)' + END + + INSERT INTO #Objects (ObjectID, SchemaID, SchemaName, ObjectName, ObjectType, IsMemoryOptimized, HasClusteredColumnstore, IsClusteredIndexComputed, IsClusteredIndexDisabled) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max)', @ParamDatabaseName = @CurrentDatabaseName + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select indexes + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT indexes.[object_id] AS ObjectID' + + ', indexes.index_id AS IndexID' + + ', indexes.[name] AS IndexName' + + ', indexes.[type] AS IndexType' + + ', indexes.data_space_id AS DataSpaceID' + + ', indexes.allow_page_locks AS AllowPageLocks' + + ', indexes.has_filter AS HasFilter' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') THEN '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] = indexes.object_id AND types.name IN(''image'',''text'',''ntext'')) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsImageText' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') THEN 'CASE WHEN indexes.[type] = 1 AND EXISTS(SELECT * FROM sys.columns columns WHERE columns.[object_id] = indexes.object_id AND columns.is_filestream = 1) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsFileStream' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') AND (@Version >= 16 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) THEN 'CASE WHEN EXISTS(SELECT * FROM sys.index_columns index_columns WHERE index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND index_columns.column_store_order_ordinal = 1) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsColumnstoreOrdered' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') AND @Resumable = 'Y' THEN '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 OR index_columns.is_included_column = 1) 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' ELSE 'NULL' END + ' AS IsComputed' + + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') AND @Resumable = 'Y' THEN '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.key_ordinal > 0 OR index_columns.partition_ordinal > 0) AND index_columns.[object_id] = indexes.[object_id] AND index_columns.index_id = indexes.index_id AND types.[name] = ''timestamp'') THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsTimestamp' + + ' FROM sys.indexes indexes' + + ' INNER JOIN #Objects Objects ON indexes.[object_id] = Objects.ObjectID' + + ' AND indexes.[type] IN(1,2,3,4,5,6,7)' + + ' AND indexes.is_disabled = 0' + + ' AND indexes.is_hypothetical = 0' + + INSERT INTO #Indexes (ObjectID, IndexID, IndexName, IndexType, DataSpaceID, AllowPageLocks, HasFilter, IsImageText, IsFileStream, IsColumnstoreOrdered, IsComputed, IsTimestamp) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select statistics + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT stats.[object_id] AS ObjectID' + + ', stats.stats_id AS StatisticsID' + + ', stats.name AS StatisticsName' + + ', stats.no_recompute AS NoRecompute' + + ', stats.is_incremental AS IsIncremental' + + ', CASE WHEN EXISTS(SELECT * FROM sys.indexes indexes WHERE indexes.[object_id] = stats.[object_id] AND indexes.index_id = stats.stats_id) THEN 1 ELSE 0 END AS IsIndex' + + ' FROM sys.stats stats' + + ' INNER JOIN #Objects Objects ON stats.[object_id] = Objects.ObjectID' + + INSERT INTO #Stats (ObjectID, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, IsIndex) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select paused resumable index operations + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT index_resumable_operations.object_id AS ObjectID' + + ', index_resumable_operations.index_id AS IndexID' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'index_resumable_operations.partition_number AS PartitionNumber' WHEN @PartitionLevel = 'N' THEN 'NULL AS PartitionNumber' END + + ' FROM sys.index_resumable_operations index_resumable_operations' + + ' WHERE index_resumable_operations.state_desc = ''PAUSED''' + + INSERT INTO @tmpResumableOperations (ObjectID, IndexID, PartitionNumber) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + IF EXISTS(SELECT * FROM @ActionsPreferred) OR @UpdateStatistics IN('ALL','INDEX') + BEGIN + -- Check if there are read-only filegroups in the database + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT @ParamDatabaseHasReadOnlyFileGroup = CASE WHEN EXISTS(SELECT * FROM sys.filegroups filegroups WHERE filegroups.is_read_only = 1) THEN 1 ELSE 0 END' + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseHasReadOnlyFileGroup bit OUTPUT', @ParamDatabaseHasReadOnlyFileGroup = @CurrentDatabaseHasReadOnlyFileGroup OUTPUT + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select clustered, nonclustered and hash indexes + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Indexes.IndexID AS IndexID' + + ', Indexes.IndexName AS IndexName' + + ', Indexes.IndexType AS IndexType' + + ', Indexes.AllowPageLocks AS AllowPageLocks' + + ', Indexes.HasFilter AS HasFilter' + + ', Indexes.IsImageText AS IsImageText' + + ', Indexes.IsFileStream AS IsFileStream' + + ', Objects.HasClusteredColumnstore AS HasClusteredColumnstore' + + ', Indexes.IsColumnstoreOrdered AS IsColumnstoreOrdered' + + ', Indexes.IsComputed AS IsComputed' + + ', Objects.IsClusteredIndexComputed AS IsClusteredIndexComputed' + + ', Indexes.IsTimestamp AS IsTimestamp' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON Indexes.DataSpaceID = 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.ObjectID AND indexes2.[index_id] = Indexes.IndexID' + 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.DataSpaceID = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND Indexes.ObjectID = indexes2.[object_id] AND Indexes.IndexID = indexes2.index_id) THEN 1' + + ' WHEN Indexes.IndexType = 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.ObjectID) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ', 0 AS ResumableIndexOperation' + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.StatisticsID AS StatisticsID' ELSE ', NULL AS StatisticsID' END + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.StatisticsName AS StatisticsName' ELSE ', NULL AS StatisticsName' END + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.[NoRecompute] AS NoRecompute' ELSE ', NULL AS NoRecompute' END + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.IsIncremental AS IsIncremental' ELSE ', NULL AS IsIncremental' END + + ', ' + 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' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + + ' FROM #Indexes Indexes' + + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ' INNER JOIN #Stats Stats ON Indexes.ObjectID = Stats.ObjectID AND Indexes.IndexID = Stats.StatisticsID' ELSE '' END + IF @PartitionLevel = 'Y' + BEGIN + SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON Indexes.ObjectID = partitions.[object_id] AND Indexes.IndexID = partitions.index_id' + END + IF @PartitionLevel = 'Y' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) + BEGIN + SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.object_id = dm_db_partition_stats.object_id AND partitions.index_id = dm_db_partition_stats.index_id AND partitions.partition_number = dm_db_partition_stats.partition_number' + END + SET @CurrentCommand += ' WHERE Objects.ObjectType IN(''U'',''V'')' + + ' AND Indexes.IndexType IN(1,2,7)' + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select XML and spatial indexes + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Indexes.IndexID AS IndexID' + + ', Indexes.IndexName AS IndexName' + + ', Indexes.IndexType AS IndexType' + + ', Indexes.AllowPageLocks AS AllowPageLocks' + + ', Indexes.HasFilter AS HasFilter' + + ', Indexes.IsImageText AS IsImageText' + + ', Indexes.IsFileStream AS IsFileStream' + + ', Objects.HasClusteredColumnstore AS HasClusteredColumnstore' + + ', Indexes.IsColumnstoreOrdered AS IsColumnstoreOrdered' + + ', Indexes.IsComputed AS IsComputed' + + ', Objects.IsClusteredIndexComputed AS IsClusteredIndexComputed' + + ', Indexes.IsTimestamp AS IsTimestamp' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON Indexes.DataSpaceID = 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.ObjectID AND indexes2.[index_id] = Indexes.IndexID) THEN 1' + + ' WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.filegroups filegroups ON Indexes.DataSpaceID = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND Indexes.ObjectID = indexes2.[object_id] AND Indexes.IndexID = indexes2.index_id) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ', 0 AS ResumableIndexOperation' + + ' FROM #Indexes Indexes' + + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + + ' WHERE Objects.ObjectType = ''U''' + + ' AND Indexes.IndexType IN(3,4)' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select columnstore indexes + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Indexes.IndexID AS IndexID' + + ', Indexes.IndexName AS IndexName' + + ', Indexes.IndexType AS IndexType' + + ', Indexes.AllowPageLocks AS AllowPageLocks' + + ', Indexes.HasFilter AS HasFilter' + + ', Indexes.IsImageText AS IsImageText' + + ', Indexes.IsFileStream AS IsFileStream' + + ', Objects.HasClusteredColumnstore AS HasClusteredColumnstore' + + ', Indexes.IsColumnstoreOrdered AS IsColumnstoreOrdered' + + ', Indexes.IsComputed AS IsComputed' + + ', Objects.IsClusteredIndexComputed AS IsClusteredIndexComputed' + + ', Indexes.IsTimestamp AS IsTimestamp' + + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON Indexes.DataSpaceID = 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.ObjectID AND indexes2.[index_id] = Indexes.IndexID' + 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.DataSpaceID = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND Indexes.ObjectID = indexes2.[object_id] AND Indexes.IndexID = indexes2.index_id) THEN 1' + + ' WHEN Indexes.IndexType = 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.ObjectID) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + + ', 0 AS ResumableIndexOperation' + + ', NULL AS StatisticsID' + + ', NULL AS StatisticsName' + + ', NULL AS NoRecompute' + + ', NULL 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' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + + ' FROM #Indexes Indexes' + + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + IF @PartitionLevel = 'Y' + BEGIN + SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON Indexes.ObjectID = partitions.[object_id] AND Indexes.IndexID = partitions.index_id' + END + IF @PartitionLevel = 'Y' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) + BEGIN + SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.object_id = dm_db_partition_stats.object_id AND partitions.index_id = dm_db_partition_stats.index_id AND partitions.partition_number = dm_db_partition_stats.partition_number' + END + SET @CurrentCommand += ' WHERE Objects.ObjectType = ''U''' + + ' AND Indexes.IndexType IN(5,6)' + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + END + + IF @UpdateStatistics IN('ALL','COLUMNS') + BEGIN + -- Select non-incremental column level statistics + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Stats.StatisticsID AS StatisticsID' + + ', Stats.StatisticsName AS StatisticsName' + + ', Stats.[NoRecompute] AS NoRecompute' + + ', Stats.IsIncremental AS IsIncremental' + + ', NULL AS PartitionNumber' + + ' FROM #Stats Stats' + + ' INNER JOIN #Objects Objects ON Stats.ObjectID = Objects.ObjectID' + + ' WHERE Stats.IsIndex = 0' + + ' AND Stats.IsIncremental = 0' + + ' AND Objects.IsClusteredIndexDisabled = 0' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + + -- Select incremental column level statistics + SET @CurrentCommand = 'SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;' + + ' SELECT Objects.SchemaID AS SchemaID' + + ', Objects.SchemaName AS SchemaName' + + ', Objects.ObjectID AS ObjectID' + + ', Objects.ObjectName AS ObjectName' + + ', Objects.ObjectType AS ObjectType' + + ', Objects.IsMemoryOptimized AS IsMemoryOptimized' + + ', Stats.StatisticsID AS StatisticsID' + + ', Stats.StatisticsName AS StatisticsName' + + ', Stats.[NoRecompute] AS NoRecompute' + + ', Stats.IsIncremental AS IsIncremental' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_number' ELSE 'NULL' END + ' AS PartitionNumber' + + ' FROM #Stats Stats' + + ' INNER JOIN #Objects Objects ON Stats.ObjectID = Objects.ObjectID' + IF @PartitionLevel = 'Y' + BEGIN + SET @CurrentCommand += ' INNER JOIN sys.partitions partitions ON partitions.[object_id] = Stats.ObjectID AND partitions.index_id IN (0, 1)' + END + SET @CurrentCommand += ' WHERE Objects.IsMemoryOptimized = 0' + + ' AND Stats.IsIndex = 0' + + ' AND Stats.IsIncremental = 1' + + ' AND Objects.IsClusteredIndexDisabled = 0' + + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand + SET @Error = @@ERROR + IF @Error <> 0 + BEGIN + SET @ReturnCode = @Error + END + END + + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.ResumableIndexOperation = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @tmpResumableOperations tmpResumableOperations ON tmpIndexesStatistics.ObjectID = tmpResumableOperations.ObjectID AND tmpIndexesStatistics.IndexID = tmpResumableOperations.IndexID AND (tmpIndexesStatistics.PartitionNumber = tmpResumableOperations.PartitionNumber OR tmpResumableOperations.PartitionNumber IS NULL) + OPTION (RECOMPILE) + + IF @PartitionLevel = 'Y' + BEGIN + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.PartitionCount = PartitionCounts.PartitionCount + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN (SELECT ObjectID, IndexID, COUNT(*) AS PartitionCount FROM @tmpIndexesStatistics WHERE IndexID IS NOT NULL GROUP BY ObjectID, IndexID) PartitionCounts ON tmpIndexesStatistics.ObjectID = PartitionCounts.ObjectID AND tmpIndexesStatistics.IndexID = PartitionCounts.IndexID + OPTION (RECOMPILE) + END + + IF @Indexes IS NULL + BEGIN + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.Selected = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + END + ELSE + BEGIN + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.Selected = SelectedIndexes.Selected + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @SelectedIndexes SelectedIndexes + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(REPLACE(SelectedIndexes.IndexName,'[','[[]'),'_','[_]') + WHERE SelectedIndexes.Selected = 1 + + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.Selected = SelectedIndexes.Selected + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @SelectedIndexes SelectedIndexes + ON @CurrentDatabaseName LIKE REPLACE(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(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(REPLACE(SelectedIndexes.DatabaseName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.SchemaName LIKE REPLACE(REPLACE(SelectedIndexes.SchemaName,'[','[[]'),'_','[_]') AND tmpIndexesStatistics.ObjectName LIKE REPLACE(REPLACE(SelectedIndexes.ObjectName,'[','[[]'),'_','[_]') AND COALESCE(tmpIndexesStatistics.IndexName,tmpIndexesStatistics.StatisticsName) LIKE REPLACE(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) + END; + + WITH tmpIndexesStatistics AS ( + 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 + ) + UPDATE tmpIndexesStatistics + SET [Order] = RowNumber + + SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName' + + ' FROM sys.objects objects' + + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' + + ' WHERE objects.[type] IN(''U'',''V'')' + + ' AND EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes' + + ' WHERE SelectedIndexes.DatabaseName = @ParamDatabaseName' + + ' AND SelectedIndexes.SchemaName NOT LIKE ''%[%]%''' + + ' AND SelectedIndexes.ObjectName NOT LIKE ''%[%]%''' + + ' AND schemas.[name] = SelectedIndexes.SchemaName COLLATE ' + @Collation + + ' AND objects.[name] = SelectedIndexes.ObjectName COLLATE ' + @Collation + ')' + + INSERT INTO #ExistingObjects (SchemaName, ObjectName) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max)', @ParamDatabaseName = @CurrentDatabaseName + + SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName, [Names].[name] AS IndexName' + + ' FROM sys.objects objects' + + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' + + ' CROSS APPLY (SELECT indexes.[name] FROM sys.indexes indexes WHERE indexes.[object_id] = objects.[object_id] AND indexes.[type] <> 0' + + ' UNION SELECT stats.[name] FROM sys.stats stats WHERE stats.[object_id] = objects.[object_id]) [Names]' + + ' WHERE objects.[type] IN(''U'',''V'')' + + ' AND EXISTS(SELECT * FROM #SelectedIndexes SelectedIndexes' + + ' WHERE SelectedIndexes.DatabaseName = @ParamDatabaseName' + + ' AND SelectedIndexes.SchemaName NOT LIKE ''%[%]%''' + + ' AND SelectedIndexes.ObjectName NOT LIKE ''%[%]%''' + + ' AND SelectedIndexes.IndexName NOT LIKE ''%[%]%''' + + ' AND schemas.[name] = SelectedIndexes.SchemaName COLLATE ' + @Collation + + ' AND objects.[name] = SelectedIndexes.ObjectName COLLATE ' + @Collation + + ' AND [Names].[name] = SelectedIndexes.IndexName COLLATE ' + @Collation + ')' + + INSERT INTO #ExistingIndexes (SchemaName, ObjectName, IndexName) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max)', @ParamDatabaseName = @CurrentDatabaseName + + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC, SchemaName ASC, ObjectName ASC) + FROM @SelectedIndexes SelectedIndexes + WHERE DatabaseName = @CurrentDatabaseName + AND SchemaName NOT LIKE '%[%]%' + AND ObjectName NOT LIKE '%[%]%' + AND IndexName LIKE '%[%]%' + AND NOT EXISTS (SELECT * FROM #ExistingObjects WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName) + + IF @ErrorMessage IS NOT NULL + BEGIN + SET @ErrorMessage = 'The following objects in the @Indexes parameter do not exist: ' + @ErrorMessage + '.' + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + + SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)) + '.' + QUOTENAME(SchemaName) + '.' + QUOTENAME(ObjectName) + '.' + QUOTENAME(IndexName), ', ') + WITHIN GROUP (ORDER BY DatabaseName ASC, SchemaName ASC, ObjectName ASC, IndexName ASC) + FROM @SelectedIndexes SelectedIndexes + WHERE DatabaseName = @CurrentDatabaseName + AND SchemaName NOT LIKE '%[%]%' + AND ObjectName NOT LIKE '%[%]%' + AND IndexName NOT LIKE '%[%]%' + AND NOT EXISTS (SELECT * FROM #ExistingIndexes WHERE SchemaName = SelectedIndexes.SchemaName AND ObjectName = SelectedIndexes.ObjectName AND IndexName = SelectedIndexes.IndexName) + + IF @ErrorMessage IS NOT NULL + BEGIN + SET @ErrorMessage = 'The following indexes in the @Indexes parameter do not exist: ' + @ErrorMessage + '.' + RAISERROR('%s',10,1,@ErrorMessage) WITH NOWAIT + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + END + + WHILE (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + BEGIN + SELECT TOP 1 @CurrentIxID = ID, + @CurrentIxOrder = [Order], + @CurrentSchemaID = SchemaID, + @CurrentSchemaName = SchemaName, + @CurrentObjectID = ObjectID, + @CurrentObjectName = ObjectName, + @CurrentObjectType = ObjectType, + @CurrentIsMemoryOptimized = IsMemoryOptimized, + @CurrentIndexID = IndexID, + @CurrentIndexName = IndexName, + @CurrentIndexType = IndexType, + @CurrentAllowPageLocks = AllowPageLocks, + @CurrentHasFilter = HasFilter, + @CurrentIsImageText = IsImageText, + @CurrentIsFileStream = IsFileStream, + @CurrentHasClusteredColumnstore = HasClusteredColumnstore, + @CurrentIsColumnstoreOrdered = IsColumnstoreOrdered, + @CurrentIsComputed = IsComputed, + @CurrentIsClusteredIndexComputed = IsClusteredIndexComputed, + @CurrentIsTimestamp = IsTimestamp, + @CurrentOnReadOnlyFileGroup = OnReadOnlyFileGroup, + @CurrentResumableIndexOperation = ResumableIndexOperation, + @CurrentStatisticsID = StatisticsID, + @CurrentStatisticsName = StatisticsName, + @CurrentNoRecompute = [NoRecompute], + @CurrentIsIncremental = IsIncremental, + @CurrentPartitionID = PartitionID, + @CurrentPartitionNumber = PartitionNumber, + @CurrentPartitionCount = PartitionCount, + @CurrentInRowDataPageCount = InRowDataPageCount + FROM @tmpIndexesStatistics + WHERE Selected = 1 + AND Completed = 0 + ORDER BY [Order] 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 + + IF ((@CurrentInRowDataPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (@CurrentInRowDataPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL)) OR @CurrentInRowDataPageCount IS NULL + BEGIN + -- Does the index exist? + IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) + BEGIN + SET @CurrentCommand = '' + + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + 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 = @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 + SET @CurrentIndexExists = 0 + GOTO NoAction + END + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + + GOTO NoAction + END CATCH + 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 @CurrentCommand = '' + + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + IF @CurrentPartitionNumber IS NULL + BEGIN + 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, NULL, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + END + ELSE + BEGIN + SET @CurrentCommand += 'SELECT @ParamFragmentationLevel = avg_fragmentation_in_percent, @ParamPageCount = 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' + END + + BEGIN TRY + 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(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + + GOTO NoAction + END CATCH + END + + -- Select fragmentation group + IF @CurrentIndexID IS NOT NULL AND @CurrentOnReadOnlyFileGroup = 0 AND EXISTS(SELECT * FROM @ActionsPreferred) + BEGIN + SET @CurrentFragmentationGroup = CASE + WHEN @CurrentFragmentationLevel >= @FragmentationLevel2 THEN 'High' + WHEN @CurrentFragmentationLevel >= @FragmentationLevel1 AND @CurrentFragmentationLevel < @FragmentationLevel2 THEN 'Medium' + WHEN @CurrentFragmentationLevel < @FragmentationLevel1 THEN 'Low' + END + END + + -- Which actions are allowed? + IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) + BEGIN + IF NOT (@CurrentOnReadOnlyFileGroup = 1) + AND NOT (@CurrentIsMemoryOptimized = 1) + AND NOT (@CurrentAllowPageLocks = 0) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REORGANIZE') + END + IF NOT (@CurrentOnReadOnlyFileGroup = 1) + AND NOT (@CurrentIsMemoryOptimized = 1) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REBUILD_OFFLINE') + END + IF @EngineEdition IN (3, 5, 8) + AND NOT (@CurrentOnReadOnlyFileGroup = 1) + AND NOT (@CurrentIsMemoryOptimized = 1) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1 AND @CurrentIsImageText IS NOT NULL) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1 AND @CurrentIsFileStream IS NOT NULL) + AND NOT (@CurrentIndexType = 3) + AND NOT (@CurrentIndexType = 4) + AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @CurrentHasClusteredColumnstore IS NOT NULL AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND @CurrentIsColumnstoreOrdered IS NOT NULL AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REBUILD_ONLINE') + END + END + + -- Decide action + IF @CurrentIndexID IS NOT NULL + 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 + SELECT @CurrentAction = [Action] + FROM @ActionsPreferred + WHERE FragmentationGroup = @CurrentFragmentationGroup + AND [Priority] = (SELECT MIN([Priority]) + FROM @ActionsPreferred + WHERE FragmentationGroup = @CurrentFragmentationGroup + AND [Action] IN (SELECT [Action] FROM @CurrentActionsAllowed)) + END + ELSE + BEGIN + SELECT @CurrentAction = [Action] + FROM @ActionsPreferred + WHERE [Priority] = (SELECT MIN([Priority]) + FROM @ActionsPreferred + WHERE [Action] IN (SELECT [Action] FROM @CurrentActionsAllowed)) + END + END + + IF @CurrentResumableIndexOperation = 1 + BEGIN + SET @CurrentAction = 'INDEX_REBUILD_ONLINE' + END + + SET @CurrentMaxDOP = @MaxDOP + + -- Workaround for limitation in SQL Server, http://support.microsoft.com/kb/2292737 + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentIndexType IN (1, 2) AND @CurrentAllowPageLocks = 0 + BEGIN + SET @CurrentMaxDOP = 1 + END + END + + -- Create index comment + IF @CurrentAction 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 @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 + ', ' + IF @CurrentIsImageText IS NOT NULL SET @CurrentComment += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsFileStream IS NOT NULL SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentHasClusteredColumnstore IS NOT NULL AND @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsColumnstoreOrdered IS NOT NULL AND @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsComputed IS NOT NULL SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsClusteredIndexComputed IS NOT NULL AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsTimestamp IS NOT NULL SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 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(max)),'N/A') + ', ' + SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar(max)),'N/A') + END + + IF @CurrentAction IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) + BEGIN + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentPageCount AS nvarchar(max)) AS [PageCount], + CAST(@CurrentFragmentationLevel AS nvarchar(max)) AS Fragmentation + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) + END + + IF @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + BEGIN + SET @CurrentDatabaseContext = @CurrentDatabaseName + + SET @CurrentCommandType = 'ALTER_INDEX' + + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + 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(max)) + + 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) + VALUES('SORT_IN_TEMPDB = ON') + END + + 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) + VALUES('SORT_IN_TEMPDB = OFF') + END + + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END) + END + + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 1 AND @WaitAtLowPriorityMaxDuration IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + ')') + END + + IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('ONLINE = OFF') + END + + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentMaxDOP IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) + 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) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max))) + END + + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END) + END + + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,4) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('DATA_COMPRESSION = ' + @DataCompression) + END + + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES(CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL) THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END) + END + + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL)) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max))) + END + + IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('LOB_COMPACTION = ON') + END + + IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'N' + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('LOB_COMPACTION = OFF') + END + + IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) + BEGIN + SELECT @CurrentCommand += ' WITH (' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) + ')' + FROM @CurrentAlterIndexWithClauseArguments + END + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 + + IF @Delay > 0 + BEGIN + SET @CurrentDelay = DATEADD(ss,@Delay,'1900-01-01') + WAITFOR DELAY @CurrentDelay + END + END + + SET @CurrentMaxDOP = @MaxDOP + + -- Should the statistics be updated? - Pre checks and final decision + IF @CurrentStatisticsID IS NOT NULL + AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) + AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) + BEGIN + -- Does the statistics exist? + SET @CurrentCommand = '' + + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + 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 = @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 + SET @CurrentStatisticsExists = 0 + GOTO NoAction + END + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + + GOTO NoAction + END CATCH + + -- Check non-incremental statistics properties + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND NOT (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1) + BEGIN + SET @CurrentCommand = '' + + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + SET @CurrentCommand += 'SELECT @ParamRowCount = [rows], @ParamModificationCounter = modification_counter FROM sys.dm_db_stats_properties (@ParamObjectID, @ParamStatisticsID)' + + BEGIN TRY + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamStatisticsID int, @ParamRowCount bigint OUTPUT, @ParamModificationCounter bigint OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID, @ParamRowCount = @CurrentRowCount OUTPUT, @ParamModificationCounter = @CurrentModificationCounter OUTPUT + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + + GOTO NoAction + END CATCH + END + + -- Check incremental statistics properties + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 + AND NOT EXISTS (SELECT * FROM @IncrementalStatsProperties WHERE ObjectID = @CurrentObjectID AND StatisticsID = @CurrentStatisticsID) + BEGIN + SET @CurrentCommand = '' + + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + BEGIN + SET @CurrentCommand += 'SELECT object_id, stats_id, partition_number, [rows], modification_counter FROM sys.dm_db_incremental_stats_properties (@ParamObjectID, @ParamStatisticsID)' + END + + BEGIN TRY + INSERT INTO @IncrementalStatsProperties (ObjectID, StatisticsID, PartitionNumber, [Rows], ModificationCounter) + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamStatisticsID int', @ParamObjectID = @CurrentObjectID, @ParamStatisticsID = @CurrentStatisticsID + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + + GOTO NoAction + END CATCH + END + + SELECT @CurrentRowCount = [Rows], + @CurrentModificationCounter = [ModificationCounter] + FROM @IncrementalStatsProperties + WHERE ObjectID = @CurrentObjectID + AND StatisticsID = @CurrentStatisticsID + AND PartitionNumber = @CurrentPartitionNumber + + -- Check partition statistics + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentModificationCounter IS NULL + BEGIN + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 + BEGIN + SET @CurrentCommand += 'SELECT @ParamObjectHasRows = CASE WHEN EXISTS (SELECT * FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id IN (0,1) AND partition_number = @ParamPartitionNumber AND row_count > 0) THEN 1 ELSE 0 END' + END + ELSE + BEGIN + SET @CurrentCommand += 'SELECT @ParamObjectHasRows = CASE WHEN EXISTS (SELECT * FROM sys.dm_db_partition_stats WHERE [object_id] = @ParamObjectID AND index_id IN (0,1) AND row_count > 0) THEN 1 ELSE 0 END' + END + + BEGIN TRY + EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamObjectID int, @ParamPartitionNumber int, @ParamObjectHasRows bit OUTPUT', @ParamObjectID = @CurrentObjectID, @ParamPartitionNumber = @CurrentPartitionNumber, @ParamObjectHasRows = @CurrentObjectHasRows OUTPUT + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + ISNULL(ERROR_MESSAGE(),'') + CASE WHEN ERROR_NUMBER() = 1222 THEN ' The object ' + QUOTENAME(@CurrentDatabaseName) + '.' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' is locked. The row count 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 + SET @ReturnCode = ERROR_NUMBER() + END + GOTO NoAction + END CATCH + END + + -- Update statistics? + IF ((@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 ((@CurrentIndexType IN (1,2) OR @CurrentIndexID IS NULL) AND @CurrentModificationCounter IS NULL AND @CurrentObjectHasRows = 1)) + BEGIN + SET @CurrentUpdateStatistics = 'Y' + END + ELSE + BEGIN + SET @CurrentUpdateStatistics = 'N' + END + END + + SET @CurrentStatisticsSample = @StatisticsSample + SET @CurrentStatisticsPersistSample = @StatisticsPersistSample + SET @CurrentStatisticsResample = @StatisticsResample + + -- Incremental statistics only supports RESAMPLE + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 + BEGIN + SET @CurrentStatisticsSample = NULL + SET @CurrentStatisticsPersistSample = NULL + SET @CurrentStatisticsResample = 'Y' + END + + -- Create statistics comment + IF @CurrentUpdateStatistics = 'Y' + BEGIN + SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'StatisticsType: ' + 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 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar(max)),'N/A') + ', ' + SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar(max)),'N/A') + END + + IF @CurrentUpdateStatistics = 'Y' AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) + BEGIN + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentRowCount AS nvarchar(max)) AS [RowCount], + CAST(@CurrentModificationCounter AS nvarchar(max)) AS ModificationCounter + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) + END + ELSE + BEGIN + SET @CurrentExtendedInfo = NULL + END + + IF @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) + BEGIN + SET @CurrentDatabaseContext = @CurrentDatabaseName + + SET @CurrentCommandType = 'UPDATE_STATISTICS' + + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + SET @CurrentCommand += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) + + IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) + END + + IF @CurrentStatisticsSample = 100 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('FULLSCAN') + END + + IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT') + END + + IF @CurrentStatisticsPersistSample = 'Y' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('PERSIST_SAMPLE_PERCENT = ON') + END + + IF @CurrentStatisticsPersistSample = 'N' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('PERSIST_SAMPLE_PERCENT = OFF') + END + + IF @CurrentNoRecompute = 1 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('NORECOMPUTE') + END + + IF @CurrentStatisticsResample = 'Y' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('RESAMPLE') + END + + IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) + BEGIN + SELECT @CurrentCommand += ' WITH ' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) + FROM @CurrentUpdateStatisticsWithClauseArguments + END + + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @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 + END + + NoAction: + + -- Update that the index or statistics is completed + UPDATE @tmpIndexesStatistics + SET Completed = 1 + WHERE Selected = 1 + AND Completed = 0 + AND [Order] = @CurrentIxOrder + AND ID = @CurrentIxID + + -- Update that statistics on remaining partitions are completed where no update is needed + IF (NOT EXISTS(SELECT * FROM @ActionsPreferred) OR @CurrentIndexID IS NULL) AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentStatisticsID IS NOT NULL + BEGIN + UPDATE tmpIndexesStatistics + SET Completed = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @IncrementalStatsProperties IncrementalStatsProperties ON tmpIndexesStatistics.ObjectID = IncrementalStatsProperties.ObjectID AND tmpIndexesStatistics.StatisticsID = IncrementalStatsProperties.StatisticsID AND tmpIndexesStatistics.PartitionNumber = IncrementalStatsProperties.PartitionNumber + WHERE tmpIndexesStatistics.ObjectID = @CurrentObjectID + AND tmpIndexesStatistics.StatisticsID = @CurrentStatisticsID + AND tmpIndexesStatistics.Selected = 1 + AND tmpIndexesStatistics.Completed = 0 + AND IncrementalStatsProperties.ModificationCounter IS NOT NULL + AND ((@OnlyModifiedStatistics = 'Y' AND NOT (IncrementalStatsProperties.ModificationCounter > 0)) + OR (@StatisticsModificationLevel IS NOT NULL AND NOT ((IncrementalStatsProperties.ModificationCounter * 1. / NULLIF(IncrementalStatsProperties.[Rows],0)) * 100 >= @StatisticsModificationLevel OR (IncrementalStatsProperties.ModificationCounter > 0 AND IncrementalStatsProperties.ModificationCounter >= SQRT(IncrementalStatsProperties.[Rows] * 1000))))) + END + + -- Clear variables + SET @CurrentDatabaseContext = NULL + + SET @CurrentCommand = NULL + SET @CurrentCommandOutput = NULL + SET @CurrentCommandType = NULL + SET @CurrentComment = NULL + SET @CurrentExtendedInfo = NULL + + SET @CurrentIxID = NULL + SET @CurrentIxOrder = NULL + SET @CurrentSchemaID = NULL + SET @CurrentSchemaName = NULL + SET @CurrentObjectID = NULL + SET @CurrentObjectName = NULL + SET @CurrentObjectType = NULL + SET @CurrentIsMemoryOptimized = NULL + SET @CurrentIndexID = NULL + SET @CurrentIndexName = NULL + SET @CurrentIndexType = NULL + SET @CurrentStatisticsID = NULL + SET @CurrentStatisticsName = NULL + SET @CurrentPartitionID = NULL + SET @CurrentPartitionNumber = NULL + SET @CurrentPartitionCount = NULL + SET @CurrentInRowDataPageCount = NULL + SET @CurrentIsPartition = NULL + SET @CurrentIndexExists = NULL + SET @CurrentStatisticsExists = NULL + SET @CurrentIsImageText = NULL + SET @CurrentIsFileStream = NULL + SET @CurrentHasClusteredColumnstore = NULL + SET @CurrentIsColumnstoreOrdered = NULL + SET @CurrentIsComputed = NULL + SET @CurrentIsClusteredIndexComputed = NULL + SET @CurrentIsTimestamp = NULL + SET @CurrentAllowPageLocks = NULL + SET @CurrentHasFilter = NULL + SET @CurrentNoRecompute = NULL + SET @CurrentIsIncremental = NULL + SET @CurrentObjectHasRows = NULL + SET @CurrentRowCount = NULL + SET @CurrentModificationCounter = NULL + SET @CurrentOnReadOnlyFileGroup = NULL + SET @CurrentResumableIndexOperation = NULL + SET @CurrentFragmentationLevel = NULL + SET @CurrentPageCount = NULL + SET @CurrentFragmentationGroup = NULL + SET @CurrentAction = NULL + SET @CurrentMaxDOP = NULL + SET @CurrentUpdateStatistics = NULL + SET @CurrentStatisticsSample = NULL + SET @CurrentStatisticsPersistSample = NULL + SET @CurrentStatisticsResample = NULL + + DELETE FROM @CurrentActionsAllowed + DELETE FROM @CurrentAlterIndexWithClauseArguments + DELETE FROM @CurrentUpdateStatisticsWithClauseArguments + + END + + END + + IF @CurrentDatabaseState = 'SUSPECT' + BEGIN + SET @ErrorMessage = 'The database ' + QUOTENAME(@CurrentDatabaseName) + ' is in a SUSPECT state.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + SET @ReturnCode = @Error + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + + -- Update that the database is completed + IF @DatabasesInParallel = 'Y' + BEGIN + UPDATE dbo.QueueDatabase + SET DatabaseEndTime = SYSDATETIME() + 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 + SET @CurrentDatabaseName = NULL + + SET @CurrentDatabase_sp_executesql = NULL + + SET @CurrentExecuteAsUserExists = NULL + SET @CurrentUserAccess = NULL + SET @CurrentIsReadOnly = NULL + SET @CurrentDatabaseState = NULL + SET @CurrentInStandby = NULL + SET @CurrentRecoveryModel = NULL + SET @CurrentDatabaseHasReadOnlyFileGroup = NULL + + SET @CurrentAvailabilityGroupReplicaID = NULL + SET @CurrentAvailabilityGroupID = NULL + SET @CurrentAvailabilityGroup = NULL + SET @CurrentAvailabilityGroupRole = NULL + SET @CurrentDistributedAvailabilityGroup = NULL + SET @CurrentDistributedAvailabilityGroupReplicaID = NULL + SET @CurrentDistributedAvailabilityGroupRole = NULL + + SET @CurrentDatabaseMirroringRole = NULL + + SET @CurrentCommand = NULL + + DELETE FROM @tmpIndexesStatistics + + TRUNCATE TABLE #Objects + TRUNCATE TABLE #Indexes + TRUNCATE TABLE #Stats + TRUNCATE TABLE #ExistingObjects + TRUNCATE TABLE #ExistingIndexes + DELETE FROM @tmpResumableOperations + DELETE FROM @IncrementalStatsProperties + + END -- End of database loop + + ---------------------------------------------------------------------------------------------------- + --// Log completing information //-- + ---------------------------------------------------------------------------------------------------- + + Logging: + SET @EndMessage = 'Date and time: ' + CONVERT(nvarchar(max),SYSDATETIME(),120) + RAISERROR('%s',10,1,@EndMessage) WITH NOWAIT + + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + + IF @ReturnCode <> 0 + BEGIN + RETURN @ReturnCode + END + + ---------------------------------------------------------------------------------------------------- + +END + +GO + diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt new file mode 100644 index 00000000..357bc921 --- /dev/null +++ b/SHA256SUMS.txt @@ -0,0 +1,9 @@ +bf860c678fda70e43e2185273613ee3f8c92eb4d0e7666963a3f7425dd797882 CommandExecute.sql +7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql +8421afa874e8bc790857a00eadb6389463ee1796412509f087f5f6a0b2332e68 DatabaseBackup.sql +203fea2692a49d94e42c20f7721475c515f5f3f6c5023fefd72e42e3086a7fb6 DatabaseIntegrityCheck.sql +30e24387df2443104e1845ef87eb2235be6eafdf3c3bfb378d7240faf68f4457 IndexOptimize.sql +ea4a427ee34cea57d0c9f3e8bbff3646a5a8a59ffed94ec0b336572ec9f5062b MaintenanceSolution.sql +59b7bde837fb9899a1375945c6dba4f5a5215e589f4929cd678ce10dc7ccc5a5 MaintenanceSolutionAzureSQLDatabase.sql +c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql +8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From fd25ddc94c9fc4ec50ff882ab364e34a89a5e31f Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 21 Jul 2026 11:39:36 +0200 Subject: [PATCH 114/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index 6de78bfe..6b7eac96 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -1,6 +1,6 @@ name: Deploy to website -# Uploads the released .sql files to the website over FTPS whenever a release is merged to main. +# Uploads the released files to the website over FTPS whenever a release is merged to main. on: push: @@ -31,8 +31,9 @@ jobs: run: | set -u - # Upload order: components first, MaintenanceSolution.sql last. - FILES="CommandLog.sql Queue.sql QueueDatabase.sql CommandExecute.sql DatabaseBackup.sql DatabaseIntegrityCheck.sql IndexOptimize.sql MaintenanceSolution.sql" + # Upload order: components first, then the installers, SHA256SUMS.txt last + # (the checksums go live only after the files they describe are in place). + FILES="CommandLog.sql Queue.sql QueueDatabase.sql CommandExecute.sql DatabaseBackup.sql DatabaseIntegrityCheck.sql IndexOptimize.sql MaintenanceSolutionAzureSQLDatabase.sql MaintenanceSolution.sql SHA256SUMS.txt" # Explicit FTPS (AUTH TLS) on port 21 SETTINGS="set ftp:ssl-force true; set ftp:ssl-protect-data true; set ssl:verify-certificate true; set net:max-retries 2; set net:timeout 60" @@ -54,7 +55,7 @@ jobs: # Verification: list the files on the server and compare each size, byte for byte, against the file in the repository. verify () { - LISTING=$(run_lftp "cls -s --block-size=1 $REMOTE_DIR/*.sql") || return 1 + LISTING=$(run_lftp "cls -s --block-size=1 $REMOTE_DIR/*.sql $REMOTE_DIR/SHA256SUMS.txt") || return 1 for f in $FILES; do LOCAL=$(stat -c %s "$f") REMOTE=$(printf '%s\n' "$LISTING" | grep "/$f\$" | awk '{print $1}') From d26d27c59ec587ead537af302f428eb17366233e Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 21 Jul 2026 14:43:11 +0200 Subject: [PATCH 115/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 ++++++------ MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 20 insertions(+), 20 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 6176097c..9aad7423 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-21 11:25:14 //-- + --// Version: 2026-07-21 14:38:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 901c39c5..9acfae33 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 11:25:14 //-- + --// Version: 2026-07-21 14:38:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 85d3427a..a25e48a7 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 11:25:14 //-- + --// Version: 2026-07-21 14:38:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index c6cf0477..0ba4ffa3 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 11:25:14 //-- + --// Version: 2026-07-21 14:38:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 409510b3..51bec134 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: 2026-07-21 11:25:14 +Version: 2026-07-21 14:38:46 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 11:25:14 //-- + --// Version: 2026-07-21 14:38:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 11:25:14 //-- + --// Version: 2026-07-21 14:38:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4964,7 +4964,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 11:25:14 //-- + --// Version: 2026-07-21 14:38:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6975,7 +6975,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 11:25:14 //-- + --// Version: 2026-07-21 14:38:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -10047,7 +10047,7 @@ BEGIN INSERT INTO @Jobs ([Name], CommandCmdExec, OutputFileNamePart01) VALUES('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"', + 'powershell.exe -NoProfile -Command "Get-ChildItem -LiteralPath ''' + COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + ''' -Filter ''*_*_*_*.txt'' -File | Where-Object { $_.LastWriteTime.Date -le (Get-Date).Date.AddDays(-30) } | ForEach-Object { Write-Output (''del '' + $_.FullName); Remove-Item -LiteralPath $_.FullName }"', 'OutputFileCleanup') IF @AmazonRDS = 1 diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index ab4c4f38..44fe5be2 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-21 11:25:14 +Version: 2026-07-21 14:38:46 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 11:25:14 //-- + --// Version: 2026-07-21 14:38:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 11:25:14 //-- + --// Version: 2026-07-21 14:38:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2405,7 +2405,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 11:25:14 //-- + --// Version: 2026-07-21 14:38:46 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 357bc921..5b24f549 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -bf860c678fda70e43e2185273613ee3f8c92eb4d0e7666963a3f7425dd797882 CommandExecute.sql +6dd6f958820d4dacec73514410b31e100264bf9484425b3e41c51dc0f66fc107 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -8421afa874e8bc790857a00eadb6389463ee1796412509f087f5f6a0b2332e68 DatabaseBackup.sql -203fea2692a49d94e42c20f7721475c515f5f3f6c5023fefd72e42e3086a7fb6 DatabaseIntegrityCheck.sql -30e24387df2443104e1845ef87eb2235be6eafdf3c3bfb378d7240faf68f4457 IndexOptimize.sql -ea4a427ee34cea57d0c9f3e8bbff3646a5a8a59ffed94ec0b336572ec9f5062b MaintenanceSolution.sql -59b7bde837fb9899a1375945c6dba4f5a5215e589f4929cd678ce10dc7ccc5a5 MaintenanceSolutionAzureSQLDatabase.sql +7a3bea07072b6c25752c312b8c6b9311c3d063de185e7d51c6273881c474aea6 DatabaseBackup.sql +f8775e20574a5349b23e375cd25af3d934b7216c2027d16bd29e0b7e38aaab7e DatabaseIntegrityCheck.sql +b07ec739543324ab7a1d65f5bebb5ac49a7d9822021ae2acb315b288e6638d89 IndexOptimize.sql +28fec783f4c6b0572933913e9be27193a1bfe28da0f3dfcb71a5b1a9fd68c71c MaintenanceSolution.sql +017b5a3b0d49606a1bc33ad4a992e0df12f2d4ace14437157dd8f0b4d39368f3 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From f2452cd8f20bd143064e30ac76ee4156e81bbe33 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 21 Jul 2026 18:21:53 +0200 Subject: [PATCH 116/177] Add files via upload --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index c0655fd6..79a644c7 100644 --- a/README.md +++ b/README.md @@ -9,8 +9,9 @@ ## Getting Started -Download [MaintenanceSolution.sql](/MaintenanceSolution.sql). -This script creates all the objects and jobs that you need. +Download the script for your platform: + - [MaintenanceSolution.sql](/MaintenanceSolution.sql): SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, and Azure SQL Managed Instance. This script creates all the objects and jobs that you need. + - [MaintenanceSolutionAzureSQLDatabase.sql](/MaintenanceSolutionAzureSQLDatabase.sql): Azure SQL Database. This script creates the objects for integrity check and index and statistics maintenance. You can also download the objects as separate scripts: - [DatabaseBackup.sql](/DatabaseBackup.sql): Stored procedure to back up databases @@ -27,7 +28,7 @@ When you update DatabaseBackup, DatabaseIntegrityCheck, or IndexOptimize, you sh You need CommandLog if you are going to use the option to log commands to a table. -Supported versions: SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, Azure SQL Database, and Azure SQL Managed Instance. +You can verify the scripts against the SHA-256 checksums in [SHA256SUMS.txt](/SHA256SUMS.txt). ## Documentation From ca1468f881ce3cc86ed96c7987a20e7268288377 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 21 Jul 2026 18:24:59 +0200 Subject: [PATCH 117/177] Add files via upload --- docs/sql-server-backup.md | 8 ++++++-- docs/sql-server-index-and-statistics-maintenance.md | 9 +++++++-- docs/sql-server-integrity-check.md | 9 +++++++-- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/docs/sql-server-backup.md b/docs/sql-server-backup.md index 4fda75ee..009aa2d0 100644 --- a/docs/sql-server-backup.md +++ b/docs/sql-server-backup.md @@ -4,11 +4,15 @@ This documentation is generated from [ola.hallengren.com/sql-server-backup.html](https://ola.hallengren.com/sql-server-backup.html), which is the primary source. -DatabaseBackup is the SQL Server Maintenance Solution’s stored procedure for backing up databases. DatabaseBackup is supported on SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, and Azure SQL Managed Instance. +DatabaseBackup is the SQL Server Maintenance Solution’s stored procedure for backing up databases. ## Download -Download [MaintenanceSolution.sql](/MaintenanceSolution.sql). This script creates all the objects and jobs that you need. You can also [download](https://github.com/olahallengren/sql-server-maintenance-solution) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). +Download the script for your platform: + +- [MaintenanceSolution.sql](/MaintenanceSolution.sql): SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, and Azure SQL Managed Instance. This script creates all the objects and jobs that you need. + +You can also [download](https://github.com/olahallengren/sql-server-maintenance-solution) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). ## License diff --git a/docs/sql-server-index-and-statistics-maintenance.md b/docs/sql-server-index-and-statistics-maintenance.md index fb0dd971..580c5212 100644 --- a/docs/sql-server-index-and-statistics-maintenance.md +++ b/docs/sql-server-index-and-statistics-maintenance.md @@ -4,11 +4,16 @@ This documentation is generated from [ola.hallengren.com/sql-server-index-and-statistics-maintenance.html](https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html), which is the primary source. -IndexOptimize is the SQL Server Maintenance Solution’s stored procedure for rebuilding and reorganizing indexes and updating statistics. IndexOptimize is supported on SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, Azure SQL Database, and Azure SQL Managed Instance. +IndexOptimize is the SQL Server Maintenance Solution’s stored procedure for rebuilding and reorganizing indexes and updating statistics. ## Download -Download [MaintenanceSolution.sql](/MaintenanceSolution.sql). This script creates all the objects and jobs that you need. You can also [download](https://github.com/olahallengren/sql-server-maintenance-solution) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). +Download the script for your platform: + +- [MaintenanceSolution.sql](/MaintenanceSolution.sql): SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, and Azure SQL Managed Instance. This script creates all the objects and jobs that you need. +- [MaintenanceSolutionAzureSQLDatabase.sql](/MaintenanceSolutionAzureSQLDatabase.sql): Azure SQL Database. This script creates the objects for integrity check and index and statistics maintenance. + +You can also [download](https://github.com/olahallengren/sql-server-maintenance-solution) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). ## License diff --git a/docs/sql-server-integrity-check.md b/docs/sql-server-integrity-check.md index 4973a887..99b179f2 100644 --- a/docs/sql-server-integrity-check.md +++ b/docs/sql-server-integrity-check.md @@ -4,11 +4,16 @@ This documentation is generated from [ola.hallengren.com/sql-server-integrity-check.html](https://ola.hallengren.com/sql-server-integrity-check.html), which is the primary source. -DatabaseIntegrityCheck is the SQL Server Maintenance Solution’s stored procedure for checking the integrity of databases. DatabaseIntegrityCheck is supported on SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, Azure SQL Database, and Azure SQL Managed Instance. +DatabaseIntegrityCheck is the SQL Server Maintenance Solution’s stored procedure for checking the integrity of databases. ## Download -Download [MaintenanceSolution.sql](/MaintenanceSolution.sql). This script creates all the objects and jobs that you need. You can also [download](https://github.com/olahallengren/sql-server-maintenance-solution) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). +Download the script for your platform: + +- [MaintenanceSolution.sql](/MaintenanceSolution.sql): SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, and Azure SQL Managed Instance. This script creates all the objects and jobs that you need. +- [MaintenanceSolutionAzureSQLDatabase.sql](/MaintenanceSolutionAzureSQLDatabase.sql): Azure SQL Database. This script creates the objects for integrity check and index and statistics maintenance. + +You can also [download](https://github.com/olahallengren/sql-server-maintenance-solution) the objects as separate scripts. The SQL Server Maintenance Solution is available on [GitHub](https://github.com/olahallengren/sql-server-maintenance-solution). ## License From a4d6edac22bc2d903d759116ebe60e96d7f868a0 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 21 Jul 2026 18:45:14 +0200 Subject: [PATCH 118/177] Add check-checksums.yml --- .github/workflows/check-checksums.yml | 30 +++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 .github/workflows/check-checksums.yml diff --git a/.github/workflows/check-checksums.yml b/.github/workflows/check-checksums.yml new file mode 100644 index 00000000..e2bb0cff --- /dev/null +++ b/.github/workflows/check-checksums.yml @@ -0,0 +1,30 @@ +name: Check checksums + +# Verifies SHA256SUMS.txt against the scripts before a pull request can be merged. + +on: + pull_request: + branches: + - main + workflow_dispatch: # adds a manual "Run workflow" button, handy for testing + +jobs: + checksums: + runs-on: ubuntu-latest + steps: + - name: Check out the repository + uses: actions/checkout@v5 + + - name: Check that every script is listed in SHA256SUMS.txt + run: | + ls *.sql | sort > /tmp/scripts.txt + awk '{print $2}' SHA256SUMS.txt | sort > /tmp/listed.txt + if ! diff /tmp/scripts.txt /tmp/listed.txt; then + echo "The scripts in the repository and the files listed in SHA256SUMS.txt do not match." + echo "Lines starting with < are scripts that are not listed; lines starting with > are listed files that do not exist." + exit 1 + fi + echo "All scripts are listed." + + - name: Check that the checksums are current + run: sha256sum -c SHA256SUMS.txt From 56ac0f23902b308b2ded01f1421c55de9fb9d8b2 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 Jul 2026 00:38:41 +0200 Subject: [PATCH 119/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 11 ++++++- DatabaseIntegrityCheck.sql | 11 ++++++- IndexOptimize.sql | 13 +++++++-- MaintenanceSolution.sql | 39 +++++++++++++++++++++---- MaintenanceSolutionAzureSQLDatabase.sql | 28 ++++++++++++++---- SHA256SUMS.txt | 12 ++++---- 7 files changed, 94 insertions(+), 22 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 9aad7423..dfb29755 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-21 14:38:46 //-- + --// Version: 2026-07-22 00:31:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 9acfae33..5113c019 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 14:38:46 //-- + --// Version: 2026-07-22 00:31:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2909,6 +2909,15 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + BEGIN + SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id + FROM sys.dm_exec_connections dm_exec_connections + INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address + INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id + WHERE dm_exec_connections.session_id = @@SPID + END + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index a25e48a7..bcf0f5a1 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 14:38:46 //-- + --// Version: 2026-07-22 00:31:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1453,6 +1453,15 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + BEGIN + SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id + FROM sys.dm_exec_connections dm_exec_connections + INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address + INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id + WHERE dm_exec_connections.session_id = @@SPID + END + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 0ba4ffa3..c034f6ad 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 14:38:46 //-- + --// Version: 2026-07-22 00:31:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1646,6 +1646,15 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + BEGIN + SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id + FROM sys.dm_exec_connections dm_exec_connections + INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address + INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id + WHERE dm_exec_connections.session_id = @@SPID + END + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID @@ -1733,7 +1742,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentUserAccess = 'SINGLE_USER') - AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' AND @CurrentAvailabilityGroupRole IS NOT NULL)) AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) AND NOT (@AmazonRDS = 1 AND @CurrentDatabaseName = 'rdsadmin') AND NOT (@CurrentIsReadOnly = 1) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 51bec134..a067f968 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: 2026-07-21 14:38:46 +Version: 2026-07-22 00:31:45 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 14:38:46 //-- + --// Version: 2026-07-22 00:31:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 14:38:46 //-- + --// Version: 2026-07-22 00:31:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3308,6 +3308,15 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + BEGIN + SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id + FROM sys.dm_exec_connections dm_exec_connections + INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address + INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id + WHERE dm_exec_connections.session_id = @@SPID + END + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID @@ -4964,7 +4973,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 14:38:46 //-- + --// Version: 2026-07-22 00:31:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6377,6 +6386,15 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + BEGIN + SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id + FROM sys.dm_exec_connections dm_exec_connections + INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address + INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id + WHERE dm_exec_connections.session_id = @@SPID + END + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID @@ -6975,7 +6993,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 14:38:46 //-- + --// Version: 2026-07-22 00:31:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8565,6 +8583,15 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + BEGIN + SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id + FROM sys.dm_exec_connections dm_exec_connections + INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address + INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id + WHERE dm_exec_connections.session_id = @@SPID + END + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID @@ -8652,7 +8679,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentUserAccess = 'SINGLE_USER') - AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' AND @CurrentAvailabilityGroupRole IS NOT NULL)) AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) AND NOT (@AmazonRDS = 1 AND @CurrentDatabaseName = 'rdsadmin') AND NOT (@CurrentIsReadOnly = 1) diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 44fe5be2..3f566e03 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-21 14:38:46 +Version: 2026-07-22 00:31:45 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 14:38:46 //-- + --// Version: 2026-07-22 00:31:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 14:38:46 //-- + --// Version: 2026-07-22 00:31:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1807,6 +1807,15 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + BEGIN + SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id + FROM sys.dm_exec_connections dm_exec_connections + INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address + INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id + WHERE dm_exec_connections.session_id = @@SPID + END + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID @@ -2405,7 +2414,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-21 14:38:46 //-- + --// Version: 2026-07-22 00:31:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3995,6 +4004,15 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + BEGIN + SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id + FROM sys.dm_exec_connections dm_exec_connections + INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address + INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id + WHERE dm_exec_connections.session_id = @@SPID + END + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID @@ -4082,7 +4100,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentUserAccess = 'SINGLE_USER') - AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' AND @CurrentAvailabilityGroupRole IS NOT NULL)) AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) AND NOT (@AmazonRDS = 1 AND @CurrentDatabaseName = 'rdsadmin') AND NOT (@CurrentIsReadOnly = 1) diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 5b24f549..3c0a068f 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -6dd6f958820d4dacec73514410b31e100264bf9484425b3e41c51dc0f66fc107 CommandExecute.sql +e421955bddd025f3c60e54f72c6ce907c6e773563e82c4018c339430709b273a CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -7a3bea07072b6c25752c312b8c6b9311c3d063de185e7d51c6273881c474aea6 DatabaseBackup.sql -f8775e20574a5349b23e375cd25af3d934b7216c2027d16bd29e0b7e38aaab7e DatabaseIntegrityCheck.sql -b07ec739543324ab7a1d65f5bebb5ac49a7d9822021ae2acb315b288e6638d89 IndexOptimize.sql -28fec783f4c6b0572933913e9be27193a1bfe28da0f3dfcb71a5b1a9fd68c71c MaintenanceSolution.sql -017b5a3b0d49606a1bc33ad4a992e0df12f2d4ace14437157dd8f0b4d39368f3 MaintenanceSolutionAzureSQLDatabase.sql +759b2495e821b64c3ef66ebb73619f6c5dc854f817de09e7daa6053ec9b126ac DatabaseBackup.sql +d77648599dd63fab01f4f8d74a52a51af38510e7216c8e6aa367d47572fc2257 DatabaseIntegrityCheck.sql +5b2d0c724717fa83b54266583f4ef94f04187ce4eb16c68f1a13a3314464a0c8 IndexOptimize.sql +baf4212affbf32138d81dc5cc3e37a6bd05fbbc1cf4457cafa3362d4ed197d94 MaintenanceSolution.sql +f2132c9015539eaade6a4f61c97065ce952b7608be677b71c3559ea5d63e20af MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 2c4fdf96b484c1c87ae5803a16aa2d2efaf35f5b Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 Jul 2026 01:12:54 +0200 Subject: [PATCH 120/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 9 +++++-- DatabaseIntegrityCheck.sql | 9 +++++-- IndexOptimize.sql | 11 ++++++--- MaintenanceSolution.sql | 33 ++++++++++++++++++------- MaintenanceSolutionAzureSQLDatabase.sql | 24 ++++++++++++------ SHA256SUMS.txt | 12 ++++----- 7 files changed, 70 insertions(+), 30 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index dfb29755..20e661e5 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-22 00:31:45 //-- + --// Version: 2026-07-22 01:08:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 5113c019..0cd317e4 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 00:31:45 //-- + --// Version: 2026-07-22 01:08:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2909,13 +2909,18 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL BEGIN SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id WHERE dm_exec_connections.session_id = @@SPID + + SELECT @CurrentAvailabilityGroupReplicaID = replica_id + FROM sys.dm_hadr_availability_replica_states + WHERE group_id = @CurrentAvailabilityGroupID + AND is_local = 1 END SELECT @CurrentAvailabilityGroupRole = role_desc diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index bcf0f5a1..b24cf576 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 00:31:45 //-- + --// Version: 2026-07-22 01:08:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1453,13 +1453,18 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL BEGIN SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id WHERE dm_exec_connections.session_id = @@SPID + + SELECT @CurrentAvailabilityGroupReplicaID = replica_id + FROM sys.dm_hadr_availability_replica_states + WHERE group_id = @CurrentAvailabilityGroupID + AND is_local = 1 END SELECT @CurrentAvailabilityGroupRole = role_desc diff --git a/IndexOptimize.sql b/IndexOptimize.sql index c034f6ad..824d117f 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 00:31:45 //-- + --// Version: 2026-07-22 01:08:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1646,13 +1646,18 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL BEGIN SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id WHERE dm_exec_connections.session_id = @@SPID + + SELECT @CurrentAvailabilityGroupReplicaID = replica_id + FROM sys.dm_hadr_availability_replica_states + WHERE group_id = @CurrentAvailabilityGroupID + AND is_local = 1 END SELECT @CurrentAvailabilityGroupRole = role_desc @@ -1742,7 +1747,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentUserAccess = 'SINGLE_USER') - AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' AND @CurrentAvailabilityGroupRole IS NOT NULL)) + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) AND NOT (@AmazonRDS = 1 AND @CurrentDatabaseName = 'rdsadmin') AND NOT (@CurrentIsReadOnly = 1) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index a067f968..d6fb8d4b 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: 2026-07-22 00:31:45 +Version: 2026-07-22 01:08:53 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 00:31:45 //-- + --// Version: 2026-07-22 01:08:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 00:31:45 //-- + --// Version: 2026-07-22 01:08:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3308,13 +3308,18 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL BEGIN SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id WHERE dm_exec_connections.session_id = @@SPID + + SELECT @CurrentAvailabilityGroupReplicaID = replica_id + FROM sys.dm_hadr_availability_replica_states + WHERE group_id = @CurrentAvailabilityGroupID + AND is_local = 1 END SELECT @CurrentAvailabilityGroupRole = role_desc @@ -4973,7 +4978,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 00:31:45 //-- + --// Version: 2026-07-22 01:08:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6386,13 +6391,18 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL BEGIN SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id WHERE dm_exec_connections.session_id = @@SPID + + SELECT @CurrentAvailabilityGroupReplicaID = replica_id + FROM sys.dm_hadr_availability_replica_states + WHERE group_id = @CurrentAvailabilityGroupID + AND is_local = 1 END SELECT @CurrentAvailabilityGroupRole = role_desc @@ -6993,7 +7003,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 00:31:45 //-- + --// Version: 2026-07-22 01:08:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8583,13 +8593,18 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL BEGIN SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id WHERE dm_exec_connections.session_id = @@SPID + + SELECT @CurrentAvailabilityGroupReplicaID = replica_id + FROM sys.dm_hadr_availability_replica_states + WHERE group_id = @CurrentAvailabilityGroupID + AND is_local = 1 END SELECT @CurrentAvailabilityGroupRole = role_desc @@ -8679,7 +8694,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentUserAccess = 'SINGLE_USER') - AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' AND @CurrentAvailabilityGroupRole IS NOT NULL)) + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) AND NOT (@AmazonRDS = 1 AND @CurrentDatabaseName = 'rdsadmin') AND NOT (@CurrentIsReadOnly = 1) diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 3f566e03..895aaf11 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-22 00:31:45 +Version: 2026-07-22 01:08:53 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 00:31:45 //-- + --// Version: 2026-07-22 01:08:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 00:31:45 //-- + --// Version: 2026-07-22 01:08:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1807,13 +1807,18 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL BEGIN SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id WHERE dm_exec_connections.session_id = @@SPID + + SELECT @CurrentAvailabilityGroupReplicaID = replica_id + FROM sys.dm_hadr_availability_replica_states + WHERE group_id = @CurrentAvailabilityGroupID + AND is_local = 1 END SELECT @CurrentAvailabilityGroupRole = role_desc @@ -2414,7 +2419,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 00:31:45 //-- + --// Version: 2026-07-22 01:08:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4004,13 +4009,18 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupID IS NULL + IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL BEGIN SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id WHERE dm_exec_connections.session_id = @@SPID + + SELECT @CurrentAvailabilityGroupReplicaID = replica_id + FROM sys.dm_hadr_availability_replica_states + WHERE group_id = @CurrentAvailabilityGroupID + AND is_local = 1 END SELECT @CurrentAvailabilityGroupRole = role_desc @@ -4100,7 +4110,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT (@CurrentUserAccess = 'SINGLE_USER') - AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' AND @CurrentAvailabilityGroupRole IS NOT NULL)) + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) AND NOT (@AmazonRDS = 1 AND @CurrentDatabaseName = 'rdsadmin') AND NOT (@CurrentIsReadOnly = 1) diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 3c0a068f..c58490ea 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -e421955bddd025f3c60e54f72c6ce907c6e773563e82c4018c339430709b273a CommandExecute.sql +4e42ba126354bce24f3024b2a85b54ca49d59a67c34d9e88c630f549dea4054b CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -759b2495e821b64c3ef66ebb73619f6c5dc854f817de09e7daa6053ec9b126ac DatabaseBackup.sql -d77648599dd63fab01f4f8d74a52a51af38510e7216c8e6aa367d47572fc2257 DatabaseIntegrityCheck.sql -5b2d0c724717fa83b54266583f4ef94f04187ce4eb16c68f1a13a3314464a0c8 IndexOptimize.sql -baf4212affbf32138d81dc5cc3e37a6bd05fbbc1cf4457cafa3362d4ed197d94 MaintenanceSolution.sql -f2132c9015539eaade6a4f61c97065ce952b7608be677b71c3559ea5d63e20af MaintenanceSolutionAzureSQLDatabase.sql +ff29850ab85b62dd64598f8424e1adee9f4d750d0bbc4a424f897fb837c689b5 DatabaseBackup.sql +6133cd1a6b10ee7dac5b664dcb27975b1e96c8c66877f1566b51fc0aa813848a DatabaseIntegrityCheck.sql +e8a5d633f2cb7ba69ef3ae5b500be44e6b0281409fc006b9c60f22be13929915 IndexOptimize.sql +aa648c45db70adc42075f213d325b8acaed58951c69ff6bbb6fcd53d5cd76bf4 MaintenanceSolution.sql +ac61325437bb328e5011a965f59291c39f05a5d8b379c9c0f5d2955ff8b36f0e MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 3c69db222c65fea0cf918c764862e709b14c4123 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 Jul 2026 01:24:24 +0200 Subject: [PATCH 121/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 6 +++++- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 14 +++++++++----- MaintenanceSolutionAzureSQLDatabase.sql | 12 ++++++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 31 insertions(+), 19 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 20e661e5..ed3e5eba 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-22 01:08:53 //-- + --// Version: 2026-07-22 01:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 0cd317e4..35edfa74 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:08:53 //-- + --// Version: 2026-07-22 01:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index b24cf576..aa8fbd87 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:08:53 //-- + --// Version: 2026-07-22 01:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1467,6 +1467,10 @@ BEGIN AND is_local = 1 END + SELECT @CurrentSecondaryRoleAllowConnections = secondary_role_allow_connections_desc + FROM sys.availability_replicas + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 824d117f..8751d4cc 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:08:53 //-- + --// Version: 2026-07-22 01:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index d6fb8d4b..48450c68 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: 2026-07-22 01:08:53 +Version: 2026-07-22 01:23:44 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:08:53 //-- + --// Version: 2026-07-22 01:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:08:53 //-- + --// Version: 2026-07-22 01:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4978,7 +4978,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:08:53 //-- + --// Version: 2026-07-22 01:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6405,6 +6405,10 @@ BEGIN AND is_local = 1 END + SELECT @CurrentSecondaryRoleAllowConnections = secondary_role_allow_connections_desc + FROM sys.availability_replicas + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID @@ -7003,7 +7007,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:08:53 //-- + --// Version: 2026-07-22 01:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 895aaf11..20a9a769 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-22 01:08:53 +Version: 2026-07-22 01:23:44 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:08:53 //-- + --// Version: 2026-07-22 01:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:08:53 //-- + --// Version: 2026-07-22 01:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1821,6 +1821,10 @@ BEGIN AND is_local = 1 END + SELECT @CurrentSecondaryRoleAllowConnections = secondary_role_allow_connections_desc + FROM sys.availability_replicas + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID @@ -2419,7 +2423,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:08:53 //-- + --// Version: 2026-07-22 01:23:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index c58490ea..07fe0ea6 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -4e42ba126354bce24f3024b2a85b54ca49d59a67c34d9e88c630f549dea4054b CommandExecute.sql +f7588e0eaa3ffa0f811ae834b3b8145a004b0d82b1421ba0882a44d43ace2f57 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -ff29850ab85b62dd64598f8424e1adee9f4d750d0bbc4a424f897fb837c689b5 DatabaseBackup.sql -6133cd1a6b10ee7dac5b664dcb27975b1e96c8c66877f1566b51fc0aa813848a DatabaseIntegrityCheck.sql -e8a5d633f2cb7ba69ef3ae5b500be44e6b0281409fc006b9c60f22be13929915 IndexOptimize.sql -aa648c45db70adc42075f213d325b8acaed58951c69ff6bbb6fcd53d5cd76bf4 MaintenanceSolution.sql -ac61325437bb328e5011a965f59291c39f05a5d8b379c9c0f5d2955ff8b36f0e MaintenanceSolutionAzureSQLDatabase.sql +82c4e1f5ad2982e831953ba645a41e6a0059400b89e8bbf336062fbcc42c8f65 DatabaseBackup.sql +844caea0ca894cc488421856c9c3ebc1c410002cf16e002f6648fe27f03a36bf DatabaseIntegrityCheck.sql +f5978e3d30d6c8a559d8e446e9cd62143659ad3cb3935f557d0fd4c0091e61b1 IndexOptimize.sql +eac101db0bd0db394a1bc9f8f5ff960368918ccebb6d34f9325251e8d3b2f565 MaintenanceSolution.sql +c96aea734f3edb8fcb8a197b386edda7a32424d5cd16b19d4d7123986f0ebbac MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 7e469e618b59ab56a743628743ca7bd6c289c517 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 Jul 2026 09:56:45 +0200 Subject: [PATCH 122/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 5 ++--- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 13 ++++++------- MaintenanceSolutionAzureSQLDatabase.sql | 11 +++++------ SHA256SUMS.txt | 12 ++++++------ 7 files changed, 22 insertions(+), 25 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index ed3e5eba..9f02652b 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-22 01:23:44 //-- + --// Version: 2026-07-22 09:54:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 35edfa74..fc48705c 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:23:44 //-- + --// Version: 2026-07-22 09:54:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index aa8fbd87..42200903 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:23:44 //-- + --// Version: 2026-07-22 09:54:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1448,8 +1448,7 @@ BEGIN INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupID = group_id, - @CurrentSecondaryRoleAllowConnections = secondary_role_allow_connections_desc + SELECT @CurrentAvailabilityGroupID = group_id FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 8751d4cc..a9f5be67 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:23:44 //-- + --// Version: 2026-07-22 09:54:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 48450c68..e897121a 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: 2026-07-22 01:23:44 +Version: 2026-07-22 09:54:08 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:23:44 //-- + --// Version: 2026-07-22 09:54:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:23:44 //-- + --// Version: 2026-07-22 09:54:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4978,7 +4978,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:23:44 //-- + --// Version: 2026-07-22 09:54:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6386,8 +6386,7 @@ BEGIN INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupID = group_id, - @CurrentSecondaryRoleAllowConnections = secondary_role_allow_connections_desc + SELECT @CurrentAvailabilityGroupID = group_id FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID @@ -7007,7 +7006,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:23:44 //-- + --// Version: 2026-07-22 09:54:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 20a9a769..e268a6d1 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-22 01:23:44 +Version: 2026-07-22 09:54:08 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:23:44 //-- + --// Version: 2026-07-22 09:54:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:23:44 //-- + --// Version: 2026-07-22 09:54:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1802,8 +1802,7 @@ BEGIN INNER JOIN sys.availability_replicas availability_replicas ON databases.replica_id = availability_replicas.replica_id WHERE databases.[name] = @CurrentDatabaseName - SELECT @CurrentAvailabilityGroupID = group_id, - @CurrentSecondaryRoleAllowConnections = secondary_role_allow_connections_desc + SELECT @CurrentAvailabilityGroupID = group_id FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID @@ -2423,7 +2422,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 01:23:44 //-- + --// Version: 2026-07-22 09:54:08 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 07fe0ea6..fb746477 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -f7588e0eaa3ffa0f811ae834b3b8145a004b0d82b1421ba0882a44d43ace2f57 CommandExecute.sql +68d88d1f04dd35bdc3d45f73a74b56b780f043da5e093db303087f10c31ec680 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -82c4e1f5ad2982e831953ba645a41e6a0059400b89e8bbf336062fbcc42c8f65 DatabaseBackup.sql -844caea0ca894cc488421856c9c3ebc1c410002cf16e002f6648fe27f03a36bf DatabaseIntegrityCheck.sql -f5978e3d30d6c8a559d8e446e9cd62143659ad3cb3935f557d0fd4c0091e61b1 IndexOptimize.sql -eac101db0bd0db394a1bc9f8f5ff960368918ccebb6d34f9325251e8d3b2f565 MaintenanceSolution.sql -c96aea734f3edb8fcb8a197b386edda7a32424d5cd16b19d4d7123986f0ebbac MaintenanceSolutionAzureSQLDatabase.sql +96663043bb81b0ec3a4cbbb8e7da50ba738c599bc7cea61fec96c9bacc59ffff DatabaseBackup.sql +47a82d717780a1aae1d99d60ca167692a1795d9b3aae1a0f5c16f320e624bf76 DatabaseIntegrityCheck.sql +4090819e50e5b54a8c53ddf2062d77e1cec7f4664e808fc6f11f16b280510742 IndexOptimize.sql +00471f77cb6dab254119d286100c691a8027981a9218abc23a019b9a217c4653 MaintenanceSolution.sql +44829c25ef6a7165fb9ca0ef6f38940c24ba23a88d6b55375741f89e268e92bc MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 24c0a7f59212153001e13e02e2a52df7941cc52c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 Jul 2026 14:09:04 +0200 Subject: [PATCH 123/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 51 ++++----- DatabaseIntegrityCheck.sql | 45 ++++---- IndexOptimize.sql | 45 ++++---- MaintenanceSolution.sql | 145 +++++++++++------------- MaintenanceSolutionAzureSQLDatabase.sql | 94 +++++++-------- SHA256SUMS.txt | 12 +- 7 files changed, 179 insertions(+), 215 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 9f02652b..ed752547 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-22 09:54:08 //-- + --// Version: 2026-07-22 14:07:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index fc48705c..d8f6646b 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 09:54:08 //-- + --// Version: 2026-07-22 14:07:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -124,7 +124,6 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) - DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 DECLARE @DirectorySeparator nvarchar(max) DECLARE @Updated bit @@ -174,6 +173,7 @@ BEGIN DECLARE @CurrentDate datetime2 DECLARE @CurrentDateUTC datetime2 DECLARE @CurrentCleanupDate datetime2 + DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -322,15 +322,6 @@ BEGIN FROM sys.dm_os_host_info END - IF @EngineEdition <> 5 - BEGIN - IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) - AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) - BEGIN - SET @ContainedAvailabilityGroupListenerConnection = 1 - END - END - DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -441,12 +432,6 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF @EngineEdition <> 5 - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -2898,6 +2883,8 @@ BEGIN WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version < 15.04043 AND NOT (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND @Credential IS NULL THEN 65537 END + SET @CurrentContainedAvailabilityGroupListenerConnection = 0 + IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -2909,13 +2896,16 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL + IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id - FROM sys.dm_exec_connections dm_exec_connections - INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address - INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id - WHERE dm_exec_connections.session_id = @@SPID + SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT + + IF @CurrentAvailabilityGroupID IS NOT NULL + BEGIN + SET @CurrentContainedAvailabilityGroupListenerConnection = 1 + END SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -2982,7 +2972,7 @@ BEGIN AND NOT @CurrentInStandby = 1 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) - AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) + AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @CurrentContainedAvailabilityGroupListenerConnection = 0))) BEGIN SET @CurrentCommand = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' @@ -2998,11 +2988,11 @@ BEGIN IF @ChangeBackupType = 'Y' BEGIN - IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) + IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @CurrentContainedAvailabilityGroupListenerConnection = 0) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) BEGIN SET @CurrentBackupType = 'DIFF' END - IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / NULLIF(@CurrentAllocatedExtentPageCount, 0) * 100 >= @MinModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) + IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @CurrentContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / NULLIF(@CurrentAllocatedExtentPageCount, 0) * 100 >= @MinModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) BEGIN SET @CurrentBackupType = 'FULL' END @@ -3090,6 +3080,12 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -3189,7 +3185,7 @@ BEGIN 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 @ContainedAvailabilityGroupListenerConnection = 0)) + AND NOT (@CurrentBackupType IN('DIFF','LOG') AND (@CurrentDatabaseName = 'master' AND @CurrentContainedAvailabilityGroupListenerConnection = 0)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) @@ -4483,6 +4479,7 @@ BEGIN SET @CurrentDate = NULL SET @CurrentDateUTC = NULL SET @CurrentCleanupDate = NULL + SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 42200903..efe8ec54 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 09:54:08 //-- + --// Version: 2026-07-22 14:07:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -71,7 +71,6 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) - DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -86,7 +85,7 @@ BEGIN DECLARE @CurrentDatabaseState nvarchar(max) DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) - + DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -218,15 +217,6 @@ BEGIN FROM sys.dm_os_host_info END - IF @EngineEdition <> 5 - BEGIN - IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) - AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) - BEGIN - SET @ContainedAvailabilityGroupListenerConnection = 1 - END - END - DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -283,12 +273,6 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF @EngineEdition <> 5 - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -1441,6 +1425,8 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END + SET @CurrentContainedAvailabilityGroupListenerConnection = 0 + IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -1452,13 +1438,16 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL + IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id - FROM sys.dm_exec_connections dm_exec_connections - INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address - INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id - WHERE dm_exec_connections.session_id = @@SPID + SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT + + IF @CurrentAvailabilityGroupID IS NOT NULL + BEGIN + SET @CurrentContainedAvailabilityGroupListenerConnection = 1 + END SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -1510,6 +1499,12 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -1967,7 +1962,7 @@ BEGIN SET @CurrentDatabaseState = NULL SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL - + SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL diff --git a/IndexOptimize.sql b/IndexOptimize.sql index a9f5be67..8c1ae4b9 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 09:54:08 //-- + --// Version: 2026-07-22 14:07:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -91,7 +91,6 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) - DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -108,7 +107,7 @@ BEGIN DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) DECLARE @CurrentDatabaseHasReadOnlyFileGroup bit - + DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -368,15 +367,6 @@ BEGIN FROM sys.dm_os_host_info END - IF @EngineEdition <> 5 - BEGIN - IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) - AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) - BEGIN - SET @ContainedAvailabilityGroupListenerConnection = 1 - END - END - DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -448,12 +438,6 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF @EngineEdition <> 5 - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -1635,6 +1619,8 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END + SET @CurrentContainedAvailabilityGroupListenerConnection = 0 + IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -1646,13 +1632,16 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL + IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id - FROM sys.dm_exec_connections dm_exec_connections - INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address - INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id - WHERE dm_exec_connections.session_id = @@SPID + SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT + + IF @CurrentAvailabilityGroupID IS NOT NULL + BEGIN + SET @CurrentContainedAvailabilityGroupListenerConnection = 1 + END SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -1694,6 +1683,12 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -2909,7 +2904,7 @@ BEGIN SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL SET @CurrentDatabaseHasReadOnlyFileGroup = NULL - + SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index e897121a..7c896bb1 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: 2026-07-22 09:54:08 +Version: 2026-07-22 14:07:58 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 09:54:08 //-- + --// Version: 2026-07-22 14:07:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 09:54:08 //-- + --// Version: 2026-07-22 14:07:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -523,7 +523,6 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) - DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 DECLARE @DirectorySeparator nvarchar(max) DECLARE @Updated bit @@ -573,6 +572,7 @@ BEGIN DECLARE @CurrentDate datetime2 DECLARE @CurrentDateUTC datetime2 DECLARE @CurrentCleanupDate datetime2 + DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -721,15 +721,6 @@ BEGIN FROM sys.dm_os_host_info END - IF @EngineEdition <> 5 - BEGIN - IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) - AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) - BEGIN - SET @ContainedAvailabilityGroupListenerConnection = 1 - END - END - DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -840,12 +831,6 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF @EngineEdition <> 5 - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -3297,6 +3282,8 @@ BEGIN WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version < 15.04043 AND NOT (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND @Credential IS NULL THEN 65537 END + SET @CurrentContainedAvailabilityGroupListenerConnection = 0 + IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -3308,13 +3295,16 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL + IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id - FROM sys.dm_exec_connections dm_exec_connections - INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address - INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id - WHERE dm_exec_connections.session_id = @@SPID + SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT + + IF @CurrentAvailabilityGroupID IS NOT NULL + BEGIN + SET @CurrentContainedAvailabilityGroupListenerConnection = 1 + END SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -3381,7 +3371,7 @@ BEGIN AND NOT @CurrentInStandby = 1 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) - AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) + AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @CurrentContainedAvailabilityGroupListenerConnection = 0))) BEGIN SET @CurrentCommand = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' @@ -3397,11 +3387,11 @@ BEGIN IF @ChangeBackupType = 'Y' BEGIN - IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) + IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @CurrentContainedAvailabilityGroupListenerConnection = 0) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) BEGIN SET @CurrentBackupType = 'DIFF' END - IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / NULLIF(@CurrentAllocatedExtentPageCount, 0) * 100 >= @MinModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) + IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @CurrentContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / NULLIF(@CurrentAllocatedExtentPageCount, 0) * 100 >= @MinModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) BEGIN SET @CurrentBackupType = 'FULL' END @@ -3489,6 +3479,12 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -3588,7 +3584,7 @@ BEGIN 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 @ContainedAvailabilityGroupListenerConnection = 0)) + AND NOT (@CurrentBackupType IN('DIFF','LOG') AND (@CurrentDatabaseName = 'master' AND @CurrentContainedAvailabilityGroupListenerConnection = 0)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) @@ -4882,6 +4878,7 @@ BEGIN SET @CurrentDate = NULL SET @CurrentDateUTC = NULL SET @CurrentCleanupDate = NULL + SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL @@ -4978,7 +4975,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 09:54:08 //-- + --// Version: 2026-07-22 14:07:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5009,7 +5006,6 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) - DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -5024,7 +5020,7 @@ BEGIN DECLARE @CurrentDatabaseState nvarchar(max) DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) - + DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -5156,15 +5152,6 @@ BEGIN FROM sys.dm_os_host_info END - IF @EngineEdition <> 5 - BEGIN - IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) - AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) - BEGIN - SET @ContainedAvailabilityGroupListenerConnection = 1 - END - END - DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -5221,12 +5208,6 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF @EngineEdition <> 5 - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -6379,6 +6360,8 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END + SET @CurrentContainedAvailabilityGroupListenerConnection = 0 + IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -6390,13 +6373,16 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL + IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id - FROM sys.dm_exec_connections dm_exec_connections - INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address - INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id - WHERE dm_exec_connections.session_id = @@SPID + SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT + + IF @CurrentAvailabilityGroupID IS NOT NULL + BEGIN + SET @CurrentContainedAvailabilityGroupListenerConnection = 1 + END SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -6448,6 +6434,12 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -6905,7 +6897,7 @@ BEGIN SET @CurrentDatabaseState = NULL SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL - + SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL @@ -7006,7 +6998,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 09:54:08 //-- + --// Version: 2026-07-22 14:07:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7041,7 +7033,6 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) - DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -7058,7 +7049,7 @@ BEGIN DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) DECLARE @CurrentDatabaseHasReadOnlyFileGroup bit - + DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -7318,15 +7309,6 @@ BEGIN FROM sys.dm_os_host_info END - IF @EngineEdition <> 5 - BEGIN - IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) - AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) - BEGIN - SET @ContainedAvailabilityGroupListenerConnection = 1 - END - END - DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -7398,12 +7380,6 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF @EngineEdition <> 5 - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -8585,6 +8561,8 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END + SET @CurrentContainedAvailabilityGroupListenerConnection = 0 + IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -8596,13 +8574,16 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL + IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id - FROM sys.dm_exec_connections dm_exec_connections - INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address - INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id - WHERE dm_exec_connections.session_id = @@SPID + SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT + + IF @CurrentAvailabilityGroupID IS NOT NULL + BEGIN + SET @CurrentContainedAvailabilityGroupListenerConnection = 1 + END SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -8644,6 +8625,12 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -9859,7 +9846,7 @@ BEGIN SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL SET @CurrentDatabaseHasReadOnlyFileGroup = NULL - + SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index e268a6d1..c1ebb11c 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-22 09:54:08 +Version: 2026-07-22 14:07:58 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 09:54:08 //-- + --// Version: 2026-07-22 14:07:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 09:54:08 //-- + --// Version: 2026-07-22 14:07:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -425,7 +425,6 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) - DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -440,7 +439,7 @@ BEGIN DECLARE @CurrentDatabaseState nvarchar(max) DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) - + DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -572,15 +571,6 @@ BEGIN FROM sys.dm_os_host_info END - IF @EngineEdition <> 5 - BEGIN - IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) - AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) - BEGIN - SET @ContainedAvailabilityGroupListenerConnection = 1 - END - END - DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -637,12 +627,6 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF @EngineEdition <> 5 - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -1795,6 +1779,8 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END + SET @CurrentContainedAvailabilityGroupListenerConnection = 0 + IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -1806,13 +1792,16 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL + IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id - FROM sys.dm_exec_connections dm_exec_connections - INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address - INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id - WHERE dm_exec_connections.session_id = @@SPID + SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT + + IF @CurrentAvailabilityGroupID IS NOT NULL + BEGIN + SET @CurrentContainedAvailabilityGroupListenerConnection = 1 + END SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -1864,6 +1853,12 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -2321,7 +2316,7 @@ BEGIN SET @CurrentDatabaseState = NULL SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL - + SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL @@ -2422,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 09:54:08 //-- + --// Version: 2026-07-22 14:07:58 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2457,7 +2452,6 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) - DECLARE @ContainedAvailabilityGroupListenerConnection bit = 0 DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -2474,7 +2468,7 @@ BEGIN DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) DECLARE @CurrentDatabaseHasReadOnlyFileGroup bit - + DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -2734,15 +2728,6 @@ BEGIN FROM sys.dm_os_host_info END - IF @EngineEdition <> 5 - BEGIN - IF EXISTS (SELECT * FROM sys.databases WHERE name = 'msdb' AND database_id <> 4) - AND EXISTS (SELECT * FROM sys.dm_exec_connections dm_exec_connections INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address WHERE dm_exec_connections.session_id = @@SPID) - BEGIN - SET @ContainedAvailabilityGroupListenerConnection = 1 - END - END - DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -2814,12 +2799,6 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF @EngineEdition <> 5 - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -4001,6 +3980,8 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END + SET @CurrentContainedAvailabilityGroupListenerConnection = 0 + IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -4012,13 +3993,16 @@ BEGIN FROM sys.availability_replicas WHERE replica_id = @CurrentAvailabilityGroupReplicaID - IF @ContainedAvailabilityGroupListenerConnection = 1 AND @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL + IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SELECT @CurrentAvailabilityGroupID = availability_group_listeners.group_id - FROM sys.dm_exec_connections dm_exec_connections - INNER JOIN sys.availability_group_listener_ip_addresses availability_group_listener_ip_addresses ON dm_exec_connections.local_net_address = availability_group_listener_ip_addresses.ip_address - INNER JOIN sys.availability_group_listeners availability_group_listeners ON availability_group_listener_ip_addresses.listener_id = availability_group_listeners.listener_id - WHERE dm_exec_connections.session_id = @@SPID + SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT + + IF @CurrentAvailabilityGroupID IS NOT NULL + BEGIN + SET @CurrentContainedAvailabilityGroupListenerConnection = 1 + END SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -4060,6 +4044,12 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -5275,7 +5265,7 @@ BEGIN SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL SET @CurrentDatabaseHasReadOnlyFileGroup = NULL - + SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index fb746477..5911c296 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -68d88d1f04dd35bdc3d45f73a74b56b780f043da5e093db303087f10c31ec680 CommandExecute.sql +860bf38940301d7ab350eb5e110fe24ac6879461a216f35f787e24e14f53a133 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -96663043bb81b0ec3a4cbbb8e7da50ba738c599bc7cea61fec96c9bacc59ffff DatabaseBackup.sql -47a82d717780a1aae1d99d60ca167692a1795d9b3aae1a0f5c16f320e624bf76 DatabaseIntegrityCheck.sql -4090819e50e5b54a8c53ddf2062d77e1cec7f4664e808fc6f11f16b280510742 IndexOptimize.sql -00471f77cb6dab254119d286100c691a8027981a9218abc23a019b9a217c4653 MaintenanceSolution.sql -44829c25ef6a7165fb9ca0ef6f38940c24ba23a88d6b55375741f89e268e92bc MaintenanceSolutionAzureSQLDatabase.sql +3daa9cbf75b2e4a1f2fcddff36c3195959e8ac74fcd0e8c8435dd2973a3ac1ea DatabaseBackup.sql +358a22c996e42989c0b84ef3018289bc8fe89b02a69e0754e260787033123bb2 DatabaseIntegrityCheck.sql +c89a4aaa22e7dfa535b4ea92defc87d4af44f3ade0f4879302446c32c822b9ce IndexOptimize.sql +14fbc5230eb99a95da5cc20166701ee55fae3babac66b77946454f671d39945b MaintenanceSolution.sql +4a013bc4bd8740aac0c7cebf970d125d9bd015ce5351521b10871e3098cd5a5d MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From cde31044052fe279cb22e71a65a8326058acb187 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 Jul 2026 18:37:47 +0200 Subject: [PATCH 124/177] Add files via upload --- deploy-website.yml | 87 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 deploy-website.yml diff --git a/deploy-website.yml b/deploy-website.yml new file mode 100644 index 00000000..f09ae743 --- /dev/null +++ b/deploy-website.yml @@ -0,0 +1,87 @@ +name: Deploy to website + +# Uploads the released files to the website over FTPS whenever a release is merged to main. + +on: + push: + branches: + - main + paths: + - MaintenanceSolution.sql # a release always updates this file + workflow_dispatch: # adds a manual "Run workflow" button, handy for testing + +env: + REMOTE_DIR: "/public_html/scripts" # scripts folder on the server + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - name: Check out the repository + uses: actions/checkout@v5 + + - name: Install lftp (FTPS client) + run: sudo apt-get update -qq && sudo apt-get install -y -qq lftp + + - name: Upload files over FTPS + env: + FTP_SERVER: ${{ secrets.FTP_SERVER }} + FTP_USERNAME: ${{ secrets.FTP_USERNAME }} + LFTP_PASSWORD: ${{ secrets.FTP_PASSWORD }} + run: | + set -u + + # Upload order: components first, then the installers, SHA256SUMS.txt last + # (the checksums go live only after the files they describe are in place). + FILES="CommandLog.sql Queue.sql QueueDatabase.sql CommandExecute.sql DatabaseBackup.sql DatabaseIntegrityCheck.sql IndexOptimize.sql MaintenanceSolutionAzureSQLDatabase.sql MaintenanceSolution.sql SHA256SUMS.txt" + + # Explicit FTPS (AUTH TLS) on port 21 + SETTINGS="set ftp:ssl-force true; set ftp:ssl-protect-data true; set ssl:verify-certificate true; set net:max-retries 2; set net:timeout 60" + + # The password is read from the LFTP_PASSWORD environment variable (--env-password), + # keeping it off the command line and out of the process table. + run_lftp () { + lftp -p 21 --env-password -u "$FTP_USERNAME" -e "$SETTINGS; $1; bye" "$FTP_SERVER" + } + + # Two-phase upload. + # Phase 1 uploads ALL files under temporary names. + # Phase 2 renames the temp files into place. + UPLOAD="" + for f in $FILES; do + UPLOAD="$UPLOAD put $f -o $REMOTE_DIR/$f.tmp;" + done + for f in $FILES; do + UPLOAD="$UPLOAD mv $REMOTE_DIR/$f.tmp $REMOTE_DIR/$f;" + done + + # Verification: list the files on the server and compare each size, byte for byte, against the file in the repository. + verify () { + LISTING=$(run_lftp "cls -s --block-size=1 $REMOTE_DIR/*.sql $REMOTE_DIR/SHA256SUMS.txt") || return 1 + for f in $FILES; do + LOCAL=$(stat -c %s "$f") + REMOTE=$(printf '%s\n' "$LISTING" | grep "/$f\$" | awk '{print $1}') + if [ "$LOCAL" != "$REMOTE" ]; then + echo "VERIFY FAILED: $f is $LOCAL bytes in the repo but ${REMOTE:-missing} on the server" + return 1 + fi + echo "Verified $f ($LOCAL bytes)" + done + return 0 + } + + # Try the whole upload-and-verify up to 3 times + for attempt in 1 2 3; do + echo "=== Upload attempt $attempt of 3 ===" + if run_lftp "$UPLOAD" && verify; then + echo "Deploy succeeded and verified." + exit 0 + fi + if [ "$attempt" -lt 3 ]; then + echo "Attempt $attempt failed - waiting 120 seconds before retrying." + sleep 120 + fi + done + + echo "All attempts failed. The website may be behind or partially updated; re-run this workflow when the host is reachable to make it consistent." + exit 1 From 1590e469566b11ee0c5df12b180923bd03fa91bb Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 Jul 2026 18:39:57 +0200 Subject: [PATCH 125/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index 6b7eac96..f09ae743 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -27,7 +27,7 @@ jobs: env: FTP_SERVER: ${{ secrets.FTP_SERVER }} FTP_USERNAME: ${{ secrets.FTP_USERNAME }} - FTP_PASSWORD: ${{ secrets.FTP_PASSWORD }} + LFTP_PASSWORD: ${{ secrets.FTP_PASSWORD }} run: | set -u @@ -38,8 +38,10 @@ jobs: # Explicit FTPS (AUTH TLS) on port 21 SETTINGS="set ftp:ssl-force true; set ftp:ssl-protect-data true; set ssl:verify-certificate true; set net:max-retries 2; set net:timeout 60" + # The password is read from the LFTP_PASSWORD environment variable (--env-password), + # keeping it off the command line and out of the process table. run_lftp () { - lftp -p 21 -u "$FTP_USERNAME,$FTP_PASSWORD" -e "$SETTINGS; $1; bye" "$FTP_SERVER" + lftp -p 21 --env-password -u "$FTP_USERNAME" -e "$SETTINGS; $1; bye" "$FTP_SERVER" } # Two-phase upload. From 526a1d312c8f7ad2285ee4d2bf1b04679be2d708 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 Jul 2026 18:40:40 +0200 Subject: [PATCH 126/177] Delete deploy-website.yml --- deploy-website.yml | 87 ---------------------------------------------- 1 file changed, 87 deletions(-) delete mode 100644 deploy-website.yml diff --git a/deploy-website.yml b/deploy-website.yml deleted file mode 100644 index f09ae743..00000000 --- a/deploy-website.yml +++ /dev/null @@ -1,87 +0,0 @@ -name: Deploy to website - -# Uploads the released files to the website over FTPS whenever a release is merged to main. - -on: - push: - branches: - - main - paths: - - MaintenanceSolution.sql # a release always updates this file - workflow_dispatch: # adds a manual "Run workflow" button, handy for testing - -env: - REMOTE_DIR: "/public_html/scripts" # scripts folder on the server - -jobs: - deploy: - runs-on: ubuntu-latest - steps: - - name: Check out the repository - uses: actions/checkout@v5 - - - name: Install lftp (FTPS client) - run: sudo apt-get update -qq && sudo apt-get install -y -qq lftp - - - name: Upload files over FTPS - env: - FTP_SERVER: ${{ secrets.FTP_SERVER }} - FTP_USERNAME: ${{ secrets.FTP_USERNAME }} - LFTP_PASSWORD: ${{ secrets.FTP_PASSWORD }} - run: | - set -u - - # Upload order: components first, then the installers, SHA256SUMS.txt last - # (the checksums go live only after the files they describe are in place). - FILES="CommandLog.sql Queue.sql QueueDatabase.sql CommandExecute.sql DatabaseBackup.sql DatabaseIntegrityCheck.sql IndexOptimize.sql MaintenanceSolutionAzureSQLDatabase.sql MaintenanceSolution.sql SHA256SUMS.txt" - - # Explicit FTPS (AUTH TLS) on port 21 - SETTINGS="set ftp:ssl-force true; set ftp:ssl-protect-data true; set ssl:verify-certificate true; set net:max-retries 2; set net:timeout 60" - - # The password is read from the LFTP_PASSWORD environment variable (--env-password), - # keeping it off the command line and out of the process table. - run_lftp () { - lftp -p 21 --env-password -u "$FTP_USERNAME" -e "$SETTINGS; $1; bye" "$FTP_SERVER" - } - - # Two-phase upload. - # Phase 1 uploads ALL files under temporary names. - # Phase 2 renames the temp files into place. - UPLOAD="" - for f in $FILES; do - UPLOAD="$UPLOAD put $f -o $REMOTE_DIR/$f.tmp;" - done - for f in $FILES; do - UPLOAD="$UPLOAD mv $REMOTE_DIR/$f.tmp $REMOTE_DIR/$f;" - done - - # Verification: list the files on the server and compare each size, byte for byte, against the file in the repository. - verify () { - LISTING=$(run_lftp "cls -s --block-size=1 $REMOTE_DIR/*.sql $REMOTE_DIR/SHA256SUMS.txt") || return 1 - for f in $FILES; do - LOCAL=$(stat -c %s "$f") - REMOTE=$(printf '%s\n' "$LISTING" | grep "/$f\$" | awk '{print $1}') - if [ "$LOCAL" != "$REMOTE" ]; then - echo "VERIFY FAILED: $f is $LOCAL bytes in the repo but ${REMOTE:-missing} on the server" - return 1 - fi - echo "Verified $f ($LOCAL bytes)" - done - return 0 - } - - # Try the whole upload-and-verify up to 3 times - for attempt in 1 2 3; do - echo "=== Upload attempt $attempt of 3 ===" - if run_lftp "$UPLOAD" && verify; then - echo "Deploy succeeded and verified." - exit 0 - fi - if [ "$attempt" -lt 3 ]; then - echo "Attempt $attempt failed - waiting 120 seconds before retrying." - sleep 120 - fi - done - - echo "All attempts failed. The website may be behind or partially updated; re-run this workflow when the host is reachable to make it consistent." - exit 1 From 75213b12c0f8ef8511c8cef290c85ff05f7a5461 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 Jul 2026 18:42:08 +0200 Subject: [PATCH 127/177] Update deploy-website.yml --- .github/workflows/deploy-website.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/deploy-website.yml b/.github/workflows/deploy-website.yml index f09ae743..4e154f1c 100644 --- a/.github/workflows/deploy-website.yml +++ b/.github/workflows/deploy-website.yml @@ -38,8 +38,7 @@ jobs: # Explicit FTPS (AUTH TLS) on port 21 SETTINGS="set ftp:ssl-force true; set ftp:ssl-protect-data true; set ssl:verify-certificate true; set net:max-retries 2; set net:timeout 60" - # The password is read from the LFTP_PASSWORD environment variable (--env-password), - # keeping it off the command line and out of the process table. + # The password is read from the LFTP_PASSWORD environment variable, keeping it off the command line and out of the process table. run_lftp () { lftp -p 21 --env-password -u "$FTP_USERNAME" -e "$SETTINGS; $1; bye" "$FTP_SERVER" } From 3004f401e7ff23a2df2b37543dc2daef7a471245 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 Jul 2026 19:00:52 +0200 Subject: [PATCH 128/177] Remove orphan code in job creation --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 93 +++++++++---------------- MaintenanceSolutionAzureSQLDatabase.sql | 8 +-- SHA256SUMS.txt | 12 ++-- 7 files changed, 47 insertions(+), 74 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index ed752547..c637779f 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-22 14:07:58 //-- + --// Version: 2026-07-22 18:59:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index d8f6646b..b0030240 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 14:07:58 //-- + --// Version: 2026-07-22 18:59:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index efe8ec54..330b34c9 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 14:07:58 //-- + --// Version: 2026-07-22 18:59:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 8c1ae4b9..feadd0c1 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 14:07:58 //-- + --// Version: 2026-07-22 18:59:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 7c896bb1..6c120893 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: 2026-07-22 14:07:58 +Version: 2026-07-22 18:59:22 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 14:07:58 //-- + --// Version: 2026-07-22 18:59:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 14:07:58 //-- + --// Version: 2026-07-22 18:59:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4975,7 +4975,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 14:07:58 //-- + --// Version: 2026-07-22 18:59:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6998,7 +6998,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 14:07:58 //-- + --// Version: 2026-07-22 18:59:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -9910,7 +9910,6 @@ BEGIN DECLARE @LogDirectory nvarchar(max) DECLARE @TokenServer nvarchar(max) - DECLARE @TokenJobID nvarchar(max) DECLARE @TokenJobName nvarchar(max) DECLARE @TokenStepID nvarchar(max) DECLARE @TokenStepName nvarchar(max) @@ -9927,8 +9926,6 @@ BEGIN CommandTSQL nvarchar(max), CommandCmdExec nvarchar(max), DatabaseName varchar(max), - OutputFileNamePart01 nvarchar(max), - OutputFileNamePart02 nvarchar(max), Selected bit DEFAULT 0, Completed bit DEFAULT 0) @@ -9937,8 +9934,6 @@ BEGIN 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) @@ -9956,7 +9951,6 @@ BEGIN 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))' @@ -10013,74 +10007,59 @@ BEGIN SET @JobOwner = SUSER_SNAME(0x01) END - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01, OutputFileNamePart02) + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) VALUES('DatabaseBackup - SYSTEM_DATABASES - FULL', 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''SYSTEM_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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') + @DatabaseName) - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01, OutputFileNamePart02) + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) VALUES('DatabaseBackup - USER_DATABASES - DIFF', 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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') + @DatabaseName) - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01, OutputFileNamePart02) + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) VALUES('DatabaseBackup - USER_DATABASES - FULL', 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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') + @DatabaseName) - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01, OutputFileNamePart02) + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) VALUES('DatabaseBackup - USER_DATABASES - LOG', 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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') + @DatabaseName) - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) VALUES('DatabaseIntegrityCheck - SYSTEM_DATABASES', 'EXECUTE [dbo].[DatabaseIntegrityCheck]' + CHAR(13) + CHAR(10) + '@Databases = ''SYSTEM_DATABASES'',' + CHAR(13) + CHAR(10) + '@NoInformationalMessages = ''Y'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', - @DatabaseName, - 'DatabaseIntegrityCheck') + @DatabaseName) - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) VALUES('DatabaseIntegrityCheck - USER_DATABASES', 'EXECUTE [dbo].[DatabaseIntegrityCheck]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + '@NoInformationalMessages = ''Y'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', - @DatabaseName, - 'DatabaseIntegrityCheck') + @DatabaseName) - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) VALUES('IndexOptimize - USER_DATABASES', 'EXECUTE [dbo].[IndexOptimize]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', - @DatabaseName, - 'IndexOptimize') + @DatabaseName) - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) VALUES('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') + 'msdb') - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) VALUES('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') + 'msdb') - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName, OutputFileNamePart01) + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) VALUES('CommandLog Cleanup', 'DELETE FROM [dbo].[CommandLog]' + CHAR(13) + CHAR(10) + 'WHERE StartTime < DATEADD(dd,-30,GETDATE())', - @DatabaseName, - 'CommandLogCleanup') + @DatabaseName) - INSERT INTO @Jobs ([Name], CommandCmdExec, OutputFileNamePart01) + INSERT INTO @Jobs ([Name], CommandCmdExec) VALUES('Output File Cleanup', - 'powershell.exe -NoProfile -Command "Get-ChildItem -LiteralPath ''' + COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + ''' -Filter ''*_*_*_*.txt'' -File | Where-Object { $_.LastWriteTime.Date -le (Get-Date).Date.AddDays(-30) } | ForEach-Object { Write-Output (''del '' + $_.FullName); Remove-Item -LiteralPath $_.FullName }"', - 'OutputFileCleanup') + 'powershell.exe -NoProfile -Command "Get-ChildItem -LiteralPath ''' + COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + ''' -Filter ''*_*_*_*.txt'' -File | Where-Object { $_.LastWriteTime.Date -le (Get-Date).Date.AddDays(-30) } | ForEach-Object { Write-Output (''del '' + $_.FullName); Remove-Item -LiteralPath $_.FullName }"') IF @AmazonRDS = 1 BEGIN @@ -10108,13 +10087,11 @@ BEGIN WHILE EXISTS (SELECT * FROM @Jobs WHERE Completed = 0 AND Selected = 1) BEGIN - SELECT @CurrentJobID = JobID, - @CurrentJobName = [Name], - @CurrentCommandTSQL = CommandTSQL, - @CurrentCommandCmdExec = CommandCmdExec, - @CurrentDatabaseName = DatabaseName, - @CurrentOutputFileNamePart01 = OutputFileNamePart01, - @CurrentOutputFileNamePart02 = OutputFileNamePart02 + SELECT TOP 1 @CurrentJobID = JobID, + @CurrentJobName = [Name], + @CurrentCommandTSQL = CommandTSQL, + @CurrentCommandCmdExec = CommandCmdExec, + @CurrentDatabaseName = DatabaseName FROM @Jobs WHERE Completed = 0 AND Selected = 1 @@ -10135,9 +10112,7 @@ BEGIN IF @AmazonRDS = 0 AND SERVERPROPERTY('EngineEdition') <> 8 BEGIN - 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' + SET @CurrentOutputFileName = COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + @DirectorySeparator + @TokenJobName + '_' + @TokenStepID + '_' + @TokenDate + '_' + @TokenTime + '.txt' IF LEN(@CurrentOutputFileName) > 200 SET @CurrentOutputFileName = NULL END @@ -10158,8 +10133,6 @@ BEGIN SET @CurrentCommandTSQL = NULL SET @CurrentCommandCmdExec = NULL SET @CurrentDatabaseName = NULL - SET @CurrentOutputFileNamePart01 = NULL - SET @CurrentOutputFileNamePart02 = NULL SET @CurrentJobStepCommand = NULL SET @CurrentJobStepSubSystem = NULL SET @CurrentJobStepDatabaseName = NULL diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index c1ebb11c..4e1aaec1 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-22 14:07:58 +Version: 2026-07-22 18:59:22 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 14:07:58 //-- + --// Version: 2026-07-22 18:59:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 14:07:58 //-- + --// Version: 2026-07-22 18:59:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 14:07:58 //-- + --// Version: 2026-07-22 18:59:22 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 5911c296..317ee32c 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -860bf38940301d7ab350eb5e110fe24ac6879461a216f35f787e24e14f53a133 CommandExecute.sql +4d1de0dbaae80471cbd09aa429e39df5c5cad31de9264eed018abe704d62c5c2 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -3daa9cbf75b2e4a1f2fcddff36c3195959e8ac74fcd0e8c8435dd2973a3ac1ea DatabaseBackup.sql -358a22c996e42989c0b84ef3018289bc8fe89b02a69e0754e260787033123bb2 DatabaseIntegrityCheck.sql -c89a4aaa22e7dfa535b4ea92defc87d4af44f3ade0f4879302446c32c822b9ce IndexOptimize.sql -14fbc5230eb99a95da5cc20166701ee55fae3babac66b77946454f671d39945b MaintenanceSolution.sql -4a013bc4bd8740aac0c7cebf970d125d9bd015ce5351521b10871e3098cd5a5d MaintenanceSolutionAzureSQLDatabase.sql +62d39fb4971b3fbb901299b505911ca07e49c271294cf5d90f37dca8dcfea269 DatabaseBackup.sql +9238944d4102d4775b2947c86636b86ec36ddcfacd9a36f097f7bb05bb464205 DatabaseIntegrityCheck.sql +753b52051b80e3384111630a085e8c6f2133d84c36a829d0121ca1104b20414d IndexOptimize.sql +155d918e19b12bdbb5d98135e08581e86f91e4f2f1cd39a71683e3410444b91a MaintenanceSolution.sql +b08f4c99cd8e1c4c41d6d106418d5ac14abd5c6d570704fed158928a3fc84789 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 90d59681bb0a3710aa4af3386da9ec202aa1561a Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 Jul 2026 20:19:03 +0200 Subject: [PATCH 129/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 46 ++++----- DatabaseIntegrityCheck.sql | 38 +++---- IndexOptimize.sql | 38 +++---- MaintenanceSolution.sql | 126 ++++++++++++------------ MaintenanceSolutionAzureSQLDatabase.sql | 80 +++++++-------- SHA256SUMS.txt | 12 +-- 7 files changed, 171 insertions(+), 171 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index c637779f..f44ee484 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-22 18:59:22 //-- + --// Version: 2026-07-22 20:03:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index b0030240..dcd91ac5 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 18:59:22 //-- + --// Version: 2026-07-22 20:03:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -124,6 +124,8 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupID uniqueidentifier + DECLARE @ContainedAvailabilityGroupListenerConnection bit DECLARE @DirectorySeparator nvarchar(max) DECLARE @Updated bit @@ -173,7 +175,6 @@ BEGIN DECLARE @CurrentDate datetime2 DECLARE @CurrentDateUTC datetime2 DECLARE @CurrentCleanupDate datetime2 - DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -322,6 +323,15 @@ BEGIN FROM sys.dm_os_host_info END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @CurrentCommand = 'SELECT @ParamContainedAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamContainedAvailabilityGroupID uniqueidentifier OUTPUT', @ParamContainedAvailabilityGroupID = @ContainedAvailabilityGroupID OUTPUT + END + + SET @ContainedAvailabilityGroupListenerConnection = CASE WHEN @ContainedAvailabilityGroupID IS NOT NULL THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -432,6 +442,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -2883,8 +2899,6 @@ BEGIN WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version < 15.04043 AND NOT (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND @Credential IS NULL THEN 65537 END - SET @CurrentContainedAvailabilityGroupListenerConnection = 0 - IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -2898,14 +2912,7 @@ BEGIN IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' - - EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT - - IF @CurrentAvailabilityGroupID IS NOT NULL - BEGIN - SET @CurrentContainedAvailabilityGroupListenerConnection = 1 - END + SET @CurrentAvailabilityGroupID = @ContainedAvailabilityGroupID SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -2972,7 +2979,7 @@ BEGIN AND NOT @CurrentInStandby = 1 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) - AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @CurrentContainedAvailabilityGroupListenerConnection = 0))) + AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) BEGIN SET @CurrentCommand = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' @@ -2988,11 +2995,11 @@ BEGIN IF @ChangeBackupType = 'Y' BEGIN - IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @CurrentContainedAvailabilityGroupListenerConnection = 0) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) + IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) BEGIN SET @CurrentBackupType = 'DIFF' END - IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @CurrentContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / NULLIF(@CurrentAllocatedExtentPageCount, 0) * 100 >= @MinModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) + IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / NULLIF(@CurrentAllocatedExtentPageCount, 0) * 100 >= @MinModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) BEGIN SET @CurrentBackupType = 'FULL' END @@ -3080,12 +3087,6 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN - IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -3185,7 +3186,7 @@ BEGIN 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 @CurrentContainedAvailabilityGroupListenerConnection = 0)) + AND NOT (@CurrentBackupType IN('DIFF','LOG') AND (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) @@ -4479,7 +4480,6 @@ BEGIN SET @CurrentDate = NULL SET @CurrentDateUTC = NULL SET @CurrentCleanupDate = NULL - SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 330b34c9..df17c752 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 18:59:22 //-- + --// Version: 2026-07-22 20:03:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -71,6 +71,8 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupID uniqueidentifier + DECLARE @ContainedAvailabilityGroupListenerConnection bit DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -85,7 +87,6 @@ BEGIN DECLARE @CurrentDatabaseState nvarchar(max) DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) - DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -217,6 +218,15 @@ BEGIN FROM sys.dm_os_host_info END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @CurrentCommand = 'SELECT @ParamContainedAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamContainedAvailabilityGroupID uniqueidentifier OUTPUT', @ParamContainedAvailabilityGroupID = @ContainedAvailabilityGroupID OUTPUT + END + + SET @ContainedAvailabilityGroupListenerConnection = CASE WHEN @ContainedAvailabilityGroupID IS NOT NULL THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -273,6 +283,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -1425,8 +1441,6 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @CurrentContainedAvailabilityGroupListenerConnection = 0 - IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -1440,14 +1454,7 @@ BEGIN IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' - - EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT - - IF @CurrentAvailabilityGroupID IS NOT NULL - BEGIN - SET @CurrentContainedAvailabilityGroupListenerConnection = 1 - END + SET @CurrentAvailabilityGroupID = @ContainedAvailabilityGroupID SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -1499,12 +1506,6 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN - IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -1962,7 +1963,6 @@ BEGIN SET @CurrentDatabaseState = NULL SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL - SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL diff --git a/IndexOptimize.sql b/IndexOptimize.sql index feadd0c1..ea955fca 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 18:59:22 //-- + --// Version: 2026-07-22 20:03:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -91,6 +91,8 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupID uniqueidentifier + DECLARE @ContainedAvailabilityGroupListenerConnection bit DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -107,7 +109,6 @@ BEGIN DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) DECLARE @CurrentDatabaseHasReadOnlyFileGroup bit - DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -367,6 +368,15 @@ BEGIN FROM sys.dm_os_host_info END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @CurrentCommand = 'SELECT @ParamContainedAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamContainedAvailabilityGroupID uniqueidentifier OUTPUT', @ParamContainedAvailabilityGroupID = @ContainedAvailabilityGroupID OUTPUT + END + + SET @ContainedAvailabilityGroupListenerConnection = CASE WHEN @ContainedAvailabilityGroupID IS NOT NULL THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -438,6 +448,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -1619,8 +1635,6 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @CurrentContainedAvailabilityGroupListenerConnection = 0 - IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -1634,14 +1648,7 @@ BEGIN IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' - - EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT - - IF @CurrentAvailabilityGroupID IS NOT NULL - BEGIN - SET @CurrentContainedAvailabilityGroupListenerConnection = 1 - END + SET @CurrentAvailabilityGroupID = @ContainedAvailabilityGroupID SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -1683,12 +1690,6 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN - IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -2904,7 +2905,6 @@ BEGIN SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL SET @CurrentDatabaseHasReadOnlyFileGroup = NULL - SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 6c120893..64545bc7 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: 2026-07-22 18:59:22 +Version: 2026-07-22 20:03:34 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 18:59:22 //-- + --// Version: 2026-07-22 20:03:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 18:59:22 //-- + --// Version: 2026-07-22 20:03:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -523,6 +523,8 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupID uniqueidentifier + DECLARE @ContainedAvailabilityGroupListenerConnection bit DECLARE @DirectorySeparator nvarchar(max) DECLARE @Updated bit @@ -572,7 +574,6 @@ BEGIN DECLARE @CurrentDate datetime2 DECLARE @CurrentDateUTC datetime2 DECLARE @CurrentCleanupDate datetime2 - DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -721,6 +722,15 @@ BEGIN FROM sys.dm_os_host_info END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @CurrentCommand = 'SELECT @ParamContainedAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamContainedAvailabilityGroupID uniqueidentifier OUTPUT', @ParamContainedAvailabilityGroupID = @ContainedAvailabilityGroupID OUTPUT + END + + SET @ContainedAvailabilityGroupListenerConnection = CASE WHEN @ContainedAvailabilityGroupID IS NOT NULL THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -831,6 +841,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -3282,8 +3298,6 @@ BEGIN WHEN @MaxTransferSize IS NULL AND @Compress = 'Y' AND @CurrentIsEncrypted = 1 AND @BackupSoftware IS NULL AND (@Version < 15.04043 AND NOT (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND @Credential IS NULL THEN 65537 END - SET @CurrentContainedAvailabilityGroupListenerConnection = 0 - IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -3297,14 +3311,7 @@ BEGIN IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' - - EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT - - IF @CurrentAvailabilityGroupID IS NOT NULL - BEGIN - SET @CurrentContainedAvailabilityGroupListenerConnection = 1 - END + SET @CurrentAvailabilityGroupID = @ContainedAvailabilityGroupID SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -3371,7 +3378,7 @@ BEGIN AND NOT @CurrentInStandby = 1 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) - AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @CurrentContainedAvailabilityGroupListenerConnection = 0))) + AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) BEGIN SET @CurrentCommand = 'SELECT @ParamAllocatedExtentPageCount = SUM(allocated_extent_page_count), @ParamModifiedExtentPageCount = SUM(modified_extent_page_count) FROM sys.dm_db_file_space_usage' @@ -3387,11 +3394,11 @@ BEGIN IF @ChangeBackupType = 'Y' BEGIN - IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @CurrentContainedAvailabilityGroupListenerConnection = 0) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) + IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) BEGIN SET @CurrentBackupType = 'DIFF' END - IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @CurrentContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / NULLIF(@CurrentAllocatedExtentPageCount, 0) * 100 >= @MinModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) + IF @CurrentBackupType = 'DIFF' AND ((@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) OR @CurrentDifferentialBaseLSN IS NULL OR (@CurrentModifiedExtentPageCount * 1. / NULLIF(@CurrentAllocatedExtentPageCount, 0) * 100 >= @MinModificationLevel) OR (COALESCE(CAST(@CurrentAllocatedExtentPageCount AS bigint) * 8192, CAST(@CurrentDatabaseSize AS bigint) * 8192) < CAST(@MinDatabaseSizeForDifferentialBackup AS bigint) * 1024 * 1024)) BEGIN SET @CurrentBackupType = 'FULL' END @@ -3479,12 +3486,6 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN - IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -3584,7 +3585,7 @@ BEGIN 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 @CurrentContainedAvailabilityGroupListenerConnection = 0)) + AND NOT (@CurrentBackupType IN('DIFF','LOG') AND (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) @@ -4878,7 +4879,6 @@ BEGIN SET @CurrentDate = NULL SET @CurrentDateUTC = NULL SET @CurrentCleanupDate = NULL - SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL @@ -4975,7 +4975,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 18:59:22 //-- + --// Version: 2026-07-22 20:03:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5006,6 +5006,8 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupID uniqueidentifier + DECLARE @ContainedAvailabilityGroupListenerConnection bit DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -5020,7 +5022,6 @@ BEGIN DECLARE @CurrentDatabaseState nvarchar(max) DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) - DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -5152,6 +5153,15 @@ BEGIN FROM sys.dm_os_host_info END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @CurrentCommand = 'SELECT @ParamContainedAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamContainedAvailabilityGroupID uniqueidentifier OUTPUT', @ParamContainedAvailabilityGroupID = @ContainedAvailabilityGroupID OUTPUT + END + + SET @ContainedAvailabilityGroupListenerConnection = CASE WHEN @ContainedAvailabilityGroupID IS NOT NULL THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -5208,6 +5218,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -6360,8 +6376,6 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @CurrentContainedAvailabilityGroupListenerConnection = 0 - IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -6375,14 +6389,7 @@ BEGIN IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' - - EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT - - IF @CurrentAvailabilityGroupID IS NOT NULL - BEGIN - SET @CurrentContainedAvailabilityGroupListenerConnection = 1 - END + SET @CurrentAvailabilityGroupID = @ContainedAvailabilityGroupID SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -6434,12 +6441,6 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN - IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -6897,7 +6898,6 @@ BEGIN SET @CurrentDatabaseState = NULL SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL - SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL @@ -6998,7 +6998,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 18:59:22 //-- + --// Version: 2026-07-22 20:03:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7033,6 +7033,8 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupID uniqueidentifier + DECLARE @ContainedAvailabilityGroupListenerConnection bit DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -7049,7 +7051,6 @@ BEGIN DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) DECLARE @CurrentDatabaseHasReadOnlyFileGroup bit - DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -7309,6 +7310,15 @@ BEGIN FROM sys.dm_os_host_info END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @CurrentCommand = 'SELECT @ParamContainedAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamContainedAvailabilityGroupID uniqueidentifier OUTPUT', @ParamContainedAvailabilityGroupID = @ContainedAvailabilityGroupID OUTPUT + END + + SET @ContainedAvailabilityGroupListenerConnection = CASE WHEN @ContainedAvailabilityGroupID IS NOT NULL THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -7380,6 +7390,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -8561,8 +8577,6 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @CurrentContainedAvailabilityGroupListenerConnection = 0 - IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -8576,14 +8590,7 @@ BEGIN IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' - - EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT - - IF @CurrentAvailabilityGroupID IS NOT NULL - BEGIN - SET @CurrentContainedAvailabilityGroupListenerConnection = 1 - END + SET @CurrentAvailabilityGroupID = @ContainedAvailabilityGroupID SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -8625,12 +8632,6 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN - IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -9846,7 +9847,6 @@ BEGIN SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL SET @CurrentDatabaseHasReadOnlyFileGroup = NULL - SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 4e1aaec1..4a2c0232 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-22 18:59:22 +Version: 2026-07-22 20:03:34 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 18:59:22 //-- + --// Version: 2026-07-22 20:03:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 18:59:22 //-- + --// Version: 2026-07-22 20:03:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -425,6 +425,8 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupID uniqueidentifier + DECLARE @ContainedAvailabilityGroupListenerConnection bit DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -439,7 +441,6 @@ BEGIN DECLARE @CurrentDatabaseState nvarchar(max) DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) - DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -571,6 +572,15 @@ BEGIN FROM sys.dm_os_host_info END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @CurrentCommand = 'SELECT @ParamContainedAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamContainedAvailabilityGroupID uniqueidentifier OUTPUT', @ParamContainedAvailabilityGroupID = @ContainedAvailabilityGroupID OUTPUT + END + + SET @ContainedAvailabilityGroupListenerConnection = CASE WHEN @ContainedAvailabilityGroupID IS NOT NULL THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -627,6 +637,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -1779,8 +1795,6 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @CurrentContainedAvailabilityGroupListenerConnection = 0 - IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -1794,14 +1808,7 @@ BEGIN IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' - - EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT - - IF @CurrentAvailabilityGroupID IS NOT NULL - BEGIN - SET @CurrentContainedAvailabilityGroupListenerConnection = 1 - END + SET @CurrentAvailabilityGroupID = @ContainedAvailabilityGroupID SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -1853,12 +1860,6 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN - IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -2316,7 +2317,6 @@ BEGIN SET @CurrentDatabaseState = NULL SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL - SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 18:59:22 //-- + --// Version: 2026-07-22 20:03:34 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2452,6 +2452,8 @@ BEGIN DECLARE @CurrentParameterMessage nvarchar(max) DECLARE @HostPlatform nvarchar(max) + DECLARE @ContainedAvailabilityGroupID uniqueidentifier + DECLARE @ContainedAvailabilityGroupListenerConnection bit DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -2468,7 +2470,6 @@ BEGIN DECLARE @CurrentInStandby bit DECLARE @CurrentRecoveryModel nvarchar(max) DECLARE @CurrentDatabaseHasReadOnlyFileGroup bit - DECLARE @CurrentContainedAvailabilityGroupListenerConnection bit DECLARE @CurrentAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) @@ -2728,6 +2729,15 @@ BEGIN FROM sys.dm_os_host_info END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @CurrentCommand = 'SELECT @ParamContainedAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' + + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamContainedAvailabilityGroupID uniqueidentifier OUTPUT', @ParamContainedAvailabilityGroupID = @ContainedAvailabilityGroupID OUTPUT + END + + SET @ContainedAvailabilityGroupListenerConnection = CASE WHEN @ContainedAvailabilityGroupID IS NOT NULL THEN 1 ELSE 0 END + DECLARE @AmazonRDS bit = CASE WHEN @EngineEdition IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END ---------------------------------------------------------------------------------------------------- @@ -2799,6 +2809,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) + BEGIN + SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @ContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @ContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -3980,8 +3996,6 @@ BEGIN RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END - SET @CurrentContainedAvailabilityGroupListenerConnection = 0 - IF @IsHadrEnabled = 1 BEGIN SELECT @CurrentAvailabilityGroupReplicaID = databases.replica_id @@ -3995,14 +4009,7 @@ BEGIN IF @CurrentAvailabilityGroupReplicaID IS NULL AND @CurrentAvailabilityGroupID IS NULL AND @Version >= 16 BEGIN - SET @CurrentCommand = 'SELECT @ParamAvailabilityGroupID = contained_availability_group_id FROM sys.dm_exec_sessions WHERE session_id = @@SPID' - - EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamAvailabilityGroupID uniqueidentifier OUTPUT', @ParamAvailabilityGroupID = @CurrentAvailabilityGroupID OUTPUT - - IF @CurrentAvailabilityGroupID IS NOT NULL - BEGIN - SET @CurrentContainedAvailabilityGroupListenerConnection = 1 - END + SET @CurrentAvailabilityGroupID = @ContainedAvailabilityGroupID SELECT @CurrentAvailabilityGroupReplicaID = replica_id FROM sys.dm_hadr_availability_replica_states @@ -4044,12 +4051,6 @@ BEGIN IF @CurrentAvailabilityGroup IS NOT NULL BEGIN - IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) - BEGIN - SET @StartMessage = 'Contained availability group connection: ' + CASE WHEN @CurrentContainedAvailabilityGroupListenerConnection = 1 THEN 'Yes' WHEN @CurrentContainedAvailabilityGroupListenerConnection = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END - SET @DatabaseMessage = 'Availability group: ' + ISNULL(@CurrentAvailabilityGroup,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -5265,7 +5266,6 @@ BEGIN SET @CurrentInStandby = NULL SET @CurrentRecoveryModel = NULL SET @CurrentDatabaseHasReadOnlyFileGroup = NULL - SET @CurrentContainedAvailabilityGroupListenerConnection = NULL SET @CurrentAvailabilityGroupReplicaID = NULL SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 317ee32c..3ebe5558 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -4d1de0dbaae80471cbd09aa429e39df5c5cad31de9264eed018abe704d62c5c2 CommandExecute.sql +1ab30311724f672e5b7fc15479b65ba96e7ff92b0b5f0f4a200de1487d9f0847 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -62d39fb4971b3fbb901299b505911ca07e49c271294cf5d90f37dca8dcfea269 DatabaseBackup.sql -9238944d4102d4775b2947c86636b86ec36ddcfacd9a36f097f7bb05bb464205 DatabaseIntegrityCheck.sql -753b52051b80e3384111630a085e8c6f2133d84c36a829d0121ca1104b20414d IndexOptimize.sql -155d918e19b12bdbb5d98135e08581e86f91e4f2f1cd39a71683e3410444b91a MaintenanceSolution.sql -b08f4c99cd8e1c4c41d6d106418d5ac14abd5c6d570704fed158928a3fc84789 MaintenanceSolutionAzureSQLDatabase.sql +b5546c77fa739cbfc2d9d9e214101c208f0cd186593f93a9a10a93add26dbf52 DatabaseBackup.sql +92686d28bf412b62487b3aa615604a2b685b9be0c0eee8f6d0046f87c5b97069 DatabaseIntegrityCheck.sql +09b3c46e36b9fe071064b0032309298262b30c3d6bac49c4d1089436dbba84d6 IndexOptimize.sql +05625f543e9d82a8a8e9119c576cf2138a7c30b0753d1048fb10eca2a6c7b00d MaintenanceSolution.sql +58c2f6e8869f9c009f55f59a83073edbc44e9b259143d0856c4fffee3884143f MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 0fe22a850242b88cdb00d2c75f958bf8f0dbd905 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 Jul 2026 21:58:16 +0200 Subject: [PATCH 130/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 ++++++------ MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 20 insertions(+), 20 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index f44ee484..77255b34 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-22 20:03:34 //-- + --// Version: 2026-07-22 21:56:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index dcd91ac5..c615e3db 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 20:03:34 //-- + --// Version: 2026-07-22 21:56:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index df17c752..d0162aa3 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 20:03:34 //-- + --// Version: 2026-07-22 21:56:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index ea955fca..710fd92c 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 20:03:34 //-- + --// Version: 2026-07-22 21:56:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 64545bc7..12f95a2d 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: 2026-07-22 20:03:34 +Version: 2026-07-22 21:56:04 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 20:03:34 //-- + --// Version: 2026-07-22 21:56:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 20:03:34 //-- + --// Version: 2026-07-22 21:56:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4975,7 +4975,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 20:03:34 //-- + --// Version: 2026-07-22 21:56:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6998,7 +6998,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 20:03:34 //-- + --// Version: 2026-07-22 21:56:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -10059,7 +10059,7 @@ BEGIN INSERT INTO @Jobs ([Name], CommandCmdExec) VALUES('Output File Cleanup', - 'powershell.exe -NoProfile -Command "Get-ChildItem -LiteralPath ''' + COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + ''' -Filter ''*_*_*_*.txt'' -File | Where-Object { $_.LastWriteTime.Date -le (Get-Date).Date.AddDays(-30) } | ForEach-Object { Write-Output (''del '' + $_.FullName); Remove-Item -LiteralPath $_.FullName }"') + 'powershell.exe -NoProfile -Command "Get-ChildItem -LiteralPath ''' + REPLACE(COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory),'''','''''') + ''' -Filter ''*_*_*_*.txt'' -File | Where-Object { $_.LastWriteTime.Date -le (Get-Date).Date.AddDays(-30) } | ForEach-Object { Write-Output (''del '' + $_.FullName); Remove-Item -LiteralPath $_.FullName }"') IF @AmazonRDS = 1 BEGIN diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 4a2c0232..872fc623 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-22 20:03:34 +Version: 2026-07-22 21:56:04 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 20:03:34 //-- + --// Version: 2026-07-22 21:56:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 20:03:34 //-- + --// Version: 2026-07-22 21:56:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 20:03:34 //-- + --// Version: 2026-07-22 21:56:04 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 3ebe5558..bdd0a954 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -1ab30311724f672e5b7fc15479b65ba96e7ff92b0b5f0f4a200de1487d9f0847 CommandExecute.sql +255cec4c899f02f166d6a53133dfe75d6aa1c13715913b09a2ac1f22b65bc5ab CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -b5546c77fa739cbfc2d9d9e214101c208f0cd186593f93a9a10a93add26dbf52 DatabaseBackup.sql -92686d28bf412b62487b3aa615604a2b685b9be0c0eee8f6d0046f87c5b97069 DatabaseIntegrityCheck.sql -09b3c46e36b9fe071064b0032309298262b30c3d6bac49c4d1089436dbba84d6 IndexOptimize.sql -05625f543e9d82a8a8e9119c576cf2138a7c30b0753d1048fb10eca2a6c7b00d MaintenanceSolution.sql -58c2f6e8869f9c009f55f59a83073edbc44e9b259143d0856c4fffee3884143f MaintenanceSolutionAzureSQLDatabase.sql +c3d27def0a8587a321fe7b84a69da78b1be52f0032bdd7feef3e0e682d9bd0d8 DatabaseBackup.sql +670427a40c7ec3b0f8e3295fe211a0385d6f392eadde4fe26f9257f35319f880 DatabaseIntegrityCheck.sql +d162f07803223a4d48a210263b194ad0fb2347ee9245726a770cb683bc45bffb IndexOptimize.sql +685456ce6d847a4402814c0d28a09dd0c2d984cb6d6157d69b2fef20669322f9 MaintenanceSolution.sql +b3757ee5c69286c09db609f7db5e550d69e2a292b52a60ad5b8e7d58975aa74c MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 91cb88f4ad66b0d5f583e5e344f2e6db88a3f9da Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 22 Jul 2026 23:47:24 +0200 Subject: [PATCH 131/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 4 ++-- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 ++++++------ MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 77255b34..3a46442f 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-22 21:56:04 //-- + --// Version: 2026-07-22 23:46:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index c615e3db..4799d3a8 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 21:56:04 //-- + --// Version: 2026-07-22 23:46:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3239,7 +3239,7 @@ BEGIN IF @Description IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}','') IF @BackupSetName IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@BackupSetName,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupSetName}','') - IF @Directory IS NULL AND @MirrorDirectory IS NULL AND @URL IS NULL AND @DefaultDirectory LIKE '%' + '.' + @@SERVICENAME + @DirectorySeparator + 'MSSQL' + @DirectorySeparator + 'Backup' + IF @Directory IS NULL AND @MirrorDirectory IS NULL AND @URL IS NULL AND @DefaultDirectory LIKE '%' + '.' + REPLACE(@@SERVICENAME,'_','[_]') + @DirectorySeparator + 'MSSQL' + @DirectorySeparator + 'Backup' BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}','') SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}','') diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index d0162aa3..a9013e95 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 21:56:04 //-- + --// Version: 2026-07-22 23:46:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 710fd92c..8c07df4f 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 21:56:04 //-- + --// Version: 2026-07-22 23:46:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 12f95a2d..1f658d47 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: 2026-07-22 21:56:04 +Version: 2026-07-22 23:46:33 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 21:56:04 //-- + --// Version: 2026-07-22 23:46:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 21:56:04 //-- + --// Version: 2026-07-22 23:46:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3638,7 +3638,7 @@ BEGIN IF @Description IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}','') IF @BackupSetName IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@BackupSetName,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{BackupSetName}','') - IF @Directory IS NULL AND @MirrorDirectory IS NULL AND @URL IS NULL AND @DefaultDirectory LIKE '%' + '.' + @@SERVICENAME + @DirectorySeparator + 'MSSQL' + @DirectorySeparator + 'Backup' + IF @Directory IS NULL AND @MirrorDirectory IS NULL AND @URL IS NULL AND @DefaultDirectory LIKE '%' + '.' + REPLACE(@@SERVICENAME,'_','[_]') + @DirectorySeparator + 'MSSQL' + @DirectorySeparator + 'Backup' BEGIN SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}','') SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}','') @@ -4975,7 +4975,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 21:56:04 //-- + --// Version: 2026-07-22 23:46:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6998,7 +6998,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 21:56:04 //-- + --// Version: 2026-07-22 23:46:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 872fc623..724cd151 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-22 21:56:04 +Version: 2026-07-22 23:46:33 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 21:56:04 //-- + --// Version: 2026-07-22 23:46:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 21:56:04 //-- + --// Version: 2026-07-22 23:46:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 21:56:04 //-- + --// Version: 2026-07-22 23:46:33 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index bdd0a954..5495c73b 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -255cec4c899f02f166d6a53133dfe75d6aa1c13715913b09a2ac1f22b65bc5ab CommandExecute.sql +71f0367d66f06a3ca9fe88dcf03fe762610e56de129219cfb573c31198b5d025 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -c3d27def0a8587a321fe7b84a69da78b1be52f0032bdd7feef3e0e682d9bd0d8 DatabaseBackup.sql -670427a40c7ec3b0f8e3295fe211a0385d6f392eadde4fe26f9257f35319f880 DatabaseIntegrityCheck.sql -d162f07803223a4d48a210263b194ad0fb2347ee9245726a770cb683bc45bffb IndexOptimize.sql -685456ce6d847a4402814c0d28a09dd0c2d984cb6d6157d69b2fef20669322f9 MaintenanceSolution.sql -b3757ee5c69286c09db609f7db5e550d69e2a292b52a60ad5b8e7d58975aa74c MaintenanceSolutionAzureSQLDatabase.sql +20a248b861316bfc2822fe82506e9e3941c59893f4157fcb5aa2e851d97bfebd DatabaseBackup.sql +38c0cef0a2b62139bce5c45944b37f1f08760b261dde2041add5b66b8474ae28 DatabaseIntegrityCheck.sql +8da5a69a245925ea99e198cad654baa1c31c027deb8c283cb1c2e910de15554d IndexOptimize.sql +1791f866508e0932164720f4ab15860f028bc4874b6d442ce7c421d413a64b8c MaintenanceSolution.sql +bc48478247802f9ab6906749bf1065cc6e2942f0ec1fa7cc6d4aa53e11e830fc MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 1306169e9868a6a9557977dd4a6924c555587246 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 23 Jul 2026 00:31:11 +0200 Subject: [PATCH 132/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 11 ++++++++++- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 19 ++++++++++++++----- MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 37 insertions(+), 19 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 3a46442f..c92550ac 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-22 23:46:33 //-- + --// Version: 2026-07-23 00:22:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 4799d3a8..e01509a1 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 23:46:33 //-- + --// Version: 2026-07-23 00:22:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2930,6 +2930,15 @@ BEGIN WHERE replica_id = @CurrentAvailabilityGroupReplicaID AND database_id = DB_ID(@CurrentDatabaseName) + IF @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState IS NULL AND @ContainedAvailabilityGroupListenerConnection = 1 + BEGIN + SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, + @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc + FROM sys.dm_hadr_database_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + AND DB_NAME(database_id) = @CurrentDatabaseName + END + SELECT @CurrentAvailabilityGroup = [name], @CurrentAvailabilityGroupBackupPreference = UPPER(automated_backup_preference_desc) FROM sys.availability_groups diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index a9013e95..f0b92b4d 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 23:46:33 //-- + --// Version: 2026-07-23 00:22:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 8c07df4f..2aacef0c 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 23:46:33 //-- + --// Version: 2026-07-23 00:22:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 1f658d47..d3981d6e 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: 2026-07-22 23:46:33 +Version: 2026-07-23 00:22:31 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 23:46:33 //-- + --// Version: 2026-07-23 00:22:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 23:46:33 //-- + --// Version: 2026-07-23 00:22:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3329,6 +3329,15 @@ BEGIN WHERE replica_id = @CurrentAvailabilityGroupReplicaID AND database_id = DB_ID(@CurrentDatabaseName) + IF @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState IS NULL AND @ContainedAvailabilityGroupListenerConnection = 1 + BEGIN + SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, + @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc + FROM sys.dm_hadr_database_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + AND DB_NAME(database_id) = @CurrentDatabaseName + END + SELECT @CurrentAvailabilityGroup = [name], @CurrentAvailabilityGroupBackupPreference = UPPER(automated_backup_preference_desc) FROM sys.availability_groups @@ -4975,7 +4984,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 23:46:33 //-- + --// Version: 2026-07-23 00:22:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6998,7 +7007,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 23:46:33 //-- + --// Version: 2026-07-23 00:22:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 724cd151..baaffdae 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-22 23:46:33 +Version: 2026-07-23 00:22:31 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 23:46:33 //-- + --// Version: 2026-07-23 00:22:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 23:46:33 //-- + --// Version: 2026-07-23 00:22:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-22 23:46:33 //-- + --// Version: 2026-07-23 00:22:31 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 5495c73b..53b7dde5 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -71f0367d66f06a3ca9fe88dcf03fe762610e56de129219cfb573c31198b5d025 CommandExecute.sql +95987cdf6b0a9e9421dca4c16fae87d618e109a507a931416182860c97bce7af CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -20a248b861316bfc2822fe82506e9e3941c59893f4157fcb5aa2e851d97bfebd DatabaseBackup.sql -38c0cef0a2b62139bce5c45944b37f1f08760b261dde2041add5b66b8474ae28 DatabaseIntegrityCheck.sql -8da5a69a245925ea99e198cad654baa1c31c027deb8c283cb1c2e910de15554d IndexOptimize.sql -1791f866508e0932164720f4ab15860f028bc4874b6d442ce7c421d413a64b8c MaintenanceSolution.sql -bc48478247802f9ab6906749bf1065cc6e2942f0ec1fa7cc6d4aa53e11e830fc MaintenanceSolutionAzureSQLDatabase.sql +4ab27a23823434f9da7a859e267665e35e9e88462bd1ecd91b4c1484d80efef9 DatabaseBackup.sql +2b8c408cae1692303dad072010b10b8cfc27798e1e3181dcf8644eba06c4c35b DatabaseIntegrityCheck.sql +5c6e768c5bbd2a1773b2694d7c49f2a1fa55fd50cb738ebe10def0976c905bf7 IndexOptimize.sql +b5d97ffebc13d49856d8787d06c8c9e97700c15e1bac428a16113b43df066927 MaintenanceSolution.sql +769eb5a2c2777a8ba85c42d3d4cf4b2cf98600823338a0de888445a53abc8696 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From ffc7cf90be6ef76ba58480dd0d68e5486e94f637 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 23 Jul 2026 16:37:01 +0200 Subject: [PATCH 133/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 20 +++++++++++++++++- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 28 ++++++++++++++++++++----- MaintenanceSolutionAzureSQLDatabase.sql | 8 +++---- SHA256SUMS.txt | 12 +++++------ 7 files changed, 55 insertions(+), 19 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index c92550ac..fa65fb85 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-23 00:22:31 //-- + --// Version: 2026-07-23 16:34:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index e01509a1..e1c11647 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 00:22:31 //-- + --// Version: 2026-07-23 16:34:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1518,6 +1518,24 @@ BEGIN VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 5) END + IF @MaxTransferSize > 4194304 AND @URL IS NULL AND @BackupSoftware IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 6) + END + + IF @MaxTransferSize > 4194304 AND @URL LIKE 'https%' AND @Credential IS NULL AND @BackupSoftware IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 7) + END + + IF @MaxTransferSize < 5242880 AND @URL LIKE 's3%' AND @BackupSoftware IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 8) + END + ---------------------------------------------------------------------------------------------------- IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index f0b92b4d..83a7d22d 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 00:22:31 //-- + --// Version: 2026-07-23 16:34:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 2aacef0c..39c7e23b 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 00:22:31 //-- + --// Version: 2026-07-23 16:34:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index d3981d6e..a25ac5dc 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: 2026-07-23 00:22:31 +Version: 2026-07-23 16:34:50 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 00:22:31 //-- + --// Version: 2026-07-23 16:34:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 00:22:31 //-- + --// Version: 2026-07-23 16:34:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1917,6 +1917,24 @@ BEGIN VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 5) END + IF @MaxTransferSize > 4194304 AND @URL IS NULL AND @BackupSoftware IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 6) + END + + IF @MaxTransferSize > 4194304 AND @URL LIKE 'https%' AND @Credential IS NULL AND @BackupSoftware IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 7) + END + + IF @MaxTransferSize < 5242880 AND @URL LIKE 's3%' AND @BackupSoftware IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 8) + END + ---------------------------------------------------------------------------------------------------- IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 @@ -4984,7 +5002,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 00:22:31 //-- + --// Version: 2026-07-23 16:34:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7007,7 +7025,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 00:22:31 //-- + --// Version: 2026-07-23 16:34:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index baaffdae..80f53695 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-23 00:22:31 +Version: 2026-07-23 16:34:50 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 00:22:31 //-- + --// Version: 2026-07-23 16:34:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 00:22:31 //-- + --// Version: 2026-07-23 16:34:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 00:22:31 //-- + --// Version: 2026-07-23 16:34:50 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 53b7dde5..ddb6dd15 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -95987cdf6b0a9e9421dca4c16fae87d618e109a507a931416182860c97bce7af CommandExecute.sql +de114e88c6523241a7e3e8436df8fcf5983bc088c87ab16ca8a5fce7584ad965 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -4ab27a23823434f9da7a859e267665e35e9e88462bd1ecd91b4c1484d80efef9 DatabaseBackup.sql -2b8c408cae1692303dad072010b10b8cfc27798e1e3181dcf8644eba06c4c35b DatabaseIntegrityCheck.sql -5c6e768c5bbd2a1773b2694d7c49f2a1fa55fd50cb738ebe10def0976c905bf7 IndexOptimize.sql -b5d97ffebc13d49856d8787d06c8c9e97700c15e1bac428a16113b43df066927 MaintenanceSolution.sql -769eb5a2c2777a8ba85c42d3d4cf4b2cf98600823338a0de888445a53abc8696 MaintenanceSolutionAzureSQLDatabase.sql +1dac4d488c8cfc3a3e56a8bed074f18d9059eff22d8d3259eeff0d8e7c6b6a3b DatabaseBackup.sql +97d4f0b3891add5ee563976b6215a0daf4581517d6c0145ecac81dd2c7979bad DatabaseIntegrityCheck.sql +175457d199b84ddcc803c243a2941326a7ee9669dab7f590d1a9d3a9811f2f5e IndexOptimize.sql +8f0f193fd5a58cb5255021c26b08c7382fe8dd0efc2933d72efefae36f7be61c MaintenanceSolution.sql +9ee7561e32e001b3840f76251ae53b0e49a8b8d341cbc1caaf555323ff986600 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From ab78b69e2a4510c580a679d451d730b39b6c3d91 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 23 Jul 2026 18:44:44 +0200 Subject: [PATCH 134/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 29 +++++++++---------- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 37 ++++++++++++------------- MaintenanceSolutionAzureSQLDatabase.sql | 8 +++--- SHA256SUMS.txt | 12 ++++---- 7 files changed, 43 insertions(+), 49 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index fa65fb85..9d3d598c 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-23 16:34:50 //-- + --// Version: 2026-07-23 18:43:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index e1c11647..564acd09 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 16:34:50 //-- + --// Version: 2026-07-23 18:43:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2034,10 +2034,10 @@ BEGIN VALUES('The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 2) END - IF @MinModificationLevel IS NOT NULL AND @BackupType <> 'DIFF' + IF @MinModificationLevel IS NOT NULL AND @BackupType NOT IN('DIFF','LOG') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @MinModificationLevel can only be used for differential backups.', 16, 3) + VALUES('The parameter @MinModificationLevel can only be used for differential and transaction log backups.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -3001,25 +3001,25 @@ BEGIN WHERE database_id = DB_ID(@CurrentDatabaseName) END + SET @CurrentBackupType = @BackupType + + IF (@Version >= 16.04265 AND @Version < 17) OR @Version >= 17.04065 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous') + BEGIN + SET @BackupInProgress = CASE WHEN EXISTS(SELECT * FROM sys.dm_exec_requests WHERE database_id = DB_ID(@CurrentDatabaseName) AND command = 'BACKUP DATABASE') THEN 1 ELSE 0 END + END + IF @CurrentDatabaseState = 'ONLINE' AND NOT @CurrentUserAccess = 'SINGLE_USER' AND NOT @CurrentInStandby = 1 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) - AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) + AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) BEGIN 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 = @CurrentCommand, @params = N'@ParamAllocatedExtentPageCount bigint OUTPUT, @ParamModifiedExtentPageCount bigint OUTPUT', @ParamAllocatedExtentPageCount = @CurrentAllocatedExtentPageCount OUTPUT, @ParamModifiedExtentPageCount = @CurrentModifiedExtentPageCount OUTPUT END - IF (@Version >= 16.04265 AND @Version < 17) OR @Version >= 17.04065 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous') - BEGIN - SET @BackupInProgress = CASE WHEN EXISTS(SELECT * FROM sys.dm_exec_requests WHERE database_id = DB_ID(@CurrentDatabaseName) AND command = 'BACKUP DATABASE') THEN 1 ELSE 0 END - END - - SET @CurrentBackupType = @BackupType - IF @ChangeBackupType = 'Y' BEGIN IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) @@ -3181,11 +3181,8 @@ BEGIN SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar(max)),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentBackupType = 'LOG' AND @ChangeBackupType = 'Y' - BEGIN - SET @DatabaseMessage = 'Full or differential backup in progress: ' + CASE WHEN @BackupInProgress = 1 THEN 'Yes' WHEN @BackupInProgress = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - END + SET @DatabaseMessage = 'Full or differential backup in progress: ' + CASE WHEN @BackupInProgress = 1 THEN 'Yes' WHEN @BackupInProgress = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentBackupType IN('DIFF','FULL') BEGIN diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 83a7d22d..e65b92b7 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 16:34:50 //-- + --// Version: 2026-07-23 18:43:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 39c7e23b..d855bc93 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 16:34:50 //-- + --// Version: 2026-07-23 18:43:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index a25ac5dc..0ace7f08 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: 2026-07-23 16:34:50 +Version: 2026-07-23 18:43:44 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 16:34:50 //-- + --// Version: 2026-07-23 18:43:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 16:34:50 //-- + --// Version: 2026-07-23 18:43:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2433,10 +2433,10 @@ BEGIN VALUES('The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 2) END - IF @MinModificationLevel IS NOT NULL AND @BackupType <> 'DIFF' + IF @MinModificationLevel IS NOT NULL AND @BackupType NOT IN('DIFF','LOG') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @MinModificationLevel can only be used for differential backups.', 16, 3) + VALUES('The parameter @MinModificationLevel can only be used for differential and transaction log backups.', 16, 3) END ---------------------------------------------------------------------------------------------------- @@ -3400,25 +3400,25 @@ BEGIN WHERE database_id = DB_ID(@CurrentDatabaseName) END + SET @CurrentBackupType = @BackupType + + IF (@Version >= 16.04265 AND @Version < 17) OR @Version >= 17.04065 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous') + BEGIN + SET @BackupInProgress = CASE WHEN EXISTS(SELECT * FROM sys.dm_exec_requests WHERE database_id = DB_ID(@CurrentDatabaseName) AND command = 'BACKUP DATABASE') THEN 1 ELSE 0 END + END + IF @CurrentDatabaseState = 'ONLINE' AND NOT @CurrentUserAccess = 'SINGLE_USER' AND NOT @CurrentInStandby = 1 AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) - AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) + AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) BEGIN 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 = @CurrentCommand, @params = N'@ParamAllocatedExtentPageCount bigint OUTPUT, @ParamModifiedExtentPageCount bigint OUTPUT', @ParamAllocatedExtentPageCount = @CurrentAllocatedExtentPageCount OUTPUT, @ParamModifiedExtentPageCount = @CurrentModifiedExtentPageCount OUTPUT END - IF (@Version >= 16.04265 AND @Version < 17) OR @Version >= 17.04065 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous') - BEGIN - SET @BackupInProgress = CASE WHEN EXISTS(SELECT * FROM sys.dm_exec_requests WHERE database_id = DB_ID(@CurrentDatabaseName) AND command = 'BACKUP DATABASE') THEN 1 ELSE 0 END - END - - SET @CurrentBackupType = @BackupType - IF @ChangeBackupType = 'Y' BEGIN IF @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) @@ -3580,11 +3580,8 @@ BEGIN SET @DatabaseMessage = 'Last log backup LSN: ' + ISNULL(CAST(@CurrentLogLSN AS nvarchar(max)),'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - IF @CurrentBackupType = 'LOG' AND @ChangeBackupType = 'Y' - BEGIN - SET @DatabaseMessage = 'Full or differential backup in progress: ' + CASE WHEN @BackupInProgress = 1 THEN 'Yes' WHEN @BackupInProgress = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT - END + SET @DatabaseMessage = 'Full or differential backup in progress: ' + CASE WHEN @BackupInProgress = 1 THEN 'Yes' WHEN @BackupInProgress = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT IF @CurrentBackupType IN('DIFF','FULL') BEGIN @@ -5002,7 +4999,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 16:34:50 //-- + --// Version: 2026-07-23 18:43:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7025,7 +7022,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 16:34:50 //-- + --// Version: 2026-07-23 18:43:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 80f53695..b840c2bc 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-23 16:34:50 +Version: 2026-07-23 18:43:44 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 16:34:50 //-- + --// Version: 2026-07-23 18:43:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 16:34:50 //-- + --// Version: 2026-07-23 18:43:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 16:34:50 //-- + --// Version: 2026-07-23 18:43:44 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index ddb6dd15..90d9b734 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -de114e88c6523241a7e3e8436df8fcf5983bc088c87ab16ca8a5fce7584ad965 CommandExecute.sql +1e2edc7425d83df218798547518a5720fb23e322c3814d61fbcd70de5227ab6f CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -1dac4d488c8cfc3a3e56a8bed074f18d9059eff22d8d3259eeff0d8e7c6b6a3b DatabaseBackup.sql -97d4f0b3891add5ee563976b6215a0daf4581517d6c0145ecac81dd2c7979bad DatabaseIntegrityCheck.sql -175457d199b84ddcc803c243a2941326a7ee9669dab7f590d1a9d3a9811f2f5e IndexOptimize.sql -8f0f193fd5a58cb5255021c26b08c7382fe8dd0efc2933d72efefae36f7be61c MaintenanceSolution.sql -9ee7561e32e001b3840f76251ae53b0e49a8b8d341cbc1caaf555323ff986600 MaintenanceSolutionAzureSQLDatabase.sql +6c4ac5ed26557cc4903016478af4554e30cdb68d540f82d47e0ea092f68b9b07 DatabaseBackup.sql +15fcee944dfd7b538f733a557371d82c218eeb6aade21de593ecd0f604d8056e DatabaseIntegrityCheck.sql +cd58b4851fc713774776b277138695a242bc5a27eae455a57e7d39abe8e0a33d IndexOptimize.sql +4d3e8650f06b66746c78175cd7b9a13d9926eb398fb11f76cd9f16db79101d6f MaintenanceSolution.sql +2f518db792149eef852a590d171c463f77bbe22c6197e13234793c2da79cfb17 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 61960361ea410e528b30aeb38a170cbea5be2ca8 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Thu, 23 Jul 2026 23:38:07 +0200 Subject: [PATCH 135/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 4 ++-- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 ++++++------ MaintenanceSolutionAzureSQLDatabase.sql | 10 +++++----- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 22 insertions(+), 22 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 9d3d598c..dfb89388 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-23 18:43:44 //-- + --// Version: 2026-07-23 23:22:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 564acd09..c96ef5ed 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 18:43:44 //-- + --// Version: 2026-07-23 23:22:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index e65b92b7..93adefd8 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 18:43:44 //-- + --// Version: 2026-07-23 23:22:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1553,7 +1553,7 @@ BEGIN IF @CurrentDatabaseState IN('ONLINE','EMERGENCY') AND NOT (@CurrentUserAccess = 'SINGLE_USER') - AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR @EngineEdition = 3) + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR (@CurrentAvailabilityGroupRole = 'SECONDARY' AND @EngineEdition = 3) OR @CurrentAvailabilityGroup 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') diff --git a/IndexOptimize.sql b/IndexOptimize.sql index d855bc93..fd39ba74 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 18:43:44 //-- + --// Version: 2026-07-23 23:22:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 0ace7f08..403cdf33 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: 2026-07-23 18:43:44 +Version: 2026-07-23 23:22:18 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 18:43:44 //-- + --// Version: 2026-07-23 23:22:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 18:43:44 //-- + --// Version: 2026-07-23 23:22:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4999,7 +4999,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 18:43:44 //-- + --// Version: 2026-07-23 23:22:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -6512,7 +6512,7 @@ BEGIN IF @CurrentDatabaseState IN('ONLINE','EMERGENCY') AND NOT (@CurrentUserAccess = 'SINGLE_USER') - AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR @EngineEdition = 3) + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR (@CurrentAvailabilityGroupRole = 'SECONDARY' AND @EngineEdition = 3) OR @CurrentAvailabilityGroup 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') @@ -7022,7 +7022,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 18:43:44 //-- + --// Version: 2026-07-23 23:22:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index b840c2bc..d405648b 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-23 18:43:44 +Version: 2026-07-23 23:22:18 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 18:43:44 //-- + --// Version: 2026-07-23 23:22:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 18:43:44 //-- + --// Version: 2026-07-23 23:22:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1907,7 +1907,7 @@ BEGIN IF @CurrentDatabaseState IN('ONLINE','EMERGENCY') AND NOT (@CurrentUserAccess = 'SINGLE_USER') - AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL OR @EngineEdition = 3) + AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR (@CurrentAvailabilityGroupRole = 'SECONDARY' AND @EngineEdition = 3) OR @CurrentAvailabilityGroup 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') @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 18:43:44 //-- + --// Version: 2026-07-23 23:22:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 90d9b734..5ba717ce 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -1e2edc7425d83df218798547518a5720fb23e322c3814d61fbcd70de5227ab6f CommandExecute.sql +8795a27c24cde7185e5f5d26ec0a446a4ec46279c4992eadace7ae0b593d8748 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -6c4ac5ed26557cc4903016478af4554e30cdb68d540f82d47e0ea092f68b9b07 DatabaseBackup.sql -15fcee944dfd7b538f733a557371d82c218eeb6aade21de593ecd0f604d8056e DatabaseIntegrityCheck.sql -cd58b4851fc713774776b277138695a242bc5a27eae455a57e7d39abe8e0a33d IndexOptimize.sql -4d3e8650f06b66746c78175cd7b9a13d9926eb398fb11f76cd9f16db79101d6f MaintenanceSolution.sql -2f518db792149eef852a590d171c463f77bbe22c6197e13234793c2da79cfb17 MaintenanceSolutionAzureSQLDatabase.sql +15e4ad7c23376c3b98458b1c06795111ab197698d0e6614e6d5ec99256d1cff7 DatabaseBackup.sql +e9c2b742cd186d4cabe3c8df58f1c6f746ec2c1ba5adb2e186a54dd5ecd63e6d DatabaseIntegrityCheck.sql +18111a5fafc6b4034c77defbf7d11b5fc21dc46250694ae04a0bbd668df7f796 IndexOptimize.sql +4f41ea4c440ea8a42e747a1145a6e2e1e816ea9280d09147ec23427f9c2d6620 MaintenanceSolution.sql +68945931c1446a1eac576f937ab7f91e93b42e34c10870fa9ba801ef96fec697 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 353aac70096f16763ce2f97e9169bf9fc47009c5 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 3 Aug 2026 22:10:54 +0200 Subject: [PATCH 136/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 14 +------------ DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 8 ++++++- MaintenanceSolution.sql | 28 ++++++++++--------------- MaintenanceSolutionAzureSQLDatabase.sql | 14 +++++++++---- SHA256SUMS.txt | 12 +++++------ 7 files changed, 37 insertions(+), 43 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index dfb89388..35df3ecf 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-07-23 23:22:18 //-- + --// Version: 2026-08-03 22:09:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index c96ef5ed..784eb77a 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 23:22:18 //-- + --// Version: 2026-08-03 22:09:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1524,18 +1524,6 @@ BEGIN VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 6) END - IF @MaxTransferSize > 4194304 AND @URL LIKE 'https%' AND @Credential IS NULL AND @BackupSoftware IS NULL - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 7) - END - - IF @MaxTransferSize < 5242880 AND @URL LIKE 's3%' AND @BackupSoftware IS NULL - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 8) - END - ---------------------------------------------------------------------------------------------------- IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 93adefd8..59e0e47f 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 23:22:18 //-- + --// Version: 2026-08-03 22:09:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index fd39ba74..7ed96b35 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 23:22:18 //-- + --// Version: 2026-08-03 22:09:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1040,6 +1040,12 @@ BEGIN VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1) END + IF @WaitAtLowPriorityAbortAfterWait = 'SELF' AND @WaitAtLowPriorityMaxDuration = 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 2) + END + ---------------------------------------------------------------------------------------------------- IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 403cdf33..714e30ab 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: 2026-07-23 23:22:18 +Version: 2026-08-03 22:09:47 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 23:22:18 //-- + --// Version: 2026-08-03 22:09:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 23:22:18 //-- + --// Version: 2026-08-03 22:09:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1923,18 +1923,6 @@ BEGIN VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 6) END - IF @MaxTransferSize > 4194304 AND @URL LIKE 'https%' AND @Credential IS NULL AND @BackupSoftware IS NULL - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 7) - END - - IF @MaxTransferSize < 5242880 AND @URL LIKE 's3%' AND @BackupSoftware IS NULL - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 8) - END - ---------------------------------------------------------------------------------------------------- IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 @@ -4999,7 +4987,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 23:22:18 //-- + --// Version: 2026-08-03 22:09:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7022,7 +7010,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 23:22:18 //-- + --// Version: 2026-08-03 22:09:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8006,6 +7994,12 @@ BEGIN VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1) END + IF @WaitAtLowPriorityAbortAfterWait = 'SELF' AND @WaitAtLowPriorityMaxDuration = 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 2) + END + ---------------------------------------------------------------------------------------------------- IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index d405648b..7a4a71db 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-07-23 23:22:18 +Version: 2026-08-03 22:09:47 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 23:22:18 //-- + --// Version: 2026-08-03 22:09:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 23:22:18 //-- + --// Version: 2026-08-03 22:09:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-07-23 23:22:18 //-- + --// Version: 2026-08-03 22:09:47 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3401,6 +3401,12 @@ BEGIN VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1) END + IF @WaitAtLowPriorityAbortAfterWait = 'SELF' AND @WaitAtLowPriorityMaxDuration = 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 2) + END + ---------------------------------------------------------------------------------------------------- IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 5ba717ce..334ba7de 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -8795a27c24cde7185e5f5d26ec0a446a4ec46279c4992eadace7ae0b593d8748 CommandExecute.sql +7284afc0dfac75fb8b2b3ad99b395e2de493c1a1803af7673f596a914130c241 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -15e4ad7c23376c3b98458b1c06795111ab197698d0e6614e6d5ec99256d1cff7 DatabaseBackup.sql -e9c2b742cd186d4cabe3c8df58f1c6f746ec2c1ba5adb2e186a54dd5ecd63e6d DatabaseIntegrityCheck.sql -18111a5fafc6b4034c77defbf7d11b5fc21dc46250694ae04a0bbd668df7f796 IndexOptimize.sql -4f41ea4c440ea8a42e747a1145a6e2e1e816ea9280d09147ec23427f9c2d6620 MaintenanceSolution.sql -68945931c1446a1eac576f937ab7f91e93b42e34c10870fa9ba801ef96fec697 MaintenanceSolutionAzureSQLDatabase.sql +9a87a2fa92a2de3a6d7c38357b680925caebc5f9c266cc66609e7c2a1b158833 DatabaseBackup.sql +05ebb59557fdd9b45c1ae3ff95287cbaece35d2c0475ef72fea07dcc8ed79601 DatabaseIntegrityCheck.sql +f4c469edeb6d9742f572dd2eec1b094c306f38cc2dbfc58472723677430ce49d IndexOptimize.sql +a48c475d1b61ccef20b9d6186868c1930d979c7c9e61a8d9966c2dfac27bb672 MaintenanceSolution.sql +d8feab1d7a9b39e7c2ecf1ca5b28c2fb7c9f29d832577573e4e3e620707a99a4 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From afa1774c91f3cc5c2067520d38353789bf882020 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 4 Aug 2026 21:41:47 +0200 Subject: [PATCH 137/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 552 +++++++++++------------ MaintenanceSolution.sql | 560 ++++++++++++------------ MaintenanceSolutionAzureSQLDatabase.sql | 558 +++++++++++------------ SHA256SUMS.txt | 12 +- 7 files changed, 853 insertions(+), 835 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 35df3ecf..28be6d23 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-03 22:09:47 //-- + --// Version: 2026-08-04 21:29:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 784eb77a..2e69e678 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-03 22:09:47 //-- + --// Version: 2026-08-04 21:29:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 59e0e47f..20bc8e12 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-03 22:09:47 //-- + --// Version: 2026-08-04 21:29:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 7ed96b35..b392be0e 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-03 22:09:47 //-- + --// Version: 2026-08-04 21:29:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -151,6 +151,8 @@ BEGIN DECLARE @CurrentPartitionNumber int DECLARE @CurrentPartitionCount int DECLARE @CurrentInRowDataPageCount bigint + DECLARE @CurrentAlterIndexCompleted bit + DECLARE @CurrentUpdateStatisticsCompleted bit DECLARE @CurrentIsPartition bit DECLARE @CurrentIndexExists bit DECLARE @CurrentStatisticsExists bit @@ -232,7 +234,9 @@ BEGIN StartPosition int, [Order] int DEFAULT 0, Selected bit DEFAULT 0, - Completed bit DEFAULT 0, + AlterIndexCompleted bit DEFAULT 0, + UpdateStatisticsCompleted bit DEFAULT 0, + Completed AS CASE WHEN AlterIndexCompleted = 1 AND UpdateStatisticsCompleted = 1 THEN 1 ELSE 0 END, PRIMARY KEY (Selected, Completed, [Order], ID), INDEX IX_ObjectID_StatisticsID_PartitionNumber NONCLUSTERED (ObjectID, StatisticsID, PartitionNumber)) @@ -2136,6 +2140,19 @@ BEGIN UPDATE tmpIndexesStatistics SET [Order] = RowNumber + -- Update that alter index is completed for rows that have no index, if no index actions have been selected, for rows on read-only filegroups, or based on the page counts + UPDATE @tmpIndexesStatistics + SET AlterIndexCompleted = 1 + WHERE IndexID IS NULL + OR NOT EXISTS (SELECT * FROM @ActionsPreferred) + OR OnReadOnlyFileGroup = 1 + OR NOT (((InRowDataPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (InRowDataPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL)) OR InRowDataPageCount IS NULL) + + -- Update that update statistics is completed for rows that have no statistics + UPDATE @tmpIndexesStatistics + SET UpdateStatisticsCompleted = 1 + WHERE StatisticsID IS NULL + SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName' + ' FROM sys.objects objects' + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' @@ -2232,7 +2249,9 @@ BEGIN @CurrentPartitionID = PartitionID, @CurrentPartitionNumber = PartitionNumber, @CurrentPartitionCount = PartitionCount, - @CurrentInRowDataPageCount = InRowDataPageCount + @CurrentInRowDataPageCount = InRowDataPageCount, + @CurrentAlterIndexCompleted = AlterIndexCompleted, + @CurrentUpdateStatisticsCompleted = UpdateStatisticsCompleted FROM @tmpIndexesStatistics WHERE Selected = 1 AND Completed = 0 @@ -2246,47 +2265,41 @@ BEGIN -- Is the index a partition? IF @CurrentPartitionNumber IS NULL OR @CurrentPartitionCount = 1 BEGIN SET @CurrentIsPartition = 0 END ELSE BEGIN SET @CurrentIsPartition = 1 END - IF ((@CurrentInRowDataPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (@CurrentInRowDataPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL)) OR @CurrentInRowDataPageCount IS NULL + IF @CurrentAlterIndexCompleted = 0 AND @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) AND @CurrentOnReadOnlyFileGroup = 0 BEGIN -- Does the index exist? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentCommand = '' + SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - 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' + 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 = @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 + BEGIN TRY + 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 - SET @CurrentIndexExists = 0 - GOTO NoAction - END - END TRY - BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @CurrentIndexExists IS NULL + BEGIN + SET @CurrentIndexExists = 0 + GOTO NoAction + END + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 - SET @ReturnCode = ERROR_NUMBER() - END + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END - GOTO NoAction - END CATCH - END + GOTO NoAction + END CATCH -- 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) + IF EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) OR @MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL BEGIN SET @CurrentCommand = '' @@ -2320,51 +2333,40 @@ BEGIN END -- Select fragmentation group - IF @CurrentIndexID IS NOT NULL AND @CurrentOnReadOnlyFileGroup = 0 AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentFragmentationGroup = CASE - WHEN @CurrentFragmentationLevel >= @FragmentationLevel2 THEN 'High' - WHEN @CurrentFragmentationLevel >= @FragmentationLevel1 AND @CurrentFragmentationLevel < @FragmentationLevel2 THEN 'Medium' - WHEN @CurrentFragmentationLevel < @FragmentationLevel1 THEN 'Low' - END + SET @CurrentFragmentationGroup = CASE + WHEN @CurrentFragmentationLevel >= @FragmentationLevel2 THEN 'High' + WHEN @CurrentFragmentationLevel >= @FragmentationLevel1 AND @CurrentFragmentationLevel < @FragmentationLevel2 THEN 'Medium' + WHEN @CurrentFragmentationLevel < @FragmentationLevel1 THEN 'Low' END -- Which actions are allowed? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) + IF NOT (@CurrentIsMemoryOptimized = 1) + AND NOT (@CurrentAllowPageLocks = 0) BEGIN - IF NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) - AND NOT (@CurrentAllowPageLocks = 0) - BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REORGANIZE') - END - IF NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) - BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REBUILD_OFFLINE') - END - IF @EngineEdition IN (3, 5, 8) - AND NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1 AND @CurrentIsImageText IS NOT NULL) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1 AND @CurrentIsFileStream IS NOT NULL) - AND NOT (@CurrentIndexType = 3) - AND NOT (@CurrentIndexType = 4) - AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @CurrentHasClusteredColumnstore IS NOT NULL AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND @CurrentIsColumnstoreOrdered IS NOT NULL AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REBUILD_ONLINE') - END + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REORGANIZE') + END + IF NOT (@CurrentIsMemoryOptimized = 1) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REBUILD_OFFLINE') + END + IF @EngineEdition IN (3, 5, 8) + AND NOT (@CurrentIsMemoryOptimized = 1) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1 AND @CurrentIsImageText IS NOT NULL) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1 AND @CurrentIsFileStream IS NOT NULL) + AND NOT (@CurrentIndexType = 3) + AND NOT (@CurrentIndexType = 4) + AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @CurrentHasClusteredColumnstore IS NOT NULL AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND @CurrentIsColumnstoreOrdered IS NOT NULL AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REBUILD_ONLINE') END -- Decide action - IF @CurrentIndexID IS NOT NULL - AND EXISTS(SELECT * FROM @ActionsPreferred) - AND (@CurrentPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) + IF (@CurrentPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (@CurrentPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL) AND @CurrentResumableIndexOperation = 0 BEGIN @@ -2400,148 +2402,149 @@ BEGIN BEGIN SET @CurrentMaxDOP = 1 END - END - - -- Create index comment - IF @CurrentAction 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 @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 + ', ' - IF @CurrentIsImageText IS NOT NULL SET @CurrentComment += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsFileStream IS NOT NULL SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentHasClusteredColumnstore IS NOT NULL AND @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsColumnstoreOrdered IS NOT NULL AND @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsComputed IS NOT NULL SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsClusteredIndexComputed IS NOT NULL AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsTimestamp IS NOT NULL SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 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(max)),'N/A') + ', ' - SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar(max)),'N/A') - END - - IF @CurrentAction IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) - BEGIN - SET @CurrentExtendedInfo = (SELECT * - FROM (SELECT CAST(@CurrentPageCount AS nvarchar(max)) AS [PageCount], - CAST(@CurrentFragmentationLevel AS nvarchar(max)) AS Fragmentation - ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) - END - IF @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) - BEGIN - SET @CurrentDatabaseContext = @CurrentDatabaseName - - SET @CurrentCommandType = 'ALTER_INDEX' - - SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - 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(max)) - - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 + -- Create index comment + IF @CurrentAction IS NOT NULL BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('SORT_IN_TEMPDB = ON') + 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 + ', ' + IF @CurrentIsImageText IS NOT NULL SET @CurrentComment += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsFileStream IS NOT NULL SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentHasClusteredColumnstore IS NOT NULL AND @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsColumnstoreOrdered IS NOT NULL AND @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsComputed IS NOT NULL SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsClusteredIndexComputed IS NOT NULL AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsTimestamp IS NOT NULL SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 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(max)),'N/A') + ', ' + SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar(max)),'N/A') END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'N' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 + IF @CurrentAction IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('SORT_IN_TEMPDB = OFF') + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentPageCount AS nvarchar(max)) AS [PageCount], + CAST(@CurrentFragmentationLevel AS nvarchar(max)) AS Fragmentation + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 + IF @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END) - END + SET @CurrentDatabaseContext = @CurrentDatabaseName - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 1 AND @WaitAtLowPriorityMaxDuration IS NOT NULL - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + ')') - END + SET @CurrentCommandType = 'ALTER_INDEX' - IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('ONLINE = OFF') - END + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + 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(max)) - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentMaxDOP IS NOT NULL - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) - END + 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) + VALUES('SORT_IN_TEMPDB = ON') + 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) AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max))) - END + 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) + VALUES('SORT_IN_TEMPDB = OFF') + END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END) - END + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END) + END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,4) AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('DATA_COMPRESSION = ' + @DataCompression) - END + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 1 AND @WaitAtLowPriorityMaxDuration IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + ')') + END - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES(CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL) THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END) - END + IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('ONLINE = OFF') + END - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL)) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max))) - END + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentMaxDOP IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) + END - IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('LOB_COMPACTION = ON') - 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) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max))) + END - IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'N' - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('LOB_COMPACTION = OFF') - END + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END) + END - IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) - BEGIN - SELECT @CurrentCommand += ' WITH (' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) + ')' - FROM @CurrentAlterIndexWithClauseArguments - END + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,4) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('DATA_COMPRESSION = ' + @DataCompression) + END - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES(CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL) THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END) + END - IF @Delay > 0 - BEGIN - SET @CurrentDelay = DATEADD(ss,@Delay,'1900-01-01') - WAITFOR DELAY @CurrentDelay + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL)) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max))) + END + + IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('LOB_COMPACTION = ON') + END + + IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'N' + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('LOB_COMPACTION = OFF') + END + + IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) + BEGIN + SELECT @CurrentCommand += ' WITH (' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) + ')' + FROM @CurrentAlterIndexWithClauseArguments + END + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 + + IF @Delay > 0 + BEGIN + SET @CurrentDelay = DATEADD(ss,@Delay,'1900-01-01') + WAITFOR DELAY @CurrentDelay + END END END SET @CurrentMaxDOP = @MaxDOP - -- Should the statistics be updated? - Pre checks and final decision - IF @CurrentStatisticsID IS NOT NULL + -- Should the statistics be updated? + IF @CurrentUpdateStatisticsCompleted = 0 + AND @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) BEGIN @@ -2680,124 +2683,125 @@ BEGIN BEGIN SET @CurrentUpdateStatistics = 'N' END - END - - SET @CurrentStatisticsSample = @StatisticsSample - SET @CurrentStatisticsPersistSample = @StatisticsPersistSample - SET @CurrentStatisticsResample = @StatisticsResample - - -- Incremental statistics only supports RESAMPLE - IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 - BEGIN - SET @CurrentStatisticsSample = NULL - SET @CurrentStatisticsPersistSample = NULL - SET @CurrentStatisticsResample = 'Y' - END - - -- Create statistics comment - IF @CurrentUpdateStatistics = 'Y' - BEGIN - SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment += 'StatisticsType: ' + 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 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar(max)),'N/A') + ', ' - SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar(max)),'N/A') - END - - IF @CurrentUpdateStatistics = 'Y' AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) - BEGIN - SET @CurrentExtendedInfo = (SELECT * - FROM (SELECT CAST(@CurrentRowCount AS nvarchar(max)) AS [RowCount], - CAST(@CurrentModificationCounter AS nvarchar(max)) AS ModificationCounter - ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) - END - ELSE - BEGIN - SET @CurrentExtendedInfo = NULL - END - - IF @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) - BEGIN - SET @CurrentDatabaseContext = @CurrentDatabaseName - - SET @CurrentCommandType = 'UPDATE_STATISTICS' - SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - SET @CurrentCommand += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) + SET @CurrentStatisticsSample = @StatisticsSample + SET @CurrentStatisticsPersistSample = @StatisticsPersistSample + SET @CurrentStatisticsResample = @StatisticsResample - IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) + -- Incremental statistics only supports RESAMPLE + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) + SET @CurrentStatisticsSample = NULL + SET @CurrentStatisticsPersistSample = NULL + SET @CurrentStatisticsResample = 'Y' END - IF @CurrentStatisticsSample = 100 + -- Create statistics comment + IF @CurrentUpdateStatistics = 'Y' BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('FULLSCAN') + SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'StatisticsType: ' + 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 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar(max)),'N/A') + ', ' + SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar(max)),'N/A') END - IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 + IF @CurrentUpdateStatistics = 'Y' AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT') + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentRowCount AS nvarchar(max)) AS [RowCount], + CAST(@CurrentModificationCounter AS nvarchar(max)) AS ModificationCounter + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END - - IF @CurrentStatisticsPersistSample = 'Y' + ELSE BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('PERSIST_SAMPLE_PERCENT = ON') + SET @CurrentExtendedInfo = NULL END - IF @CurrentStatisticsPersistSample = 'N' + IF @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('PERSIST_SAMPLE_PERCENT = OFF') - END + SET @CurrentDatabaseContext = @CurrentDatabaseName - IF @CurrentNoRecompute = 1 - BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('NORECOMPUTE') - END + SET @CurrentCommandType = 'UPDATE_STATISTICS' - IF @CurrentStatisticsResample = 'Y' - BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('RESAMPLE') - END + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + SET @CurrentCommand += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) - IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) - BEGIN - SELECT @CurrentCommand += ' WITH ' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) - FROM @CurrentUpdateStatisticsWithClauseArguments - END + IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) + END - IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + IF @CurrentStatisticsSample = 100 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('FULLSCAN') + END - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @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 + IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT') + END + + IF @CurrentStatisticsPersistSample = 'Y' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('PERSIST_SAMPLE_PERCENT = ON') + END + + IF @CurrentStatisticsPersistSample = 'N' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('PERSIST_SAMPLE_PERCENT = OFF') + END + + IF @CurrentNoRecompute = 1 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('NORECOMPUTE') + END + + IF @CurrentStatisticsResample = 'Y' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('RESAMPLE') + END + + IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) + BEGIN + SELECT @CurrentCommand += ' WITH ' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) + FROM @CurrentUpdateStatisticsWithClauseArguments + END + + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @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 + END END NoAction: -- Update that the index or statistics is completed UPDATE @tmpIndexesStatistics - SET Completed = 1 + SET AlterIndexCompleted = 1, + UpdateStatisticsCompleted = 1 WHERE Selected = 1 AND Completed = 0 AND [Order] = @CurrentIxOrder AND ID = @CurrentIxID -- Update that statistics on remaining partitions are completed where no update is needed - IF (NOT EXISTS(SELECT * FROM @ActionsPreferred) OR @CurrentIndexID IS NULL) AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentStatisticsID IS NOT NULL + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentStatisticsID IS NOT NULL BEGIN UPDATE tmpIndexesStatistics - SET Completed = 1 + SET UpdateStatisticsCompleted = 1 FROM @tmpIndexesStatistics tmpIndexesStatistics INNER JOIN @IncrementalStatsProperties IncrementalStatsProperties ON tmpIndexesStatistics.ObjectID = IncrementalStatsProperties.ObjectID AND tmpIndexesStatistics.StatisticsID = IncrementalStatsProperties.StatisticsID AND tmpIndexesStatistics.PartitionNumber = IncrementalStatsProperties.PartitionNumber WHERE tmpIndexesStatistics.ObjectID = @CurrentObjectID @@ -2835,6 +2839,8 @@ BEGIN SET @CurrentPartitionNumber = NULL SET @CurrentPartitionCount = NULL SET @CurrentInRowDataPageCount = NULL + SET @CurrentAlterIndexCompleted = NULL + SET @CurrentUpdateStatisticsCompleted = NULL SET @CurrentIsPartition = NULL SET @CurrentIndexExists = NULL SET @CurrentStatisticsExists = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 714e30ab..99bfee31 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: 2026-08-03 22:09:47 +Version: 2026-08-04 21:29:03 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-03 22:09:47 //-- + --// Version: 2026-08-04 21:29:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-03 22:09:47 //-- + --// Version: 2026-08-04 21:29:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4987,7 +4987,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-03 22:09:47 //-- + --// Version: 2026-08-04 21:29:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7010,7 +7010,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-03 22:09:47 //-- + --// Version: 2026-08-04 21:29:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7105,6 +7105,8 @@ BEGIN DECLARE @CurrentPartitionNumber int DECLARE @CurrentPartitionCount int DECLARE @CurrentInRowDataPageCount bigint + DECLARE @CurrentAlterIndexCompleted bit + DECLARE @CurrentUpdateStatisticsCompleted bit DECLARE @CurrentIsPartition bit DECLARE @CurrentIndexExists bit DECLARE @CurrentStatisticsExists bit @@ -7186,7 +7188,9 @@ BEGIN StartPosition int, [Order] int DEFAULT 0, Selected bit DEFAULT 0, - Completed bit DEFAULT 0, + AlterIndexCompleted bit DEFAULT 0, + UpdateStatisticsCompleted bit DEFAULT 0, + Completed AS CASE WHEN AlterIndexCompleted = 1 AND UpdateStatisticsCompleted = 1 THEN 1 ELSE 0 END, PRIMARY KEY (Selected, Completed, [Order], ID), INDEX IX_ObjectID_StatisticsID_PartitionNumber NONCLUSTERED (ObjectID, StatisticsID, PartitionNumber)) @@ -9090,6 +9094,19 @@ BEGIN UPDATE tmpIndexesStatistics SET [Order] = RowNumber + -- Update that alter index is completed for rows that have no index, if no index actions have been selected, for rows on read-only filegroups, or based on the page counts + UPDATE @tmpIndexesStatistics + SET AlterIndexCompleted = 1 + WHERE IndexID IS NULL + OR NOT EXISTS (SELECT * FROM @ActionsPreferred) + OR OnReadOnlyFileGroup = 1 + OR NOT (((InRowDataPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (InRowDataPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL)) OR InRowDataPageCount IS NULL) + + -- Update that update statistics is completed for rows that have no statistics + UPDATE @tmpIndexesStatistics + SET UpdateStatisticsCompleted = 1 + WHERE StatisticsID IS NULL + SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName' + ' FROM sys.objects objects' + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' @@ -9186,7 +9203,9 @@ BEGIN @CurrentPartitionID = PartitionID, @CurrentPartitionNumber = PartitionNumber, @CurrentPartitionCount = PartitionCount, - @CurrentInRowDataPageCount = InRowDataPageCount + @CurrentInRowDataPageCount = InRowDataPageCount, + @CurrentAlterIndexCompleted = AlterIndexCompleted, + @CurrentUpdateStatisticsCompleted = UpdateStatisticsCompleted FROM @tmpIndexesStatistics WHERE Selected = 1 AND Completed = 0 @@ -9200,47 +9219,41 @@ BEGIN -- Is the index a partition? IF @CurrentPartitionNumber IS NULL OR @CurrentPartitionCount = 1 BEGIN SET @CurrentIsPartition = 0 END ELSE BEGIN SET @CurrentIsPartition = 1 END - IF ((@CurrentInRowDataPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (@CurrentInRowDataPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL)) OR @CurrentInRowDataPageCount IS NULL + IF @CurrentAlterIndexCompleted = 0 AND @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) AND @CurrentOnReadOnlyFileGroup = 0 BEGIN -- Does the index exist? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentCommand = '' + SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - 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' + 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 = @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 + BEGIN TRY + 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 - SET @CurrentIndexExists = 0 - GOTO NoAction - END - END TRY - BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @CurrentIndexExists IS NULL + BEGIN + SET @CurrentIndexExists = 0 + GOTO NoAction + END + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 - SET @ReturnCode = ERROR_NUMBER() - END + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END - GOTO NoAction - END CATCH - END + GOTO NoAction + END CATCH -- 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) + IF EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) OR @MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL BEGIN SET @CurrentCommand = '' @@ -9274,51 +9287,40 @@ BEGIN END -- Select fragmentation group - IF @CurrentIndexID IS NOT NULL AND @CurrentOnReadOnlyFileGroup = 0 AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentFragmentationGroup = CASE - WHEN @CurrentFragmentationLevel >= @FragmentationLevel2 THEN 'High' - WHEN @CurrentFragmentationLevel >= @FragmentationLevel1 AND @CurrentFragmentationLevel < @FragmentationLevel2 THEN 'Medium' - WHEN @CurrentFragmentationLevel < @FragmentationLevel1 THEN 'Low' - END + SET @CurrentFragmentationGroup = CASE + WHEN @CurrentFragmentationLevel >= @FragmentationLevel2 THEN 'High' + WHEN @CurrentFragmentationLevel >= @FragmentationLevel1 AND @CurrentFragmentationLevel < @FragmentationLevel2 THEN 'Medium' + WHEN @CurrentFragmentationLevel < @FragmentationLevel1 THEN 'Low' END -- Which actions are allowed? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) + IF NOT (@CurrentIsMemoryOptimized = 1) + AND NOT (@CurrentAllowPageLocks = 0) BEGIN - IF NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) - AND NOT (@CurrentAllowPageLocks = 0) - BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REORGANIZE') - END - IF NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) - BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REBUILD_OFFLINE') - END - IF @EngineEdition IN (3, 5, 8) - AND NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1 AND @CurrentIsImageText IS NOT NULL) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1 AND @CurrentIsFileStream IS NOT NULL) - AND NOT (@CurrentIndexType = 3) - AND NOT (@CurrentIndexType = 4) - AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @CurrentHasClusteredColumnstore IS NOT NULL AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND @CurrentIsColumnstoreOrdered IS NOT NULL AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REBUILD_ONLINE') - END + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REORGANIZE') + END + IF NOT (@CurrentIsMemoryOptimized = 1) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REBUILD_OFFLINE') + END + IF @EngineEdition IN (3, 5, 8) + AND NOT (@CurrentIsMemoryOptimized = 1) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1 AND @CurrentIsImageText IS NOT NULL) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1 AND @CurrentIsFileStream IS NOT NULL) + AND NOT (@CurrentIndexType = 3) + AND NOT (@CurrentIndexType = 4) + AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @CurrentHasClusteredColumnstore IS NOT NULL AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND @CurrentIsColumnstoreOrdered IS NOT NULL AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REBUILD_ONLINE') END -- Decide action - IF @CurrentIndexID IS NOT NULL - AND EXISTS(SELECT * FROM @ActionsPreferred) - AND (@CurrentPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) + IF (@CurrentPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (@CurrentPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL) AND @CurrentResumableIndexOperation = 0 BEGIN @@ -9354,148 +9356,149 @@ BEGIN BEGIN SET @CurrentMaxDOP = 1 END - END - -- Create index comment - IF @CurrentAction 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 @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 + ', ' - IF @CurrentIsImageText IS NOT NULL SET @CurrentComment += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsFileStream IS NOT NULL SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentHasClusteredColumnstore IS NOT NULL AND @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsColumnstoreOrdered IS NOT NULL AND @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsComputed IS NOT NULL SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsClusteredIndexComputed IS NOT NULL AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsTimestamp IS NOT NULL SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 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(max)),'N/A') + ', ' - SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar(max)),'N/A') - END - - IF @CurrentAction IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) - BEGIN - SET @CurrentExtendedInfo = (SELECT * - FROM (SELECT CAST(@CurrentPageCount AS nvarchar(max)) AS [PageCount], - CAST(@CurrentFragmentationLevel AS nvarchar(max)) AS Fragmentation - ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) - END - - IF @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) - BEGIN - SET @CurrentDatabaseContext = @CurrentDatabaseName - - SET @CurrentCommandType = 'ALTER_INDEX' - - SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - 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(max)) - - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 + -- Create index comment + IF @CurrentAction IS NOT NULL BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('SORT_IN_TEMPDB = ON') + 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 + ', ' + IF @CurrentIsImageText IS NOT NULL SET @CurrentComment += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsFileStream IS NOT NULL SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentHasClusteredColumnstore IS NOT NULL AND @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsColumnstoreOrdered IS NOT NULL AND @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsComputed IS NOT NULL SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsClusteredIndexComputed IS NOT NULL AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsTimestamp IS NOT NULL SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 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(max)),'N/A') + ', ' + SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar(max)),'N/A') END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'N' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 + IF @CurrentAction IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('SORT_IN_TEMPDB = OFF') + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentPageCount AS nvarchar(max)) AS [PageCount], + CAST(@CurrentFragmentationLevel AS nvarchar(max)) AS Fragmentation + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 + IF @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END) - END + SET @CurrentDatabaseContext = @CurrentDatabaseName - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 1 AND @WaitAtLowPriorityMaxDuration IS NOT NULL - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + ')') - END + SET @CurrentCommandType = 'ALTER_INDEX' - IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('ONLINE = OFF') - END + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + 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(max)) - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentMaxDOP IS NOT NULL - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) - END + 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) + VALUES('SORT_IN_TEMPDB = ON') + 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) AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max))) - END + 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) + VALUES('SORT_IN_TEMPDB = OFF') + END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END) - END + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END) + END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,4) AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('DATA_COMPRESSION = ' + @DataCompression) - END + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 1 AND @WaitAtLowPriorityMaxDuration IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + ')') + END - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES(CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL) THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END) - END + IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('ONLINE = OFF') + END - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL)) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max))) - END + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentMaxDOP IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) + END - IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('LOB_COMPACTION = ON') - 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) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max))) + END - IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'N' - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('LOB_COMPACTION = OFF') - END + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END) + END - IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) - BEGIN - SELECT @CurrentCommand += ' WITH (' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) + ')' - FROM @CurrentAlterIndexWithClauseArguments - END + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,4) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('DATA_COMPRESSION = ' + @DataCompression) + END - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES(CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL) THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END) + END - IF @Delay > 0 - BEGIN - SET @CurrentDelay = DATEADD(ss,@Delay,'1900-01-01') - WAITFOR DELAY @CurrentDelay + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL)) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max))) + END + + IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('LOB_COMPACTION = ON') + END + + IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'N' + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('LOB_COMPACTION = OFF') + END + + IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) + BEGIN + SELECT @CurrentCommand += ' WITH (' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) + ')' + FROM @CurrentAlterIndexWithClauseArguments + END + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 + + IF @Delay > 0 + BEGIN + SET @CurrentDelay = DATEADD(ss,@Delay,'1900-01-01') + WAITFOR DELAY @CurrentDelay + END END END SET @CurrentMaxDOP = @MaxDOP - -- Should the statistics be updated? - Pre checks and final decision - IF @CurrentStatisticsID IS NOT NULL + -- Should the statistics be updated? + IF @CurrentUpdateStatisticsCompleted = 0 + AND @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) BEGIN @@ -9634,124 +9637,125 @@ BEGIN BEGIN SET @CurrentUpdateStatistics = 'N' END - END - - SET @CurrentStatisticsSample = @StatisticsSample - SET @CurrentStatisticsPersistSample = @StatisticsPersistSample - SET @CurrentStatisticsResample = @StatisticsResample - -- Incremental statistics only supports RESAMPLE - IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 - BEGIN - SET @CurrentStatisticsSample = NULL - SET @CurrentStatisticsPersistSample = NULL - SET @CurrentStatisticsResample = 'Y' - END - - -- Create statistics comment - IF @CurrentUpdateStatistics = 'Y' - BEGIN - SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment += 'StatisticsType: ' + 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 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar(max)),'N/A') + ', ' - SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar(max)),'N/A') - END - - IF @CurrentUpdateStatistics = 'Y' AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) - BEGIN - SET @CurrentExtendedInfo = (SELECT * - FROM (SELECT CAST(@CurrentRowCount AS nvarchar(max)) AS [RowCount], - CAST(@CurrentModificationCounter AS nvarchar(max)) AS ModificationCounter - ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) - END - ELSE - BEGIN - SET @CurrentExtendedInfo = NULL - END + SET @CurrentStatisticsSample = @StatisticsSample + SET @CurrentStatisticsPersistSample = @StatisticsPersistSample + SET @CurrentStatisticsResample = @StatisticsResample - IF @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) - BEGIN - SET @CurrentDatabaseContext = @CurrentDatabaseName - - SET @CurrentCommandType = 'UPDATE_STATISTICS' - - SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - SET @CurrentCommand += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) - - IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) + -- Incremental statistics only supports RESAMPLE + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) + SET @CurrentStatisticsSample = NULL + SET @CurrentStatisticsPersistSample = NULL + SET @CurrentStatisticsResample = 'Y' END - IF @CurrentStatisticsSample = 100 + -- Create statistics comment + IF @CurrentUpdateStatistics = 'Y' BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('FULLSCAN') + SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'StatisticsType: ' + 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 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar(max)),'N/A') + ', ' + SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar(max)),'N/A') END - IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 + IF @CurrentUpdateStatistics = 'Y' AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT') + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentRowCount AS nvarchar(max)) AS [RowCount], + CAST(@CurrentModificationCounter AS nvarchar(max)) AS ModificationCounter + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END - - IF @CurrentStatisticsPersistSample = 'Y' + ELSE BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('PERSIST_SAMPLE_PERCENT = ON') + SET @CurrentExtendedInfo = NULL END - IF @CurrentStatisticsPersistSample = 'N' + IF @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('PERSIST_SAMPLE_PERCENT = OFF') - END + SET @CurrentDatabaseContext = @CurrentDatabaseName - IF @CurrentNoRecompute = 1 - BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('NORECOMPUTE') - END + SET @CurrentCommandType = 'UPDATE_STATISTICS' - IF @CurrentStatisticsResample = 'Y' - BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('RESAMPLE') - END + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + SET @CurrentCommand += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) - IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) - BEGIN - SELECT @CurrentCommand += ' WITH ' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) - FROM @CurrentUpdateStatisticsWithClauseArguments - END + IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) + END - IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + IF @CurrentStatisticsSample = 100 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('FULLSCAN') + END - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @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 + IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT') + END + + IF @CurrentStatisticsPersistSample = 'Y' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('PERSIST_SAMPLE_PERCENT = ON') + END + + IF @CurrentStatisticsPersistSample = 'N' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('PERSIST_SAMPLE_PERCENT = OFF') + END + + IF @CurrentNoRecompute = 1 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('NORECOMPUTE') + END + + IF @CurrentStatisticsResample = 'Y' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('RESAMPLE') + END + + IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) + BEGIN + SELECT @CurrentCommand += ' WITH ' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) + FROM @CurrentUpdateStatisticsWithClauseArguments + END + + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @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 + END END NoAction: -- Update that the index or statistics is completed UPDATE @tmpIndexesStatistics - SET Completed = 1 + SET AlterIndexCompleted = 1, + UpdateStatisticsCompleted = 1 WHERE Selected = 1 AND Completed = 0 AND [Order] = @CurrentIxOrder AND ID = @CurrentIxID -- Update that statistics on remaining partitions are completed where no update is needed - IF (NOT EXISTS(SELECT * FROM @ActionsPreferred) OR @CurrentIndexID IS NULL) AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentStatisticsID IS NOT NULL + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentStatisticsID IS NOT NULL BEGIN UPDATE tmpIndexesStatistics - SET Completed = 1 + SET UpdateStatisticsCompleted = 1 FROM @tmpIndexesStatistics tmpIndexesStatistics INNER JOIN @IncrementalStatsProperties IncrementalStatsProperties ON tmpIndexesStatistics.ObjectID = IncrementalStatsProperties.ObjectID AND tmpIndexesStatistics.StatisticsID = IncrementalStatsProperties.StatisticsID AND tmpIndexesStatistics.PartitionNumber = IncrementalStatsProperties.PartitionNumber WHERE tmpIndexesStatistics.ObjectID = @CurrentObjectID @@ -9789,6 +9793,8 @@ BEGIN SET @CurrentPartitionNumber = NULL SET @CurrentPartitionCount = NULL SET @CurrentInRowDataPageCount = NULL + SET @CurrentAlterIndexCompleted = NULL + SET @CurrentUpdateStatisticsCompleted = NULL SET @CurrentIsPartition = NULL SET @CurrentIndexExists = NULL SET @CurrentStatisticsExists = NULL diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 7a4a71db..1a05153e 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-03 22:09:47 +Version: 2026-08-04 21:29:03 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-03 22:09:47 //-- + --// Version: 2026-08-04 21:29:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-03 22:09:47 //-- + --// Version: 2026-08-04 21:29:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-03 22:09:47 //-- + --// Version: 2026-08-04 21:29:03 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2512,6 +2512,8 @@ BEGIN DECLARE @CurrentPartitionNumber int DECLARE @CurrentPartitionCount int DECLARE @CurrentInRowDataPageCount bigint + DECLARE @CurrentAlterIndexCompleted bit + DECLARE @CurrentUpdateStatisticsCompleted bit DECLARE @CurrentIsPartition bit DECLARE @CurrentIndexExists bit DECLARE @CurrentStatisticsExists bit @@ -2593,7 +2595,9 @@ BEGIN StartPosition int, [Order] int DEFAULT 0, Selected bit DEFAULT 0, - Completed bit DEFAULT 0, + AlterIndexCompleted bit DEFAULT 0, + UpdateStatisticsCompleted bit DEFAULT 0, + Completed AS CASE WHEN AlterIndexCompleted = 1 AND UpdateStatisticsCompleted = 1 THEN 1 ELSE 0 END, PRIMARY KEY (Selected, Completed, [Order], ID), INDEX IX_ObjectID_StatisticsID_PartitionNumber NONCLUSTERED (ObjectID, StatisticsID, PartitionNumber)) @@ -4497,6 +4501,19 @@ BEGIN UPDATE tmpIndexesStatistics SET [Order] = RowNumber + -- Update that alter index is completed for rows that have no index, if no index actions have been selected, for rows on read-only filegroups, or based on the page counts + UPDATE @tmpIndexesStatistics + SET AlterIndexCompleted = 1 + WHERE IndexID IS NULL + OR NOT EXISTS (SELECT * FROM @ActionsPreferred) + OR OnReadOnlyFileGroup = 1 + OR NOT (((InRowDataPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (InRowDataPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL)) OR InRowDataPageCount IS NULL) + + -- Update that update statistics is completed for rows that have no statistics + UPDATE @tmpIndexesStatistics + SET UpdateStatisticsCompleted = 1 + WHERE StatisticsID IS NULL + SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName' + ' FROM sys.objects objects' + ' INNER JOIN sys.schemas schemas ON objects.[schema_id] = schemas.[schema_id]' @@ -4593,7 +4610,9 @@ BEGIN @CurrentPartitionID = PartitionID, @CurrentPartitionNumber = PartitionNumber, @CurrentPartitionCount = PartitionCount, - @CurrentInRowDataPageCount = InRowDataPageCount + @CurrentInRowDataPageCount = InRowDataPageCount, + @CurrentAlterIndexCompleted = AlterIndexCompleted, + @CurrentUpdateStatisticsCompleted = UpdateStatisticsCompleted FROM @tmpIndexesStatistics WHERE Selected = 1 AND Completed = 0 @@ -4607,47 +4626,41 @@ BEGIN -- Is the index a partition? IF @CurrentPartitionNumber IS NULL OR @CurrentPartitionCount = 1 BEGIN SET @CurrentIsPartition = 0 END ELSE BEGIN SET @CurrentIsPartition = 1 END - IF ((@CurrentInRowDataPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (@CurrentInRowDataPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL)) OR @CurrentInRowDataPageCount IS NULL + IF @CurrentAlterIndexCompleted = 0 AND @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) AND @CurrentOnReadOnlyFileGroup = 0 BEGIN -- Does the index exist? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentCommand = '' + SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - 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' + 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 = @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 + BEGIN TRY + 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 - SET @CurrentIndexExists = 0 - GOTO NoAction - END - END TRY - BEGIN CATCH - SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 @CurrentIndexExists IS NULL + BEGIN + SET @CurrentIndexExists = 0 + GOTO NoAction + END + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 - SET @ReturnCode = ERROR_NUMBER() - END + IF NOT (ERROR_NUMBER() IN(1205,1222) AND @LockMessageSeverity = 10) + BEGIN + SET @ReturnCode = ERROR_NUMBER() + END - GOTO NoAction - END CATCH - END + GOTO NoAction + END CATCH -- 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) + IF EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) OR @MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL BEGIN SET @CurrentCommand = '' @@ -4681,51 +4694,40 @@ BEGIN END -- Select fragmentation group - IF @CurrentIndexID IS NOT NULL AND @CurrentOnReadOnlyFileGroup = 0 AND EXISTS(SELECT * FROM @ActionsPreferred) - BEGIN - SET @CurrentFragmentationGroup = CASE - WHEN @CurrentFragmentationLevel >= @FragmentationLevel2 THEN 'High' - WHEN @CurrentFragmentationLevel >= @FragmentationLevel1 AND @CurrentFragmentationLevel < @FragmentationLevel2 THEN 'Medium' - WHEN @CurrentFragmentationLevel < @FragmentationLevel1 THEN 'Low' - END + SET @CurrentFragmentationGroup = CASE + WHEN @CurrentFragmentationLevel >= @FragmentationLevel2 THEN 'High' + WHEN @CurrentFragmentationLevel >= @FragmentationLevel1 AND @CurrentFragmentationLevel < @FragmentationLevel2 THEN 'Medium' + WHEN @CurrentFragmentationLevel < @FragmentationLevel1 THEN 'Low' END -- Which actions are allowed? - IF @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) + IF NOT (@CurrentIsMemoryOptimized = 1) + AND NOT (@CurrentAllowPageLocks = 0) BEGIN - IF NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) - AND NOT (@CurrentAllowPageLocks = 0) - BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REORGANIZE') - END - IF NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) - BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REBUILD_OFFLINE') - END - IF @EngineEdition IN (3, 5, 8) - AND NOT (@CurrentOnReadOnlyFileGroup = 1) - AND NOT (@CurrentIsMemoryOptimized = 1) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1 AND @CurrentIsImageText IS NOT NULL) - AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1 AND @CurrentIsFileStream IS NOT NULL) - AND NOT (@CurrentIndexType = 3) - AND NOT (@CurrentIndexType = 4) - AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @CurrentHasClusteredColumnstore IS NOT NULL AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND @CurrentIsColumnstoreOrdered IS NOT NULL AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) - BEGIN - INSERT INTO @CurrentActionsAllowed ([Action]) - VALUES ('INDEX_REBUILD_ONLINE') - END + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REORGANIZE') + END + IF NOT (@CurrentIsMemoryOptimized = 1) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REBUILD_OFFLINE') + END + IF @EngineEdition IN (3, 5, 8) + AND NOT (@CurrentIsMemoryOptimized = 1) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsImageText = 1 AND @CurrentIsImageText IS NOT NULL) + AND NOT (@CurrentIndexType = 1 AND @CurrentIsFileStream = 1 AND @CurrentIsFileStream IS NOT NULL) + AND NOT (@CurrentIndexType = 3) + AND NOT (@CurrentIndexType = 4) + AND NOT (@CurrentIndexType = 5 AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 2 AND @CurrentHasClusteredColumnstore = 1 AND @CurrentHasClusteredColumnstore IS NOT NULL AND NOT (@Version >= 15 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + AND NOT (@CurrentIndexType = 5 AND @CurrentIsColumnstoreOrdered = 1 AND @CurrentIsColumnstoreOrdered IS NOT NULL AND NOT (@Version >= 17 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous'))) + BEGIN + INSERT INTO @CurrentActionsAllowed ([Action]) + VALUES ('INDEX_REBUILD_ONLINE') END -- Decide action - IF @CurrentIndexID IS NOT NULL - AND EXISTS(SELECT * FROM @ActionsPreferred) - AND (@CurrentPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) + IF (@CurrentPageCount >= @MinNumberOfPages OR @MinNumberOfPages = 0) AND (@CurrentPageCount <= @MaxNumberOfPages OR @MaxNumberOfPages IS NULL) AND @CurrentResumableIndexOperation = 0 BEGIN @@ -4761,148 +4763,149 @@ BEGIN BEGIN SET @CurrentMaxDOP = 1 END - END - - -- Create index comment - IF @CurrentAction 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 @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 + ', ' - IF @CurrentIsImageText IS NOT NULL SET @CurrentComment += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsFileStream IS NOT NULL SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentHasClusteredColumnstore IS NOT NULL AND @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsColumnstoreOrdered IS NOT NULL AND @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsComputed IS NOT NULL SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsClusteredIndexComputed IS NOT NULL AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @CurrentIsTimestamp IS NOT NULL SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' - IF @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 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(max)),'N/A') + ', ' - SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar(max)),'N/A') - END - - IF @CurrentAction IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) - BEGIN - SET @CurrentExtendedInfo = (SELECT * - FROM (SELECT CAST(@CurrentPageCount AS nvarchar(max)) AS [PageCount], - CAST(@CurrentFragmentationLevel AS nvarchar(max)) AS Fragmentation - ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) - END - - IF @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) - BEGIN - SET @CurrentDatabaseContext = @CurrentDatabaseName - - SET @CurrentCommandType = 'ALTER_INDEX' - SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - 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(max)) - - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'Y' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 + -- Create index comment + IF @CurrentAction IS NOT NULL BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('SORT_IN_TEMPDB = ON') + 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 + ', ' + IF @CurrentIsImageText IS NOT NULL SET @CurrentComment += 'ImageText: ' + CASE WHEN @CurrentIsImageText = 1 THEN 'Yes' WHEN @CurrentIsImageText = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsFileStream IS NOT NULL SET @CurrentComment += 'FileStream: ' + CASE WHEN @CurrentIsFileStream = 1 THEN 'Yes' WHEN @CurrentIsFileStream = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentHasClusteredColumnstore IS NOT NULL AND @CurrentIndexType NOT IN(5, 6) SET @CurrentComment += 'HasClusteredColumnstore: ' + CASE WHEN @CurrentHasClusteredColumnstore = 1 THEN 'Yes' WHEN @CurrentHasClusteredColumnstore = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsColumnstoreOrdered IS NOT NULL AND @CurrentIndexType = 5 SET @CurrentComment += 'IsColumnstoreOrdered: ' + CASE WHEN @CurrentIsColumnstoreOrdered = 1 THEN 'Yes' WHEN @CurrentIsColumnstoreOrdered = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsComputed IS NOT NULL SET @CurrentComment += 'Computed: ' + CASE WHEN @CurrentIsComputed = 1 THEN 'Yes' WHEN @CurrentIsComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsClusteredIndexComputed IS NOT NULL AND @CurrentIndexType = 2 SET @CurrentComment += 'ClusteredIndexComputed: ' + CASE WHEN @CurrentIsClusteredIndexComputed = 1 THEN 'Yes' WHEN @CurrentIsClusteredIndexComputed = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @CurrentIsTimestamp IS NOT NULL SET @CurrentComment += 'Timestamp: ' + CASE WHEN @CurrentIsTimestamp = 1 THEN 'Yes' WHEN @CurrentIsTimestamp = 0 THEN 'No' ELSE 'N/A' END + ', ' + IF @Resumable = 'Y' SET @CurrentComment += 'HasFilter: ' + CASE WHEN @CurrentHasFilter = 1 THEN 'Yes' WHEN @CurrentHasFilter = 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(max)),'N/A') + ', ' + SET @CurrentComment += 'Fragmentation: ' + ISNULL(CAST(@CurrentFragmentationLevel AS nvarchar(max)),'N/A') END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @SortInTempdb = 'N' AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 + IF @CurrentAction IS NOT NULL AND (@CurrentPageCount IS NOT NULL OR @CurrentFragmentationLevel IS NOT NULL) BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('SORT_IN_TEMPDB = OFF') + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentPageCount AS nvarchar(max)) AS [PageCount], + CAST(@CurrentFragmentationLevel AS nvarchar(max)) AS Fragmentation + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 + IF @CurrentAction IS NOT NULL AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END) - END + SET @CurrentDatabaseContext = @CurrentDatabaseName - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 1 AND @WaitAtLowPriorityMaxDuration IS NOT NULL - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + ')') - END + SET @CurrentCommandType = 'ALTER_INDEX' - IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('ONLINE = OFF') - END + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + 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(max)) - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentMaxDOP IS NOT NULL - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) - END + 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) + VALUES('SORT_IN_TEMPDB = ON') + 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) AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max))) - END + 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) + VALUES('SORT_IN_TEMPDB = OFF') + END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END) - END + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('ONLINE = ON' + CASE WHEN @WaitAtLowPriorityMaxDuration IS NOT NULL THEN ' (WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + '))' ELSE '' END) + END - IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,4) AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('DATA_COMPRESSION = ' + @DataCompression) - END + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 1 AND @WaitAtLowPriorityMaxDuration IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('WAIT_AT_LOW_PRIORITY (MAX_DURATION = ' + CAST(@WaitAtLowPriorityMaxDuration AS nvarchar(max)) + ', ABORT_AFTER_WAIT = ' + UPPER(@WaitAtLowPriorityAbortAfterWait) + ')') + END - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES(CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL) THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END) - END + IF @CurrentAction = 'INDEX_REBUILD_OFFLINE' AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('ONLINE = OFF') + END - IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL)) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max))) - END + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @CurrentMaxDOP IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) + END - IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('LOB_COMPACTION = ON') - 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) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('FILLFACTOR = ' + CAST(@FillFactor AS nvarchar(max))) + END - IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'N' - BEGIN - INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) - VALUES('LOB_COMPACTION = OFF') - END + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @PadIndex IS NOT NULL AND @CurrentIsPartition = 0 AND @CurrentIndexType IN(1,2,3,4) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('PAD_INDEX = ' + CASE WHEN @PadIndex = 'Y' THEN 'ON' WHEN @PadIndex = 'N' THEN 'OFF' END) + END - IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) - BEGIN - SELECT @CurrentCommand += ' WITH (' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) + ')' - FROM @CurrentAlterIndexWithClauseArguments - END + IF @CurrentAction IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') AND @DataCompression IS NOT NULL AND @CurrentIndexType IN(1,2,4) AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('DATA_COMPRESSION = ' + @DataCompression) + END - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentResumableIndexOperation = 0 + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES(CASE WHEN @Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL) THEN 'RESUMABLE = ON' ELSE 'RESUMABLE = OFF' END) + END - IF @Delay > 0 - BEGIN - SET @CurrentDelay = DATEADD(ss,@Delay,'1900-01-01') - WAITFOR DELAY @CurrentDelay + IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND ((@Resumable = 'Y' AND @CurrentIndexType IN(1,2) AND (@CurrentIsComputed = 0 OR @CurrentIsComputed IS NULL) AND (@CurrentIsClusteredIndexComputed = 0 OR @CurrentIsClusteredIndexComputed IS NULL) AND (@CurrentIsTimestamp = 0 OR @CurrentIsTimestamp IS NULL) AND @CurrentHasFilter = 0 AND (@CurrentHasClusteredColumnstore = 0 OR @CurrentHasClusteredColumnstore IS NULL)) OR @CurrentResumableIndexOperation = 1) AND @TimeLimit IS NOT NULL + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('MAX_DURATION = ' + CAST(CASE WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) < 1 THEN 1 WHEN DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) > 10080 THEN 10080 ELSE DATEDIFF(MINUTE,SYSDATETIME(),DATEADD(SECOND,@TimeLimit,@StartTime)) END AS nvarchar(max))) + END + + IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'Y' + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('LOB_COMPACTION = ON') + END + + IF @CurrentAction IN('INDEX_REORGANIZE') AND @LOBCompaction = 'N' + BEGIN + INSERT INTO @CurrentAlterIndexWithClauseArguments (Argument) + VALUES('LOB_COMPACTION = OFF') + END + + IF EXISTS (SELECT * FROM @CurrentAlterIndexWithClauseArguments) + BEGIN + SELECT @CurrentCommand += ' WITH (' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) + ')' + FROM @CurrentAlterIndexWithClauseArguments + END + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @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 + + IF @Delay > 0 + BEGIN + SET @CurrentDelay = DATEADD(ss,@Delay,'1900-01-01') + WAITFOR DELAY @CurrentDelay + END END END SET @CurrentMaxDOP = @MaxDOP - -- Should the statistics be updated? - Pre checks and final decision - IF @CurrentStatisticsID IS NOT NULL + -- Should the statistics be updated? + IF @CurrentUpdateStatisticsCompleted = 0 + AND @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) BEGIN @@ -5041,124 +5044,125 @@ BEGIN BEGIN SET @CurrentUpdateStatistics = 'N' END - END - - SET @CurrentStatisticsSample = @StatisticsSample - SET @CurrentStatisticsPersistSample = @StatisticsPersistSample - SET @CurrentStatisticsResample = @StatisticsResample - -- Incremental statistics only supports RESAMPLE - IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 - BEGIN - SET @CurrentStatisticsSample = NULL - SET @CurrentStatisticsPersistSample = NULL - SET @CurrentStatisticsResample = 'Y' - END - - -- Create statistics comment - IF @CurrentUpdateStatistics = 'Y' - BEGIN - SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' - SET @CurrentComment += 'StatisticsType: ' + 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 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' ELSE 'N/A' END + ', ' - SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar(max)),'N/A') + ', ' - SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar(max)),'N/A') - END + SET @CurrentStatisticsSample = @StatisticsSample + SET @CurrentStatisticsPersistSample = @StatisticsPersistSample + SET @CurrentStatisticsResample = @StatisticsResample - IF @CurrentUpdateStatistics = 'Y' AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) - BEGIN - SET @CurrentExtendedInfo = (SELECT * - FROM (SELECT CAST(@CurrentRowCount AS nvarchar(max)) AS [RowCount], - CAST(@CurrentModificationCounter AS nvarchar(max)) AS ModificationCounter - ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) - END - ELSE - BEGIN - SET @CurrentExtendedInfo = NULL - END - - IF @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) - BEGIN - SET @CurrentDatabaseContext = @CurrentDatabaseName - - SET @CurrentCommandType = 'UPDATE_STATISTICS' - - SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' - SET @CurrentCommand += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) - - IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) + -- Incremental statistics only supports RESAMPLE + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) + SET @CurrentStatisticsSample = NULL + SET @CurrentStatisticsPersistSample = NULL + SET @CurrentStatisticsResample = 'Y' END - IF @CurrentStatisticsSample = 100 + -- Create statistics comment + IF @CurrentUpdateStatistics = 'Y' BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('FULLSCAN') + SET @CurrentComment = 'ObjectType: ' + CASE WHEN @CurrentObjectType = 'U' THEN 'Table' WHEN @CurrentObjectType = 'V' THEN 'View' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'StatisticsType: ' + 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 'Yes' WHEN @CurrentIsIncremental = 0 THEN 'No' ELSE 'N/A' END + ', ' + SET @CurrentComment += 'RowCount: ' + ISNULL(CAST(@CurrentRowCount AS nvarchar(max)),'N/A') + ', ' + SET @CurrentComment += 'ModificationCounter: ' + ISNULL(CAST(@CurrentModificationCounter AS nvarchar(max)),'N/A') END - IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 + IF @CurrentUpdateStatistics = 'Y' AND (@CurrentRowCount IS NOT NULL OR @CurrentModificationCounter IS NOT NULL) BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT') + SET @CurrentExtendedInfo = (SELECT * + FROM (SELECT CAST(@CurrentRowCount AS nvarchar(max)) AS [RowCount], + CAST(@CurrentModificationCounter AS nvarchar(max)) AS ModificationCounter + ) ExtendedInfo FOR XML RAW('ExtendedInfo'), ELEMENTS) END - - IF @CurrentStatisticsPersistSample = 'Y' + ELSE BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('PERSIST_SAMPLE_PERCENT = ON') + SET @CurrentExtendedInfo = NULL END - IF @CurrentStatisticsPersistSample = 'N' + IF @CurrentUpdateStatistics = 'Y' AND (SYSDATETIME() < DATEADD(SECOND,@TimeLimit,@StartTime) OR @TimeLimit IS NULL) BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('PERSIST_SAMPLE_PERCENT = OFF') - END + SET @CurrentDatabaseContext = @CurrentDatabaseName - IF @CurrentNoRecompute = 1 - BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('NORECOMPUTE') - END + SET @CurrentCommandType = 'UPDATE_STATISTICS' - IF @CurrentStatisticsResample = 'Y' - BEGIN - INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) - VALUES('RESAMPLE') - END + SET @CurrentCommand = '' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + SET @CurrentCommand += 'UPDATE STATISTICS ' + QUOTENAME(@CurrentSchemaName) + '.' + QUOTENAME(@CurrentObjectName) + ' ' + QUOTENAME(@CurrentStatisticsName) - IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) - BEGIN - SELECT @CurrentCommand += ' WITH ' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) - FROM @CurrentUpdateStatisticsWithClauseArguments - END + IF @CurrentMaxDOP IS NOT NULL AND (@Version >= 14.03015 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('MAXDOP = ' + CAST(@CurrentMaxDOP AS nvarchar(max))) + END - IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + IF @CurrentStatisticsSample = 100 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('FULLSCAN') + END - EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @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 + IF @CurrentStatisticsSample IS NOT NULL AND @CurrentStatisticsSample <> 100 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('SAMPLE ' + CAST(@CurrentStatisticsSample AS nvarchar(max)) + ' PERCENT') + END + + IF @CurrentStatisticsPersistSample = 'Y' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('PERSIST_SAMPLE_PERCENT = ON') + END + + IF @CurrentStatisticsPersistSample = 'N' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('PERSIST_SAMPLE_PERCENT = OFF') + END + + IF @CurrentNoRecompute = 1 + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('NORECOMPUTE') + END + + IF @CurrentStatisticsResample = 'Y' + BEGIN + INSERT INTO @CurrentUpdateStatisticsWithClauseArguments (Argument) + VALUES('RESAMPLE') + END + + IF EXISTS (SELECT * FROM @CurrentUpdateStatisticsWithClauseArguments) + BEGIN + SELECT @CurrentCommand += ' WITH ' + STRING_AGG(Argument, ', ') WITHIN GROUP (ORDER BY ID ASC) + FROM @CurrentUpdateStatisticsWithClauseArguments + END + + IF @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND @CurrentPartitionNumber IS NOT NULL SET @CurrentCommand += ' ON PARTITIONS(' + CAST(@CurrentPartitionNumber AS nvarchar(max)) + ')' + + EXECUTE @CurrentCommandOutput = dbo.CommandExecute @DatabaseContext = @CurrentDatabaseContext, @Command = @CurrentCommand, @CommandType = @CurrentCommandType, @Mode = 2, @Comment = @CurrentComment, @DatabaseName = @CurrentDatabaseName, @SchemaName = @CurrentSchemaName, @ObjectName = @CurrentObjectName, @ObjectType = @CurrentObjectType, @IndexName = @CurrentIndexName, @IndexType = @CurrentIndexType, @StatisticsName = @CurrentStatisticsName, @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 + END END NoAction: -- Update that the index or statistics is completed UPDATE @tmpIndexesStatistics - SET Completed = 1 + SET AlterIndexCompleted = 1, + UpdateStatisticsCompleted = 1 WHERE Selected = 1 AND Completed = 0 AND [Order] = @CurrentIxOrder AND ID = @CurrentIxID -- Update that statistics on remaining partitions are completed where no update is needed - IF (NOT EXISTS(SELECT * FROM @ActionsPreferred) OR @CurrentIndexID IS NULL) AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentStatisticsID IS NOT NULL + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentStatisticsID IS NOT NULL BEGIN UPDATE tmpIndexesStatistics - SET Completed = 1 + SET UpdateStatisticsCompleted = 1 FROM @tmpIndexesStatistics tmpIndexesStatistics INNER JOIN @IncrementalStatsProperties IncrementalStatsProperties ON tmpIndexesStatistics.ObjectID = IncrementalStatsProperties.ObjectID AND tmpIndexesStatistics.StatisticsID = IncrementalStatsProperties.StatisticsID AND tmpIndexesStatistics.PartitionNumber = IncrementalStatsProperties.PartitionNumber WHERE tmpIndexesStatistics.ObjectID = @CurrentObjectID @@ -5196,6 +5200,8 @@ BEGIN SET @CurrentPartitionNumber = NULL SET @CurrentPartitionCount = NULL SET @CurrentInRowDataPageCount = NULL + SET @CurrentAlterIndexCompleted = NULL + SET @CurrentUpdateStatisticsCompleted = NULL SET @CurrentIsPartition = NULL SET @CurrentIndexExists = NULL SET @CurrentStatisticsExists = NULL diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 334ba7de..5747946b 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -7284afc0dfac75fb8b2b3ad99b395e2de493c1a1803af7673f596a914130c241 CommandExecute.sql +f3db9ab926e4d0fa4558a8e0e014029c1dde9c2e4f35e25afa5ea0c610dc9f88 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -9a87a2fa92a2de3a6d7c38357b680925caebc5f9c266cc66609e7c2a1b158833 DatabaseBackup.sql -05ebb59557fdd9b45c1ae3ff95287cbaece35d2c0475ef72fea07dcc8ed79601 DatabaseIntegrityCheck.sql -f4c469edeb6d9742f572dd2eec1b094c306f38cc2dbfc58472723677430ce49d IndexOptimize.sql -a48c475d1b61ccef20b9d6186868c1930d979c7c9e61a8d9966c2dfac27bb672 MaintenanceSolution.sql -d8feab1d7a9b39e7c2ecf1ca5b28c2fb7c9f29d832577573e4e3e620707a99a4 MaintenanceSolutionAzureSQLDatabase.sql +56408d97466a94203401880b720cb6247f3f55f3ca3ca445fc3ddd6ae5bdd7b4 DatabaseBackup.sql +9460affbaa6191e58aceddf696a9e5d6b2db80c50869bf2c478deac1b036f426 DatabaseIntegrityCheck.sql +fb4af452182f30854c0bc1f810bb30e61b7eee0c1ab05fe1eeab9855f75bb6a8 IndexOptimize.sql +b986af12349b949772cca5509c156a7ad3bf85e70bc06c5d95e40206b29afd99 MaintenanceSolution.sql +db49c641e781e19de80187b7cad0a900d758dde67f542969ea6cec259f0704c7 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 0f22da0279a3724ba5b966a970142ed0cb3f53c0 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 4 Aug 2026 22:45:51 +0200 Subject: [PATCH 138/177] Create Header.sql --- header-and-footer/Header.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 header-and-footer/Header.sql diff --git a/header-and-footer/Header.sql b/header-and-footer/Header.sql new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/header-and-footer/Header.sql @@ -0,0 +1 @@ + From d14a503a413232eff282f2cda8636b1d22b99152 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Tue, 4 Aug 2026 22:46:25 +0200 Subject: [PATCH 139/177] Add files via upload --- header-and-footer/Footer.sql | 283 +++++++++++++++++++ header-and-footer/Header.sql | 66 ++++- header-and-footer/HeaderAzureSQLDatabase.sql | 20 ++ 3 files changed, 368 insertions(+), 1 deletion(-) create mode 100644 header-and-footer/Footer.sql create mode 100644 header-and-footer/HeaderAzureSQLDatabase.sql diff --git a/header-and-footer/Footer.sql b/header-and-footer/Footer.sql new file mode 100644 index 00000000..dccd6e71 --- /dev/null +++ b/header-and-footer/Footer.sql @@ -0,0 +1,283 @@ +IF (SELECT [Value] FROM #Config WHERE Name = 'CreateJobs') = 'Y' + AND SERVERPROPERTY('EngineEdition') NOT IN(4, 5) + AND (IS_SRVROLEMEMBER('sysadmin') = 1 OR (EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa')) + AND NOT (EXISTS (SELECT * FROM #Config WHERE Name = 'BackupDirectory' AND [Value] IS NOT NULL) AND EXISTS (SELECT * FROM #Config WHERE Name = 'BackupURL' AND [Value] IS NOT NULL)) + AND NOT (EXISTS (SELECT * FROM #Config WHERE Name = 'BackupURL' AND [Value] IS NOT NULL) AND EXISTS (SELECT * FROM #Config WHERE Name = 'CleanupTime' AND [Value] IS NOT NULL)) +BEGIN + + DECLARE @BackupDirectory nvarchar(max) + DECLARE @BackupURL nvarchar(max) + DECLARE @CleanupTime int + DECLARE @OutputFileDirectory nvarchar(max) + DECLARE @LogToTable nvarchar(max) + DECLARE @DatabaseName nvarchar(max) + + DECLARE @HostPlatform nvarchar(max) + DECLARE @DirectorySeparator nvarchar(max) + DECLARE @LogDirectory nvarchar(max) + + DECLARE @TokenServer 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) + + DECLARE @JobDescription nvarchar(max) + DECLARE @JobCategory nvarchar(max) + DECLARE @JobOwner nvarchar(max) + + DECLARE @Jobs TABLE (JobID int IDENTITY, + [Name] nvarchar(max), + CommandTSQL nvarchar(max), + CommandCmdExec nvarchar(max), + DatabaseName varchar(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 @CurrentJobStepCommand nvarchar(max) + DECLARE @CurrentJobStepSubSystem nvarchar(max) + DECLARE @CurrentJobStepDatabaseName nvarchar(max) + DECLARE @CurrentOutputFileName nvarchar(max) + + DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info + + SELECT @DirectorySeparator = CASE + WHEN @HostPlatform = 'Windows' THEN '\' + WHEN @HostPlatform = 'Linux' THEN '/' + END + + SET @TokenServer = '$' + '(ESCAPE_SQUOTE(SRVR))' + SET @TokenStepID = '$' + '(ESCAPE_SQUOTE(STEPID))' + SET @TokenDate = '$' + '(ESCAPE_SQUOTE(DATE))' + SET @TokenTime = '$' + '(ESCAPE_SQUOTE(TIME))' + SET @TokenJobName = '$' + '(ESCAPE_SQUOTE(JOBNAME))' + SET @TokenStepName = '$' + '(ESCAPE_SQUOTE(STEPNAME))' + + IF @HostPlatform = 'Windows' + BEGIN + SET @TokenLogDirectory = '$' + '(ESCAPE_SQUOTE(SQLLOGDIR))' + END + + SELECT @BackupDirectory = Value + FROM #Config + WHERE [Name] = 'BackupDirectory' + + SELECT @BackupURL = Value + FROM #Config + WHERE [Name] = 'BackupURL' + + SELECT @CleanupTime = Value + FROM #Config + WHERE [Name] = 'CleanupTime' + + SELECT @OutputFileDirectory = Value + FROM #Config + WHERE [Name] = 'OutputFileDirectory' + + SELECT @LogToTable = Value + FROM #Config + WHERE [Name] = 'LogToTable' + + SELECT @DatabaseName = Value + FROM #Config + WHERE [Name] = 'DatabaseName' + + SELECT @LogDirectory = [path] + FROM sys.dm_os_server_diagnostics_log_configurations + + IF @OutputFileDirectory IS NOT NULL AND RIGHT(@OutputFileDirectory,1) = @DirectorySeparator + BEGIN + SET @OutputFileDirectory = LEFT(@OutputFileDirectory, LEN(@OutputFileDirectory) - 1) + END + + IF @LogDirectory IS NOT NULL AND RIGHT(@LogDirectory,1) = @DirectorySeparator + BEGIN + SET @LogDirectory = LEFT(@LogDirectory, LEN(@LogDirectory) - 1) + END + + SET @JobDescription = 'Source: https://ola.hallengren.com' + SET @JobCategory = 'Database Maintenance' + + IF @AmazonRDS = 0 + BEGIN + SET @JobOwner = SUSER_SNAME(0x01) + END + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) + VALUES('DatabaseBackup - SYSTEM_DATABASES - FULL', + 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''SYSTEM_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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) + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) + VALUES('DatabaseBackup - USER_DATABASES - DIFF', + 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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) + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) + VALUES('DatabaseBackup - USER_DATABASES - FULL', + 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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) + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) + VALUES('DatabaseBackup - USER_DATABASES - LOG', + 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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) + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) + VALUES('DatabaseIntegrityCheck - SYSTEM_DATABASES', + 'EXECUTE [dbo].[DatabaseIntegrityCheck]' + CHAR(13) + CHAR(10) + '@Databases = ''SYSTEM_DATABASES'',' + CHAR(13) + CHAR(10) + '@NoInformationalMessages = ''Y'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', + @DatabaseName) + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) + VALUES('DatabaseIntegrityCheck - USER_DATABASES', + 'EXECUTE [dbo].[DatabaseIntegrityCheck]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + '@NoInformationalMessages = ''Y'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', + @DatabaseName) + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) + VALUES('IndexOptimize - USER_DATABASES', + 'EXECUTE [dbo].[IndexOptimize]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', + @DatabaseName) + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) + VALUES('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') + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) + VALUES('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') + + INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) + VALUES('CommandLog Cleanup', + 'DELETE FROM [dbo].[CommandLog]' + CHAR(13) + CHAR(10) + 'WHERE StartTime < DATEADD(dd,-30,GETDATE())', + @DatabaseName) + + INSERT INTO @Jobs ([Name], CommandCmdExec) + VALUES('Output File Cleanup', + 'powershell.exe -NoProfile -Command "Get-ChildItem -LiteralPath ''' + REPLACE(COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory),'''','''''') + ''' -Filter ''*_*_*_*.txt'' -File | Where-Object { $_.LastWriteTime.Date -le (Get-Date).Date.AddDays(-30) } | ForEach-Object { Write-Output (''del '' + $_.FullName); Remove-Item -LiteralPath $_.FullName }"') + + IF @AmazonRDS = 1 + BEGIN + UPDATE @Jobs + 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 + SET Selected = 1 + END + ELSE IF @HostPlatform = 'Linux' + BEGIN + UPDATE @Jobs + SET Selected = 1 + WHERE CommandTSQL IS NOT NULL + END + + WHILE EXISTS (SELECT * FROM @Jobs WHERE Completed = 0 AND Selected = 1) + BEGIN + SELECT TOP 1 @CurrentJobID = JobID, + @CurrentJobName = [Name], + @CurrentCommandTSQL = CommandTSQL, + @CurrentCommandCmdExec = CommandCmdExec, + @CurrentDatabaseName = DatabaseName + FROM @Jobs + WHERE Completed = 0 + AND Selected = 1 + ORDER BY JobID ASC + + IF @CurrentCommandTSQL IS NOT NULL + BEGIN + SET @CurrentJobStepSubSystem = 'TSQL' + SET @CurrentJobStepCommand = @CurrentCommandTSQL + SET @CurrentJobStepDatabaseName = @CurrentDatabaseName + END + ELSE IF @CurrentCommandCmdExec IS NOT NULL AND @HostPlatform = 'Windows' + BEGIN + SET @CurrentJobStepSubSystem = 'CMDEXEC' + SET @CurrentJobStepCommand = @CurrentCommandCmdExec + SET @CurrentJobStepDatabaseName = NULL + END + + IF @AmazonRDS = 0 AND SERVERPROPERTY('EngineEdition') <> 8 + BEGIN + SET @CurrentOutputFileName = COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + @DirectorySeparator + @TokenJobName + '_' + @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 @CurrentJobStepCommand = NULL + SET @CurrentJobStepSubSystem = NULL + SET @CurrentJobStepDatabaseName = NULL + SET @CurrentOutputFileName = NULL + + END + +END +GO + +DECLARE @job_id uniqueidentifier +DECLARE @step_id int +DECLARE @command nvarchar(max) +DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END + +IF @AmazonRDS = 0 +BEGIN + + DECLARE JobCursor CURSOR LOCAL FAST_FORWARD FOR SELECT job_id, step_id, command FROM msdb.dbo.sysjobsteps WHERE command LIKE '%DatabaseBackup%@CheckSum%' COLLATE SQL_Latin1_General_CP1_CS_AS OR command LIKE '%DatabaseBackup%@ModificationLevel%' OR command LIKE '%DatabaseBackup%@LogSizeSinceLastLogBackup%' OR command LIKE '%DatabaseBackup%@TimeSinceLastLogBackup%' + + OPEN JobCursor + + FETCH JobCursor INTO @job_id, @step_id, @command + + WHILE @@FETCH_STATUS = 0 + BEGIN + SET @command = REPLACE(@command, '@CheckSum', '@Checksum') + SET @command = REPLACE(@command, '@ModificationLevel', '@MinModificationLevel') + SET @command = REPLACE(@command, '@LogSizeSinceLastLogBackup', '@MinLogSizeSinceLastLogBackup') + SET @command = REPLACE(@command, '@TimeSinceLastLogBackup', '@MinTimeSinceLastLogBackup') + + EXECUTE msdb.dbo.sp_update_jobstep @job_id = @job_id, @step_id = @step_id, @command = @command + + FETCH NEXT FROM JobCursor INTO @job_id, @step_id, @command + END + + CLOSE JobCursor + + DEALLOCATE JobCursor +END +GO diff --git a/header-and-footer/Header.sql b/header-and-footer/Header.sql index 8b137891..0b6f3b66 100644 --- a/header-and-footer/Header.sql +++ b/header-and-footer/Header.sql @@ -1 +1,65 @@ - +/* + +SQL Server Maintenance Solution - SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, and Azure SQL Managed Instance + +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 + +License: https://ola.hallengren.com/license.html + +GitHub: https://github.com/olahallengren/sql-server-maintenance-solution + +Version: + +You can contact me by e-mail at ola@hallengren.com. + +Ola Hallengren +https://ola.hallengren.com + +*/ + +USE [master] -- Specify the database in which the objects will be created. + +SET NOCOUNT ON + +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 @BackupURL nvarchar(max) = NULL -- Specify the backup root URL. +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. + +DECLARE @ErrorMessage nvarchar(max) + +IF IS_SRVROLEMEMBER('sysadmin') = 0 AND NOT (EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') 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.' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT +END + +IF @BackupDirectory IS NOT NULL AND @BackupURL IS NOT NULL +BEGIN + SET @ErrorMessage = 'Only one of the variables @BackupDirectory and @BackupURL can be set.' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT +END + +IF @BackupURL IS NOT NULL AND @CleanupTime IS NOT NULL +BEGIN + SET @ErrorMessage = 'The variable @CleanupTime is not supported with backup to URL.' + RAISERROR(@ErrorMessage,16,1) WITH NOWAIT +END + +IF OBJECT_ID('tempdb..#Config') IS NOT NULL DROP TABLE #Config + +CREATE TABLE #Config ([Name] nvarchar(max), + [Value] nvarchar(max)) + +INSERT INTO #Config ([Name], [Value]) VALUES('CreateJobs', @CreateJobs) +INSERT INTO #Config ([Name], [Value]) VALUES('BackupDirectory', @BackupDirectory) +INSERT INTO #Config ([Name], [Value]) VALUES('BackupURL', @BackupURL) +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()) +GO \ No newline at end of file diff --git a/header-and-footer/HeaderAzureSQLDatabase.sql b/header-and-footer/HeaderAzureSQLDatabase.sql new file mode 100644 index 00000000..b51418f2 --- /dev/null +++ b/header-and-footer/HeaderAzureSQLDatabase.sql @@ -0,0 +1,20 @@ +/* + +SQL Server Maintenance Solution - Azure SQL Database + +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 + +License: https://ola.hallengren.com/license.html + +GitHub: https://github.com/olahallengren/sql-server-maintenance-solution + +Version: + +You can contact me by e-mail at ola@hallengren.com. + +Ola Hallengren +https://ola.hallengren.com + +*/ + From a9b003764ad112e2ecfcb53d25daeef08e387bf7 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 5 Aug 2026 00:37:38 +0200 Subject: [PATCH 140/177] Add files via upload --- .github/workflows/check-scripts.yml | 65 +++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 .github/workflows/check-scripts.yml diff --git a/.github/workflows/check-scripts.yml b/.github/workflows/check-scripts.yml new file mode 100644 index 00000000..ce90b7b1 --- /dev/null +++ b/.github/workflows/check-scripts.yml @@ -0,0 +1,65 @@ +name: Check scripts + +# Verifies that the scripts in the repository are consistent with each other before a pull request can be merged. + +on: + pull_request: + branches: + - main + workflow_dispatch: # adds a manual "Run workflow" button, handy for testing + +jobs: + checksums: + runs-on: ubuntu-latest + steps: + - name: Check out the repository + uses: actions/checkout@v5 + + - name: Check that every script is listed in SHA256SUMS.txt + run: | + ls *.sql | sort > /tmp/scripts.txt + awk '{print $2}' SHA256SUMS.txt | sort > /tmp/listed.txt + if ! diff /tmp/scripts.txt /tmp/listed.txt; then + echo "The scripts in the repository and the files listed in SHA256SUMS.txt do not match." + echo "Lines starting with < are scripts that are not listed; lines starting with > are listed files that do not exist." + exit 1 + fi + echo "All scripts are listed." + + - name: Check that the checksums are current + run: sha256sum -c SHA256SUMS.txt + + versions: + runs-on: ubuntu-latest + steps: + - name: Check out the repository + uses: actions/checkout@v5 + + - name: Check that every script has the same version timestamp + run: | + set -u + + # Every script in a release is built at the same time and stamped with that time. + # The installation scripts contain one stamp per stored procedure they include, so this also detects an installation script built from an outdated procedure. + PATTERN='Version: [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}' + + echo "Version timestamps found in each script:" + for f in *.sql; do + STAMPS=$(grep -hoE "$PATTERN" "$f" | sed 's/^Version: //' | sort -u | tr '\n' ' ') + printf ' %-42s %s\n' "$f" "${STAMPS:-(none)}" + done + + ALL=$(grep -hoE "$PATTERN" *.sql | sed 's/^Version: //' | sort -u) + COUNT=$(printf '%s\n' "$ALL" | grep -c . || true) + + echo + if [ "$COUNT" -eq 0 ]; then + echo "No version timestamps were found. The scripts are expected to carry one." + exit 1 + fi + if [ "$COUNT" -ne 1 ]; then + echo "The scripts do not all have the same version timestamp:" + printf '%s\n' "$ALL" | sed 's/^/ /' + exit 1 + fi + echo "All scripts have the same version timestamp: $ALL" From c953de1ec9534dc4b11b1c3807398ee1a3bc50c4 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 5 Aug 2026 00:44:14 +0200 Subject: [PATCH 141/177] Delete header-and-footer/Header.sql --- header-and-footer/Header.sql | 65 ------------------------------------ 1 file changed, 65 deletions(-) delete mode 100644 header-and-footer/Header.sql diff --git a/header-and-footer/Header.sql b/header-and-footer/Header.sql deleted file mode 100644 index 0b6f3b66..00000000 --- a/header-and-footer/Header.sql +++ /dev/null @@ -1,65 +0,0 @@ -/* - -SQL Server Maintenance Solution - SQL Server 2017, SQL Server 2019, SQL Server 2022, SQL Server 2025, and Azure SQL Managed Instance - -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 - -License: https://ola.hallengren.com/license.html - -GitHub: https://github.com/olahallengren/sql-server-maintenance-solution - -Version: - -You can contact me by e-mail at ola@hallengren.com. - -Ola Hallengren -https://ola.hallengren.com - -*/ - -USE [master] -- Specify the database in which the objects will be created. - -SET NOCOUNT ON - -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 @BackupURL nvarchar(max) = NULL -- Specify the backup root URL. -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. - -DECLARE @ErrorMessage nvarchar(max) - -IF IS_SRVROLEMEMBER('sysadmin') = 0 AND NOT (EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') 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.' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT -END - -IF @BackupDirectory IS NOT NULL AND @BackupURL IS NOT NULL -BEGIN - SET @ErrorMessage = 'Only one of the variables @BackupDirectory and @BackupURL can be set.' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT -END - -IF @BackupURL IS NOT NULL AND @CleanupTime IS NOT NULL -BEGIN - SET @ErrorMessage = 'The variable @CleanupTime is not supported with backup to URL.' - RAISERROR(@ErrorMessage,16,1) WITH NOWAIT -END - -IF OBJECT_ID('tempdb..#Config') IS NOT NULL DROP TABLE #Config - -CREATE TABLE #Config ([Name] nvarchar(max), - [Value] nvarchar(max)) - -INSERT INTO #Config ([Name], [Value]) VALUES('CreateJobs', @CreateJobs) -INSERT INTO #Config ([Name], [Value]) VALUES('BackupDirectory', @BackupDirectory) -INSERT INTO #Config ([Name], [Value]) VALUES('BackupURL', @BackupURL) -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()) -GO \ No newline at end of file From f278a847b7aa4575ef96a8917eba99013c50470a Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 5 Aug 2026 00:44:39 +0200 Subject: [PATCH 142/177] Delete .github/workflows/check-checksums.yml --- .github/workflows/check-checksums.yml | 30 --------------------------- 1 file changed, 30 deletions(-) delete mode 100644 .github/workflows/check-checksums.yml diff --git a/.github/workflows/check-checksums.yml b/.github/workflows/check-checksums.yml deleted file mode 100644 index e2bb0cff..00000000 --- a/.github/workflows/check-checksums.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Check checksums - -# Verifies SHA256SUMS.txt against the scripts before a pull request can be merged. - -on: - pull_request: - branches: - - main - workflow_dispatch: # adds a manual "Run workflow" button, handy for testing - -jobs: - checksums: - runs-on: ubuntu-latest - steps: - - name: Check out the repository - uses: actions/checkout@v5 - - - name: Check that every script is listed in SHA256SUMS.txt - run: | - ls *.sql | sort > /tmp/scripts.txt - awk '{print $2}' SHA256SUMS.txt | sort > /tmp/listed.txt - if ! diff /tmp/scripts.txt /tmp/listed.txt; then - echo "The scripts in the repository and the files listed in SHA256SUMS.txt do not match." - echo "Lines starting with < are scripts that are not listed; lines starting with > are listed files that do not exist." - exit 1 - fi - echo "All scripts are listed." - - - name: Check that the checksums are current - run: sha256sum -c SHA256SUMS.txt From ad72c4738c7ebcb21e125cba60ca1219c4695b16 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 5 Aug 2026 00:46:14 +0200 Subject: [PATCH 143/177] Delete header-and-footer/Footer.sql --- header-and-footer/Footer.sql | 283 ----------------------------------- 1 file changed, 283 deletions(-) delete mode 100644 header-and-footer/Footer.sql diff --git a/header-and-footer/Footer.sql b/header-and-footer/Footer.sql deleted file mode 100644 index dccd6e71..00000000 --- a/header-and-footer/Footer.sql +++ /dev/null @@ -1,283 +0,0 @@ -IF (SELECT [Value] FROM #Config WHERE Name = 'CreateJobs') = 'Y' - AND SERVERPROPERTY('EngineEdition') NOT IN(4, 5) - AND (IS_SRVROLEMEMBER('sysadmin') = 1 OR (EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa')) - AND NOT (EXISTS (SELECT * FROM #Config WHERE Name = 'BackupDirectory' AND [Value] IS NOT NULL) AND EXISTS (SELECT * FROM #Config WHERE Name = 'BackupURL' AND [Value] IS NOT NULL)) - AND NOT (EXISTS (SELECT * FROM #Config WHERE Name = 'BackupURL' AND [Value] IS NOT NULL) AND EXISTS (SELECT * FROM #Config WHERE Name = 'CleanupTime' AND [Value] IS NOT NULL)) -BEGIN - - DECLARE @BackupDirectory nvarchar(max) - DECLARE @BackupURL nvarchar(max) - DECLARE @CleanupTime int - DECLARE @OutputFileDirectory nvarchar(max) - DECLARE @LogToTable nvarchar(max) - DECLARE @DatabaseName nvarchar(max) - - DECLARE @HostPlatform nvarchar(max) - DECLARE @DirectorySeparator nvarchar(max) - DECLARE @LogDirectory nvarchar(max) - - DECLARE @TokenServer 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) - - DECLARE @JobDescription nvarchar(max) - DECLARE @JobCategory nvarchar(max) - DECLARE @JobOwner nvarchar(max) - - DECLARE @Jobs TABLE (JobID int IDENTITY, - [Name] nvarchar(max), - CommandTSQL nvarchar(max), - CommandCmdExec nvarchar(max), - DatabaseName varchar(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 @CurrentJobStepCommand nvarchar(max) - DECLARE @CurrentJobStepSubSystem nvarchar(max) - DECLARE @CurrentJobStepDatabaseName nvarchar(max) - DECLARE @CurrentOutputFileName nvarchar(max) - - DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END - - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info - - SELECT @DirectorySeparator = CASE - WHEN @HostPlatform = 'Windows' THEN '\' - WHEN @HostPlatform = 'Linux' THEN '/' - END - - SET @TokenServer = '$' + '(ESCAPE_SQUOTE(SRVR))' - SET @TokenStepID = '$' + '(ESCAPE_SQUOTE(STEPID))' - SET @TokenDate = '$' + '(ESCAPE_SQUOTE(DATE))' - SET @TokenTime = '$' + '(ESCAPE_SQUOTE(TIME))' - SET @TokenJobName = '$' + '(ESCAPE_SQUOTE(JOBNAME))' - SET @TokenStepName = '$' + '(ESCAPE_SQUOTE(STEPNAME))' - - IF @HostPlatform = 'Windows' - BEGIN - SET @TokenLogDirectory = '$' + '(ESCAPE_SQUOTE(SQLLOGDIR))' - END - - SELECT @BackupDirectory = Value - FROM #Config - WHERE [Name] = 'BackupDirectory' - - SELECT @BackupURL = Value - FROM #Config - WHERE [Name] = 'BackupURL' - - SELECT @CleanupTime = Value - FROM #Config - WHERE [Name] = 'CleanupTime' - - SELECT @OutputFileDirectory = Value - FROM #Config - WHERE [Name] = 'OutputFileDirectory' - - SELECT @LogToTable = Value - FROM #Config - WHERE [Name] = 'LogToTable' - - SELECT @DatabaseName = Value - FROM #Config - WHERE [Name] = 'DatabaseName' - - SELECT @LogDirectory = [path] - FROM sys.dm_os_server_diagnostics_log_configurations - - IF @OutputFileDirectory IS NOT NULL AND RIGHT(@OutputFileDirectory,1) = @DirectorySeparator - BEGIN - SET @OutputFileDirectory = LEFT(@OutputFileDirectory, LEN(@OutputFileDirectory) - 1) - END - - IF @LogDirectory IS NOT NULL AND RIGHT(@LogDirectory,1) = @DirectorySeparator - BEGIN - SET @LogDirectory = LEFT(@LogDirectory, LEN(@LogDirectory) - 1) - END - - SET @JobDescription = 'Source: https://ola.hallengren.com' - SET @JobCategory = 'Database Maintenance' - - IF @AmazonRDS = 0 - BEGIN - SET @JobOwner = SUSER_SNAME(0x01) - END - - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) - VALUES('DatabaseBackup - SYSTEM_DATABASES - FULL', - 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''SYSTEM_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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) - - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) - VALUES('DatabaseBackup - USER_DATABASES - DIFF', - 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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) - - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) - VALUES('DatabaseBackup - USER_DATABASES - FULL', - 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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) - - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) - VALUES('DatabaseBackup - USER_DATABASES - LOG', - 'EXECUTE [dbo].[DatabaseBackup]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + CASE WHEN @BackupURL IS NOT NULL THEN '@URL = N''' + REPLACE(@BackupURL,'''','''''') + '''' ELSE '@Directory = ' + ISNULL('N''' + REPLACE(@BackupDirectory,'''','''''') + '''','NULL') END + ',' + 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) - - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) - VALUES('DatabaseIntegrityCheck - SYSTEM_DATABASES', - 'EXECUTE [dbo].[DatabaseIntegrityCheck]' + CHAR(13) + CHAR(10) + '@Databases = ''SYSTEM_DATABASES'',' + CHAR(13) + CHAR(10) + '@NoInformationalMessages = ''Y'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', - @DatabaseName) - - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) - VALUES('DatabaseIntegrityCheck - USER_DATABASES', - 'EXECUTE [dbo].[DatabaseIntegrityCheck]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + '@NoInformationalMessages = ''Y'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', - @DatabaseName) - - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) - VALUES('IndexOptimize - USER_DATABASES', - 'EXECUTE [dbo].[IndexOptimize]' + CHAR(13) + CHAR(10) + '@Databases = ''USER_DATABASES'',' + CHAR(13) + CHAR(10) + '@LogToTable = ''' + @LogToTable + '''', - @DatabaseName) - - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) - VALUES('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') - - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) - VALUES('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') - - INSERT INTO @Jobs ([Name], CommandTSQL, DatabaseName) - VALUES('CommandLog Cleanup', - 'DELETE FROM [dbo].[CommandLog]' + CHAR(13) + CHAR(10) + 'WHERE StartTime < DATEADD(dd,-30,GETDATE())', - @DatabaseName) - - INSERT INTO @Jobs ([Name], CommandCmdExec) - VALUES('Output File Cleanup', - 'powershell.exe -NoProfile -Command "Get-ChildItem -LiteralPath ''' + REPLACE(COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory),'''','''''') + ''' -Filter ''*_*_*_*.txt'' -File | Where-Object { $_.LastWriteTime.Date -le (Get-Date).Date.AddDays(-30) } | ForEach-Object { Write-Output (''del '' + $_.FullName); Remove-Item -LiteralPath $_.FullName }"') - - IF @AmazonRDS = 1 - BEGIN - UPDATE @Jobs - 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 - SET Selected = 1 - END - ELSE IF @HostPlatform = 'Linux' - BEGIN - UPDATE @Jobs - SET Selected = 1 - WHERE CommandTSQL IS NOT NULL - END - - WHILE EXISTS (SELECT * FROM @Jobs WHERE Completed = 0 AND Selected = 1) - BEGIN - SELECT TOP 1 @CurrentJobID = JobID, - @CurrentJobName = [Name], - @CurrentCommandTSQL = CommandTSQL, - @CurrentCommandCmdExec = CommandCmdExec, - @CurrentDatabaseName = DatabaseName - FROM @Jobs - WHERE Completed = 0 - AND Selected = 1 - ORDER BY JobID ASC - - IF @CurrentCommandTSQL IS NOT NULL - BEGIN - SET @CurrentJobStepSubSystem = 'TSQL' - SET @CurrentJobStepCommand = @CurrentCommandTSQL - SET @CurrentJobStepDatabaseName = @CurrentDatabaseName - END - ELSE IF @CurrentCommandCmdExec IS NOT NULL AND @HostPlatform = 'Windows' - BEGIN - SET @CurrentJobStepSubSystem = 'CMDEXEC' - SET @CurrentJobStepCommand = @CurrentCommandCmdExec - SET @CurrentJobStepDatabaseName = NULL - END - - IF @AmazonRDS = 0 AND SERVERPROPERTY('EngineEdition') <> 8 - BEGIN - SET @CurrentOutputFileName = COALESCE(@OutputFileDirectory,@TokenLogDirectory,@LogDirectory) + @DirectorySeparator + @TokenJobName + '_' + @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 @CurrentJobStepCommand = NULL - SET @CurrentJobStepSubSystem = NULL - SET @CurrentJobStepDatabaseName = NULL - SET @CurrentOutputFileName = NULL - - END - -END -GO - -DECLARE @job_id uniqueidentifier -DECLARE @step_id int -DECLARE @command nvarchar(max) -DECLARE @AmazonRDS bit = CASE WHEN SERVERPROPERTY('EngineEdition') IN (5, 8) THEN 0 WHEN EXISTS (SELECT * FROM sys.databases WHERE [name] = 'rdsadmin') AND SUSER_SNAME(0x01) = 'rdsa' THEN 1 ELSE 0 END - -IF @AmazonRDS = 0 -BEGIN - - DECLARE JobCursor CURSOR LOCAL FAST_FORWARD FOR SELECT job_id, step_id, command FROM msdb.dbo.sysjobsteps WHERE command LIKE '%DatabaseBackup%@CheckSum%' COLLATE SQL_Latin1_General_CP1_CS_AS OR command LIKE '%DatabaseBackup%@ModificationLevel%' OR command LIKE '%DatabaseBackup%@LogSizeSinceLastLogBackup%' OR command LIKE '%DatabaseBackup%@TimeSinceLastLogBackup%' - - OPEN JobCursor - - FETCH JobCursor INTO @job_id, @step_id, @command - - WHILE @@FETCH_STATUS = 0 - BEGIN - SET @command = REPLACE(@command, '@CheckSum', '@Checksum') - SET @command = REPLACE(@command, '@ModificationLevel', '@MinModificationLevel') - SET @command = REPLACE(@command, '@LogSizeSinceLastLogBackup', '@MinLogSizeSinceLastLogBackup') - SET @command = REPLACE(@command, '@TimeSinceLastLogBackup', '@MinTimeSinceLastLogBackup') - - EXECUTE msdb.dbo.sp_update_jobstep @job_id = @job_id, @step_id = @step_id, @command = @command - - FETCH NEXT FROM JobCursor INTO @job_id, @step_id, @command - END - - CLOSE JobCursor - - DEALLOCATE JobCursor -END -GO From 99f7c61fec88bbd5452dae8e3ee2539485de9719 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 5 Aug 2026 00:46:27 +0200 Subject: [PATCH 144/177] Delete header-and-footer/HeaderAzureSQLDatabase.sql --- header-and-footer/HeaderAzureSQLDatabase.sql | 20 -------------------- 1 file changed, 20 deletions(-) delete mode 100644 header-and-footer/HeaderAzureSQLDatabase.sql diff --git a/header-and-footer/HeaderAzureSQLDatabase.sql b/header-and-footer/HeaderAzureSQLDatabase.sql deleted file mode 100644 index b51418f2..00000000 --- a/header-and-footer/HeaderAzureSQLDatabase.sql +++ /dev/null @@ -1,20 +0,0 @@ -/* - -SQL Server Maintenance Solution - Azure SQL Database - -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 - -License: https://ola.hallengren.com/license.html - -GitHub: https://github.com/olahallengren/sql-server-maintenance-solution - -Version: - -You can contact me by e-mail at ola@hallengren.com. - -Ola Hallengren -https://ola.hallengren.com - -*/ - From d0731b65c9d86ec9ee40f9f0d07475a59f70137b Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 5 Aug 2026 01:01:01 +0200 Subject: [PATCH 145/177] Add files via upload --- .github/workflows/check-scripts.yml | 62 +++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/.github/workflows/check-scripts.yml b/.github/workflows/check-scripts.yml index ce90b7b1..b9be946b 100644 --- a/.github/workflows/check-scripts.yml +++ b/.github/workflows/check-scripts.yml @@ -63,3 +63,65 @@ jobs: exit 1 fi echo "All scripts have the same version timestamp: $ALL" + + installers: + runs-on: ubuntu-latest + steps: + - name: Check out the repository + uses: actions/checkout@v5 + + - name: Check that the installation scripts contain the same code as the separate scripts + run: | + python3 - << 'EOF' + import sys + + BOM = b"\xef\xbb\xbf" + + # Which separate scripts each installation script is built from, in order. + INSTALLERS = { + "MaintenanceSolution.sql": [ + "CommandLog.sql", "CommandExecute.sql", "DatabaseBackup.sql", + "DatabaseIntegrityCheck.sql", "IndexOptimize.sql"], + "MaintenanceSolutionAzureSQLDatabase.sql": [ + "CommandLog.sql", "CommandExecute.sql", + "DatabaseIntegrityCheck.sql", "IndexOptimize.sql"], + } + + def read(path): + data = open(path, "rb").read() + return data[len(BOM):] if data.startswith(BOM) else data + + def body(path): + # The separate scripts have one line terminator appended after they have been merged into the installation scripts, so the merged copy is the file without it. + return read(path).rstrip(b"\r\n") + + failures = 0 + for installer, objects in INSTALLERS.items(): + data = read(installer) + print("%s (%d bytes)" % (installer, len(data))) + position = None + for name in objects: + part = body(name) + found = data.find(part) + if found < 0: + print(" FAIL %s: the code is not in the installation script" % name) + failures += 1 + break + if position is not None and found != position: + print(" FAIL %s: starts at byte %d, but the previous script ends at byte %d" + % (name, found, position)) + failures += 1 + break + print(" OK %-28s %8d bytes at byte %d" % (name, len(part), found)) + position = found + len(part) + 2 # one line terminator between the scripts + else: + # The header and the footer are not in the repository, so the bytes before the first script and after the last one are not checked. + print(" (%d bytes before the first script, %d bytes after the last)" + % (data.find(body(objects[0])), len(data) - position)) + print() + + if failures: + print("Rebuild the installation scripts so that every file comes from the same build.") + sys.exit(1) + print("The installation scripts contain the same code as the separate scripts.") + EOF From 7e98634399ac3f1192ffaee84a95486a918bf1b3 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 5 Aug 2026 01:08:38 +0200 Subject: [PATCH 146/177] Update .gitattributes --- .gitattributes | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitattributes b/.gitattributes index 5eddf26f..1f051895 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,4 @@ *.sql linguist-language=TSQL +*.sql -text .github export-ignore .gitattributes export-ignore From 68a46d3d8d620bf072be650acf6d0de8f76650e6 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 5 Aug 2026 01:11:23 +0200 Subject: [PATCH 147/177] Update .gitattributes --- .gitattributes | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.gitattributes b/.gitattributes index 1f051895..1e9fe84c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,3 @@ -*.sql linguist-language=TSQL -*.sql -text +*.sql linguist-language=TSQL -text .github export-ignore .gitattributes export-ignore From a1af9c455675b1ce24d07ae3671a0fbbed3a3f34 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 5 Aug 2026 01:23:06 +0200 Subject: [PATCH 148/177] Add files via upload --- .github/workflows/check-scripts.yml | 44 +++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/.github/workflows/check-scripts.yml b/.github/workflows/check-scripts.yml index b9be946b..b1baf638 100644 --- a/.github/workflows/check-scripts.yml +++ b/.github/workflows/check-scripts.yml @@ -64,6 +64,50 @@ jobs: fi echo "All scripts have the same version timestamp: $ALL" + timestamp: + runs-on: ubuntu-latest + steps: + - name: Check out the repository + uses: actions/checkout@v5 + with: + fetch-depth: 0 # the base commit is needed to read the previous version timestamp + + - name: Check that the version timestamp moves forward + if: github.event_name == 'pull_request' + run: | + set -u + + # Every release is built from scratch and stamped with the time of the build, so the timestamp always moves forward. + # A timestamp that has gone backwards means the scripts were copied from an older build folder. + BASE='${{ github.event.pull_request.base.sha }}' + PATTERN='Version: [0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}' + + OLD=$(git show "$BASE:DatabaseBackup.sql" | grep -m1 -oE "$PATTERN" | sed 's/^Version: //') + NEW=$(grep -m1 -oE "$PATTERN" DatabaseBackup.sql | sed 's/^Version: //') + + if [ -z "$OLD" ] || [ -z "$NEW" ]; then + echo "A version timestamp could not be read from DatabaseBackup.sql." + exit 1 + fi + + if [ "$NEW" = "$OLD" ]; then + if git diff --quiet "$BASE" -- '*.sql'; then + echo "The scripts have not changed. Version timestamp $NEW." + exit 0 + fi + echo "The scripts have changed but the version timestamp is still $NEW." + echo "Every change to the scripts should come from a build." + exit 1 + fi + + if [ "$NEW" \< "$OLD" ]; then + echo "The version timestamp has gone backwards: $OLD -> $NEW." + echo "This usually means the scripts were copied from an older build folder." + exit 1 + fi + + echo "The version timestamp has moved forward: $OLD -> $NEW" + installers: runs-on: ubuntu-latest steps: From 736463b2128a66ca9b09616edab4ee0ae56e100c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 5 Aug 2026 01:53:25 +0200 Subject: [PATCH 149/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 14 +++++++++++++- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 22 +++++++++++++++++----- MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 43 insertions(+), 19 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 28be6d23..13e58c7f 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-04 21:29:03 //-- + --// Version: 2026-08-05 01:52:35 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 2e69e678..4c1b8c8b 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-04 21:29:03 //-- + --// Version: 2026-08-05 01:52:35 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1095,6 +1095,12 @@ BEGIN VALUES('The number of URLs for the parameters @URL and @MirrorURL has to be the same.', 16, 3) END + IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND @Version < 16 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('Backup to S3-compatible storage is not supported in this version of SQL Server.', 16, 4) + END + ---------------------------------------------------------------------------------------------------- IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND NOT (DirectoryPath LIKE 'https://%/%' OR DirectoryPath LIKE 's3://%/%')) @@ -1103,6 +1109,12 @@ BEGIN VALUES('The value for the parameter @MirrorURL is not supported.', 16, 1) END + IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath LIKE 's3://%/%') AND @Version < 16 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('Mirrored backups to S3-compatible storage are not supported in this version of SQL Server.', 16, 2) + END + ---------------------------------------------------------------------------------------------------- --// Get directory separator //-- ---------------------------------------------------------------------------------------------------- diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 20bc8e12..915ea952 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-04 21:29:03 //-- + --// Version: 2026-08-05 01:52:35 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index b392be0e..70002ed2 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-04 21:29:03 //-- + --// Version: 2026-08-05 01:52:35 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 99bfee31..65acccef 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: 2026-08-04 21:29:03 +Version: 2026-08-05 01:52:35 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-04 21:29:03 //-- + --// Version: 2026-08-05 01:52:35 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-04 21:29:03 //-- + --// Version: 2026-08-05 01:52:35 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1494,6 +1494,12 @@ BEGIN VALUES('The number of URLs for the parameters @URL and @MirrorURL has to be the same.', 16, 3) END + IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND @Version < 16 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('Backup to S3-compatible storage is not supported in this version of SQL Server.', 16, 4) + END + ---------------------------------------------------------------------------------------------------- IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND NOT (DirectoryPath LIKE 'https://%/%' OR DirectoryPath LIKE 's3://%/%')) @@ -1502,6 +1508,12 @@ BEGIN VALUES('The value for the parameter @MirrorURL is not supported.', 16, 1) END + IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath LIKE 's3://%/%') AND @Version < 16 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('Mirrored backups to S3-compatible storage are not supported in this version of SQL Server.', 16, 2) + END + ---------------------------------------------------------------------------------------------------- --// Get directory separator //-- ---------------------------------------------------------------------------------------------------- @@ -4987,7 +4999,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-04 21:29:03 //-- + --// Version: 2026-08-05 01:52:35 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7010,7 +7022,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-04 21:29:03 //-- + --// Version: 2026-08-05 01:52:35 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 1a05153e..32334cd6 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-04 21:29:03 +Version: 2026-08-05 01:52:35 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-04 21:29:03 //-- + --// Version: 2026-08-05 01:52:35 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-04 21:29:03 //-- + --// Version: 2026-08-05 01:52:35 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-04 21:29:03 //-- + --// Version: 2026-08-05 01:52:35 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 5747946b..7bbda298 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -f3db9ab926e4d0fa4558a8e0e014029c1dde9c2e4f35e25afa5ea0c610dc9f88 CommandExecute.sql +f2b54b1048f82e3ae30531da987263d1c8ae4e073650e6454e619ef4ec49a2fa CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -56408d97466a94203401880b720cb6247f3f55f3ca3ca445fc3ddd6ae5bdd7b4 DatabaseBackup.sql -9460affbaa6191e58aceddf696a9e5d6b2db80c50869bf2c478deac1b036f426 DatabaseIntegrityCheck.sql -fb4af452182f30854c0bc1f810bb30e61b7eee0c1ab05fe1eeab9855f75bb6a8 IndexOptimize.sql -b986af12349b949772cca5509c156a7ad3bf85e70bc06c5d95e40206b29afd99 MaintenanceSolution.sql -db49c641e781e19de80187b7cad0a900d758dde67f542969ea6cec259f0704c7 MaintenanceSolutionAzureSQLDatabase.sql +ad3719d10892f9918f3e70386196b3ea09f212b65691c9663230f02064346beb DatabaseBackup.sql +bd03d7554af4c53f3943291b47555b95e7bf36ffca6759dd804a45a74fbc11c8 DatabaseIntegrityCheck.sql +3664f55bbd72d9ac8ea41d346e1639e9e4f9fe67952dafcd6e958c847deea09f IndexOptimize.sql +3476ff263aab0f46e0ef724fbee46568bf674b3757114f0ec47298d212ea097d MaintenanceSolution.sql +e3bc304ba1ec2797997d2b618d2c45ab5351af1e108d0221cd10536a8cc37036 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From a82d2a7d68acb3bf155206b439aa57c42e301b68 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 5 Aug 2026 02:08:12 +0200 Subject: [PATCH 150/177] Add files via upload --- .github/workflows/check-scripts.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/check-scripts.yml b/.github/workflows/check-scripts.yml index b1baf638..08ea7ccf 100644 --- a/.github/workflows/check-scripts.yml +++ b/.github/workflows/check-scripts.yml @@ -6,6 +6,9 @@ on: pull_request: branches: - main + push: + branches: + - main # confirms that main itself is consistent after a merge workflow_dispatch: # adds a manual "Run workflow" button, handy for testing jobs: From 90b889f53bfe5373eb43c3131113c91911164041 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 5 Aug 2026 02:20:26 +0200 Subject: [PATCH 151/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 10 +++++++++- MaintenanceSolution.sql | 18 +++++++++++++----- MaintenanceSolutionAzureSQLDatabase.sql | 16 ++++++++++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 43 insertions(+), 19 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 13e58c7f..58467106 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-05 01:52:35 //-- + --// Version: 2026-08-05 02:19:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 4c1b8c8b..d719a2f2 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 01:52:35 //-- + --// Version: 2026-08-05 02:19:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 915ea952..8d532ced 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 01:52:35 //-- + --// Version: 2026-08-05 02:19:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 70002ed2..336ec7b2 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 01:52:35 //-- + --// Version: 2026-08-05 02:19:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -998,6 +998,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @MinNumberOfPages > @MaxNumberOfPages + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxNumberOfPages has to be greater than or equal to the value for @MinNumberOfPages.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 65acccef..074f4505 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: 2026-08-05 01:52:35 +Version: 2026-08-05 02:19:20 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 01:52:35 //-- + --// Version: 2026-08-05 02:19:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 01:52:35 //-- + --// Version: 2026-08-05 02:19:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4999,7 +4999,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 01:52:35 //-- + --// Version: 2026-08-05 02:19:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7022,7 +7022,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 01:52:35 //-- + --// Version: 2026-08-05 02:19:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7964,6 +7964,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @MinNumberOfPages > @MaxNumberOfPages + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxNumberOfPages has to be greater than or equal to the value for @MinNumberOfPages.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 32334cd6..cb23f51b 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-05 01:52:35 +Version: 2026-08-05 02:19:20 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 01:52:35 //-- + --// Version: 2026-08-05 02:19:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 01:52:35 //-- + --// Version: 2026-08-05 02:19:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 01:52:35 //-- + --// Version: 2026-08-05 02:19:20 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3359,6 +3359,14 @@ BEGIN ---------------------------------------------------------------------------------------------------- + IF @MinNumberOfPages > @MaxNumberOfPages + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxNumberOfPages has to be greater than or equal to the value for @MinNumberOfPages.', 16, 1) + END + + ---------------------------------------------------------------------------------------------------- + IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 7bbda298..9d2e1bed 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -f2b54b1048f82e3ae30531da987263d1c8ae4e073650e6454e619ef4ec49a2fa CommandExecute.sql +a2899b828f737522ebcf32a63f133975ea339fdf94923306dc27fc86c75f5f4b CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -ad3719d10892f9918f3e70386196b3ea09f212b65691c9663230f02064346beb DatabaseBackup.sql -bd03d7554af4c53f3943291b47555b95e7bf36ffca6759dd804a45a74fbc11c8 DatabaseIntegrityCheck.sql -3664f55bbd72d9ac8ea41d346e1639e9e4f9fe67952dafcd6e958c847deea09f IndexOptimize.sql -3476ff263aab0f46e0ef724fbee46568bf674b3757114f0ec47298d212ea097d MaintenanceSolution.sql -e3bc304ba1ec2797997d2b618d2c45ab5351af1e108d0221cd10536a8cc37036 MaintenanceSolutionAzureSQLDatabase.sql +73ec157f2fdfcec22feef501e8f1e8504e76524698aac03b2dc728b5fb18795c DatabaseBackup.sql +b03358f1c39b4ffb57cda04b0e8bb52b8cedf98b75899e4749b19e7b1956d1cc DatabaseIntegrityCheck.sql +258cc9baf57f5c0de36b34adeec8b9704108bb8249f02cbea152b69e2d9010cf IndexOptimize.sql +0faab29d5cf680b34766ec36066158df6d0925f03b2038044f0cd2f757f7544c MaintenanceSolution.sql +f772c9836d8a9a0e5e0fac56591ab52b621d4166cd444f1ff5baf78e33007748 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 36f2fa4919a64004240b2ad6a7ba6a4e938233f7 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 5 Aug 2026 21:39:48 +0200 Subject: [PATCH 152/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 40 +++++++++++++-------- MaintenanceSolution.sql | 48 +++++++++++++++---------- MaintenanceSolutionAzureSQLDatabase.sql | 46 +++++++++++++++--------- SHA256SUMS.txt | 12 +++---- 7 files changed, 94 insertions(+), 58 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 58467106..508fbdeb 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-05 02:19:20 //-- + --// Version: 2026-08-05 21:02:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index d719a2f2..3d49ab8e 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 02:19:20 //-- + --// Version: 2026-08-05 21:02:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 8d532ced..0e17e70d 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 02:19:20 //-- + --// Version: 2026-08-05 21:02:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 336ec7b2..83bca345 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 02:19:20 //-- + --// Version: 2026-08-05 21:02:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1909,7 +1909,7 @@ BEGIN + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.IsIncremental AS IsIncremental' ELSE ', NULL AS IsIncremental' END + ', ' + 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' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + + ', ' + CASE WHEN (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ' INNER JOIN #Stats Stats ON Indexes.ObjectID = Stats.ObjectID AND Indexes.IndexID = Stats.StatisticsID' ELSE '' END @@ -1921,10 +1921,14 @@ BEGIN BEGIN SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.object_id = dm_db_partition_stats.object_id AND partitions.index_id = dm_db_partition_stats.index_id AND partitions.partition_number = dm_db_partition_stats.partition_number' END + IF @PartitionLevel = 'N' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) + BEGIN + SET @CurrentCommand += ' INNER JOIN (SELECT object_id, index_id, SUM(in_row_data_page_count) AS in_row_data_page_count FROM sys.dm_db_partition_stats GROUP BY object_id, index_id) dm_db_partition_stats ON Indexes.ObjectID = dm_db_partition_stats.object_id AND Indexes.IndexID = dm_db_partition_stats.index_id' + END SET @CurrentCommand += ' WHERE Objects.ObjectType IN(''U'',''V'')' + ' AND Indexes.IndexType IN(1,2,7)' - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END + + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages @@ -2000,7 +2004,7 @@ BEGIN + ', NULL 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' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + + ', ' + CASE WHEN (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' IF @PartitionLevel = 'Y' @@ -2011,10 +2015,14 @@ BEGIN BEGIN SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.object_id = dm_db_partition_stats.object_id AND partitions.index_id = dm_db_partition_stats.index_id AND partitions.partition_number = dm_db_partition_stats.partition_number' END + IF @PartitionLevel = 'N' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) + BEGIN + SET @CurrentCommand += ' INNER JOIN (SELECT object_id, index_id, SUM(in_row_data_page_count) AS in_row_data_page_count FROM sys.dm_db_partition_stats GROUP BY object_id, index_id) dm_db_partition_stats ON Indexes.ObjectID = dm_db_partition_stats.object_id AND Indexes.IndexID = dm_db_partition_stats.index_id' + END SET @CurrentCommand += ' WHERE Objects.ObjectType = ''U''' + ' AND Indexes.IndexType IN(5,6)' - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END + + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages @@ -2160,6 +2168,7 @@ BEGIN UPDATE @tmpIndexesStatistics SET UpdateStatisticsCompleted = 1 WHERE StatisticsID IS NULL + OR (IndexID IS NOT NULL AND @PartitionLevel = 'Y' AND IsIncremental = 0 AND PartitionNumber <> PartitionCount AND PartitionNumber IS NOT NULL) SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName' + ' FROM sys.objects objects' @@ -2644,12 +2653,15 @@ BEGIN END CATCH END - SELECT @CurrentRowCount = [Rows], - @CurrentModificationCounter = [ModificationCounter] - FROM @IncrementalStatsProperties - WHERE ObjectID = @CurrentObjectID - AND StatisticsID = @CurrentStatisticsID - AND PartitionNumber = @CurrentPartitionNumber + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 + BEGIN + SELECT @CurrentRowCount = [Rows], + @CurrentModificationCounter = [ModificationCounter] + FROM @IncrementalStatsProperties + WHERE ObjectID = @CurrentObjectID + AND StatisticsID = @CurrentStatisticsID + AND PartitionNumber = @CurrentPartitionNumber + END -- Check partition statistics IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentModificationCounter IS NULL @@ -2806,7 +2818,7 @@ BEGIN AND ID = @CurrentIxID -- Update that statistics on remaining partitions are completed where no update is needed - IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentStatisticsID IS NOT NULL + IF @CurrentStatisticsID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) BEGIN UPDATE tmpIndexesStatistics SET UpdateStatisticsCompleted = 1 diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 074f4505..dc7b49dd 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: 2026-08-05 02:19:20 +Version: 2026-08-05 21:02:49 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 02:19:20 //-- + --// Version: 2026-08-05 21:02:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 02:19:20 //-- + --// Version: 2026-08-05 21:02:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4999,7 +4999,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 02:19:20 //-- + --// Version: 2026-08-05 21:02:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7022,7 +7022,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 02:19:20 //-- + --// Version: 2026-08-05 21:02:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8875,7 +8875,7 @@ BEGIN + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.IsIncremental AS IsIncremental' ELSE ', NULL AS IsIncremental' END + ', ' + 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' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + + ', ' + CASE WHEN (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ' INNER JOIN #Stats Stats ON Indexes.ObjectID = Stats.ObjectID AND Indexes.IndexID = Stats.StatisticsID' ELSE '' END @@ -8887,10 +8887,14 @@ BEGIN BEGIN SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.object_id = dm_db_partition_stats.object_id AND partitions.index_id = dm_db_partition_stats.index_id AND partitions.partition_number = dm_db_partition_stats.partition_number' END + IF @PartitionLevel = 'N' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) + BEGIN + SET @CurrentCommand += ' INNER JOIN (SELECT object_id, index_id, SUM(in_row_data_page_count) AS in_row_data_page_count FROM sys.dm_db_partition_stats GROUP BY object_id, index_id) dm_db_partition_stats ON Indexes.ObjectID = dm_db_partition_stats.object_id AND Indexes.IndexID = dm_db_partition_stats.index_id' + END SET @CurrentCommand += ' WHERE Objects.ObjectType IN(''U'',''V'')' + ' AND Indexes.IndexType IN(1,2,7)' - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END + + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages @@ -8966,7 +8970,7 @@ BEGIN + ', NULL 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' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + + ', ' + CASE WHEN (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' IF @PartitionLevel = 'Y' @@ -8977,10 +8981,14 @@ BEGIN BEGIN SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.object_id = dm_db_partition_stats.object_id AND partitions.index_id = dm_db_partition_stats.index_id AND partitions.partition_number = dm_db_partition_stats.partition_number' END + IF @PartitionLevel = 'N' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) + BEGIN + SET @CurrentCommand += ' INNER JOIN (SELECT object_id, index_id, SUM(in_row_data_page_count) AS in_row_data_page_count FROM sys.dm_db_partition_stats GROUP BY object_id, index_id) dm_db_partition_stats ON Indexes.ObjectID = dm_db_partition_stats.object_id AND Indexes.IndexID = dm_db_partition_stats.index_id' + END SET @CurrentCommand += ' WHERE Objects.ObjectType = ''U''' + ' AND Indexes.IndexType IN(5,6)' - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END + + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages @@ -9126,6 +9134,7 @@ BEGIN UPDATE @tmpIndexesStatistics SET UpdateStatisticsCompleted = 1 WHERE StatisticsID IS NULL + OR (IndexID IS NOT NULL AND @PartitionLevel = 'Y' AND IsIncremental = 0 AND PartitionNumber <> PartitionCount AND PartitionNumber IS NOT NULL) SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName' + ' FROM sys.objects objects' @@ -9610,12 +9619,15 @@ BEGIN END CATCH END - SELECT @CurrentRowCount = [Rows], - @CurrentModificationCounter = [ModificationCounter] - FROM @IncrementalStatsProperties - WHERE ObjectID = @CurrentObjectID - AND StatisticsID = @CurrentStatisticsID - AND PartitionNumber = @CurrentPartitionNumber + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 + BEGIN + SELECT @CurrentRowCount = [Rows], + @CurrentModificationCounter = [ModificationCounter] + FROM @IncrementalStatsProperties + WHERE ObjectID = @CurrentObjectID + AND StatisticsID = @CurrentStatisticsID + AND PartitionNumber = @CurrentPartitionNumber + END -- Check partition statistics IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentModificationCounter IS NULL @@ -9772,7 +9784,7 @@ BEGIN AND ID = @CurrentIxID -- Update that statistics on remaining partitions are completed where no update is needed - IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentStatisticsID IS NOT NULL + IF @CurrentStatisticsID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) BEGIN UPDATE tmpIndexesStatistics SET UpdateStatisticsCompleted = 1 diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index cb23f51b..b13138e9 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-05 02:19:20 +Version: 2026-08-05 21:02:49 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 02:19:20 //-- + --// Version: 2026-08-05 21:02:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 02:19:20 //-- + --// Version: 2026-08-05 21:02:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 02:19:20 //-- + --// Version: 2026-08-05 21:02:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4270,7 +4270,7 @@ BEGIN + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.IsIncremental AS IsIncremental' ELSE ', NULL AS IsIncremental' END + ', ' + 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' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + + ', ' + CASE WHEN (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ' INNER JOIN #Stats Stats ON Indexes.ObjectID = Stats.ObjectID AND Indexes.IndexID = Stats.StatisticsID' ELSE '' END @@ -4282,10 +4282,14 @@ BEGIN BEGIN SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.object_id = dm_db_partition_stats.object_id AND partitions.index_id = dm_db_partition_stats.index_id AND partitions.partition_number = dm_db_partition_stats.partition_number' END + IF @PartitionLevel = 'N' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) + BEGIN + SET @CurrentCommand += ' INNER JOIN (SELECT object_id, index_id, SUM(in_row_data_page_count) AS in_row_data_page_count FROM sys.dm_db_partition_stats GROUP BY object_id, index_id) dm_db_partition_stats ON Indexes.ObjectID = dm_db_partition_stats.object_id AND Indexes.IndexID = dm_db_partition_stats.index_id' + END SET @CurrentCommand += ' WHERE Objects.ObjectType IN(''U'',''V'')' + ' AND Indexes.IndexType IN(1,2,7)' - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END + + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages @@ -4361,7 +4365,7 @@ BEGIN + ', NULL 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' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + + ', ' + CASE WHEN (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' IF @PartitionLevel = 'Y' @@ -4372,10 +4376,14 @@ BEGIN BEGIN SET @CurrentCommand += ' INNER JOIN sys.dm_db_partition_stats dm_db_partition_stats ON partitions.object_id = dm_db_partition_stats.object_id AND partitions.index_id = dm_db_partition_stats.index_id AND partitions.partition_number = dm_db_partition_stats.partition_number' END + IF @PartitionLevel = 'N' AND (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) + BEGIN + SET @CurrentCommand += ' INNER JOIN (SELECT object_id, index_id, SUM(in_row_data_page_count) AS in_row_data_page_count FROM sys.dm_db_partition_stats GROUP BY object_id, index_id) dm_db_partition_stats ON Indexes.ObjectID = dm_db_partition_stats.object_id AND Indexes.IndexID = dm_db_partition_stats.index_id' + END SET @CurrentCommand += ' WHERE Objects.ObjectType = ''U''' + ' AND Indexes.IndexType IN(5,6)' - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END - + CASE WHEN @PartitionLevel = 'Y' AND (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END + + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages @@ -4521,6 +4529,7 @@ BEGIN UPDATE @tmpIndexesStatistics SET UpdateStatisticsCompleted = 1 WHERE StatisticsID IS NULL + OR (IndexID IS NOT NULL AND @PartitionLevel = 'Y' AND IsIncremental = 0 AND PartitionNumber <> PartitionCount AND PartitionNumber IS NOT NULL) SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName' + ' FROM sys.objects objects' @@ -5005,12 +5014,15 @@ BEGIN END CATCH END - SELECT @CurrentRowCount = [Rows], - @CurrentModificationCounter = [ModificationCounter] - FROM @IncrementalStatsProperties - WHERE ObjectID = @CurrentObjectID - AND StatisticsID = @CurrentStatisticsID - AND PartitionNumber = @CurrentPartitionNumber + IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 + BEGIN + SELECT @CurrentRowCount = [Rows], + @CurrentModificationCounter = [ModificationCounter] + FROM @IncrementalStatsProperties + WHERE ObjectID = @CurrentObjectID + AND StatisticsID = @CurrentStatisticsID + AND PartitionNumber = @CurrentPartitionNumber + END -- Check partition statistics IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentModificationCounter IS NULL @@ -5167,7 +5179,7 @@ BEGIN AND ID = @CurrentIxID -- Update that statistics on remaining partitions are completed where no update is needed - IF NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) AND @CurrentStatisticsID IS NOT NULL + IF @CurrentStatisticsID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) BEGIN UPDATE tmpIndexesStatistics SET UpdateStatisticsCompleted = 1 diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 9d2e1bed..5e34dd3f 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -a2899b828f737522ebcf32a63f133975ea339fdf94923306dc27fc86c75f5f4b CommandExecute.sql +c8009564e0d09acb47c1414b0fb37ec6922806b839dd122fbf146e8e41d3aa9a CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -73ec157f2fdfcec22feef501e8f1e8504e76524698aac03b2dc728b5fb18795c DatabaseBackup.sql -b03358f1c39b4ffb57cda04b0e8bb52b8cedf98b75899e4749b19e7b1956d1cc DatabaseIntegrityCheck.sql -258cc9baf57f5c0de36b34adeec8b9704108bb8249f02cbea152b69e2d9010cf IndexOptimize.sql -0faab29d5cf680b34766ec36066158df6d0925f03b2038044f0cd2f757f7544c MaintenanceSolution.sql -f772c9836d8a9a0e5e0fac56591ab52b621d4166cd444f1ff5baf78e33007748 MaintenanceSolutionAzureSQLDatabase.sql +d7a3e13a86def129f3b86ceef206216be0c99e2268dc5418bee0e1297bdbfb33 DatabaseBackup.sql +0711269cc16818898174453c621650a501d24639c98a410fa7360e6a4fd53289 DatabaseIntegrityCheck.sql +762c6212940864d58b9458db724ec861b04dcc91c986ed348777f71f972037f5 IndexOptimize.sql +d05b03d06d91554343939cb28d1dcd890779ad029099dbd339a0f016dc5dfaa4 MaintenanceSolution.sql +0ef96156461007c8358e5d2d6a546d3583b54b6e1e249cad97e5c5ae014e7ec8 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 2e079714c6436e199d7b48b625670481f1108858 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 7 Aug 2026 12:42:37 +0200 Subject: [PATCH 153/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 2 +- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 157 +++++++++++++++------- MaintenanceSolution.sql | 165 +++++++++++++++++------- MaintenanceSolutionAzureSQLDatabase.sql | 163 ++++++++++++++++------- SHA256SUMS.txt | 12 +- 7 files changed, 352 insertions(+), 151 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 508fbdeb..6ad60a50 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-05 21:02:49 //-- + --// Version: 2026-08-07 12:41:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 3d49ab8e..be846ee1 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 21:02:49 //-- + --// Version: 2026-08-07 12:41:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 0e17e70d..1de6be02 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 21:02:49 //-- + --// Version: 2026-08-07 12:41:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 83bca345..4306767e 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 21:02:49 //-- + --// Version: 2026-08-07 12:41:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -149,11 +149,11 @@ BEGIN DECLARE @CurrentStatisticsName nvarchar(max) DECLARE @CurrentPartitionID bigint DECLARE @CurrentPartitionNumber int - DECLARE @CurrentPartitionCount int DECLARE @CurrentInRowDataPageCount bigint DECLARE @CurrentAlterIndexCompleted bit DECLARE @CurrentUpdateStatisticsCompleted bit DECLARE @CurrentIsPartition bit + DECLARE @CurrentIsLastPartition bit DECLARE @CurrentIndexExists bit DECLARE @CurrentStatisticsExists bit DECLARE @CurrentIsImageText bit @@ -229,7 +229,8 @@ BEGIN IsIncremental bit, PartitionID bigint, PartitionNumber int, - PartitionCount int, + IsPartition bit, + IsLastPartition bit, InRowDataPageCount bigint, StartPosition int, [Order] int DEFAULT 0, @@ -269,6 +270,7 @@ BEGIN IndexName nvarchar(128) COLLATE DATABASE_DEFAULT, IndexType int, DataSpaceID int, + IsPartitioned bit, AllowPageLocks bit, HasFilter bit, IsImageText bit, @@ -320,6 +322,13 @@ BEGIN StartPosition int, Selected bit) + DECLARE @PhysicalStats TABLE (ObjectID int, + IndexID int, + PartitionNumber int, + FragmentationLevel float, + PageCount bigint, + PRIMARY KEY (ObjectID, IndexID, PartitionNumber)) + DECLARE @IncrementalStatsProperties TABLE (ObjectID int, StatisticsID int, PartitionNumber int, @@ -1811,6 +1820,7 @@ BEGIN + ', indexes.[name] AS IndexName' + ', indexes.[type] AS IndexType' + ', indexes.data_space_id AS DataSpaceID' + + ', CASE WHEN EXISTS (SELECT * FROM sys.partition_schemes partition_schemes WHERE partition_schemes.data_space_id = indexes.data_space_id) THEN 1 ELSE 0 END AS IsPartitioned' + ', indexes.allow_page_locks AS AllowPageLocks' + ', indexes.has_filter AS HasFilter' + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') THEN '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] = indexes.object_id AND types.name IN(''image'',''text'',''ntext'')) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsImageText' @@ -1824,7 +1834,7 @@ BEGIN + ' AND indexes.is_disabled = 0' + ' AND indexes.is_hypothetical = 0' - INSERT INTO #Indexes (ObjectID, IndexID, IndexName, IndexType, DataSpaceID, AllowPageLocks, HasFilter, IsImageText, IsFileStream, IsColumnstoreOrdered, IsComputed, IsTimestamp) + INSERT INTO #Indexes (ObjectID, IndexID, IndexName, IndexType, DataSpaceID, IsPartitioned, AllowPageLocks, HasFilter, IsImageText, IsFileStream, IsColumnstoreOrdered, IsComputed, IsTimestamp) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -1909,6 +1919,7 @@ BEGIN + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.IsIncremental AS IsIncremental' ELSE ', NULL AS IsIncremental' END + ', ' + 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 'Indexes.IsPartitioned AS IsPartition' WHEN @PartitionLevel = 'N' THEN '0 AS IsPartition' END + ', ' + CASE WHEN (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' @@ -1930,7 +1941,7 @@ BEGIN + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, IsPartition, InRowDataPageCount) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages SET @Error = @@ERROR IF @Error <> 0 @@ -1961,12 +1972,13 @@ BEGIN + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON Indexes.DataSpaceID = 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.ObjectID AND indexes2.[index_id] = Indexes.IndexID) THEN 1' + ' WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.filegroups filegroups ON Indexes.DataSpaceID = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND Indexes.ObjectID = indexes2.[object_id] AND Indexes.IndexID = indexes2.index_id) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + ', 0 AS ResumableIndexOperation' + + ', 0 AS IsPartition' + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + ' WHERE Objects.ObjectType = ''U''' + ' AND Indexes.IndexType IN(3,4)' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, IsPartition) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -2004,6 +2016,7 @@ BEGIN + ', NULL 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 'Indexes.IsPartitioned AS IsPartition' WHEN @PartitionLevel = 'N' THEN '0 AS IsPartition' END + ', ' + CASE WHEN (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' @@ -2024,7 +2037,7 @@ BEGIN + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, IsPartition, InRowDataPageCount) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages SET @Error = @@ERROR IF @Error <> 0 @@ -2049,13 +2062,14 @@ BEGIN + ', Stats.[NoRecompute] AS NoRecompute' + ', Stats.IsIncremental AS IsIncremental' + ', NULL AS PartitionNumber' + + ', 0 AS IsPartition' + ' FROM #Stats Stats' + ' INNER JOIN #Objects Objects ON Stats.ObjectID = Objects.ObjectID' + ' WHERE Stats.IsIndex = 0' + ' AND Stats.IsIncremental = 0' + ' AND Objects.IsClusteredIndexDisabled = 0' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber, IsPartition) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -2076,6 +2090,7 @@ BEGIN + ', Stats.[NoRecompute] AS NoRecompute' + ', Stats.IsIncremental AS IsIncremental' + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_number' ELSE 'NULL' END + ' AS PartitionNumber' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN '1' ELSE '0' END + ' AS IsPartition' + ' FROM #Stats Stats' + ' INNER JOIN #Objects Objects ON Stats.ObjectID = Objects.ObjectID' IF @PartitionLevel = 'Y' @@ -2087,7 +2102,7 @@ BEGIN + ' AND Stats.IsIncremental = 1' + ' AND Objects.IsClusteredIndexDisabled = 0' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber, IsPartition) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -2096,21 +2111,21 @@ BEGIN END END - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.ResumableIndexOperation = 1 - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @tmpResumableOperations tmpResumableOperations ON tmpIndexesStatistics.ObjectID = tmpResumableOperations.ObjectID AND tmpIndexesStatistics.IndexID = tmpResumableOperations.IndexID AND (tmpIndexesStatistics.PartitionNumber = tmpResumableOperations.PartitionNumber OR tmpResumableOperations.PartitionNumber IS NULL) - OPTION (RECOMPILE) - IF @PartitionLevel = 'Y' BEGIN UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.PartitionCount = PartitionCounts.PartitionCount + SET tmpIndexesStatistics.IsLastPartition = CASE WHEN tmpIndexesStatistics.PartitionNumber = LastPartitionNumbers.LastPartitionNumber THEN 1 ELSE 0 END FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN (SELECT ObjectID, IndexID, COUNT(*) AS PartitionCount FROM @tmpIndexesStatistics WHERE IndexID IS NOT NULL GROUP BY ObjectID, IndexID) PartitionCounts ON tmpIndexesStatistics.ObjectID = PartitionCounts.ObjectID AND tmpIndexesStatistics.IndexID = PartitionCounts.IndexID + INNER JOIN (SELECT ObjectID, IndexID, MAX(PartitionNumber) AS LastPartitionNumber FROM @tmpIndexesStatistics WHERE IndexID IS NOT NULL AND PartitionNumber IS NOT NULL GROUP BY ObjectID, IndexID) LastPartitionNumbers ON tmpIndexesStatistics.ObjectID = LastPartitionNumbers.ObjectID AND tmpIndexesStatistics.IndexID = LastPartitionNumbers.IndexID OPTION (RECOMPILE) END + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.ResumableIndexOperation = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @tmpResumableOperations tmpResumableOperations ON tmpIndexesStatistics.ObjectID = tmpResumableOperations.ObjectID AND tmpIndexesStatistics.IndexID = tmpResumableOperations.IndexID AND (tmpIndexesStatistics.PartitionNumber = tmpResumableOperations.PartitionNumber OR tmpResumableOperations.PartitionNumber IS NULL) + OPTION (RECOMPILE) + IF @Indexes IS NULL BEGIN UPDATE tmpIndexesStatistics @@ -2168,7 +2183,7 @@ BEGIN UPDATE @tmpIndexesStatistics SET UpdateStatisticsCompleted = 1 WHERE StatisticsID IS NULL - OR (IndexID IS NOT NULL AND @PartitionLevel = 'Y' AND IsIncremental = 0 AND PartitionNumber <> PartitionCount AND PartitionNumber IS NOT NULL) + OR (IndexID IS NOT NULL AND @PartitionLevel = 'Y' AND IsIncremental = 0 AND IsLastPartition = 0) SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName' + ' FROM sys.objects objects' @@ -2265,7 +2280,8 @@ BEGIN @CurrentIsIncremental = IsIncremental, @CurrentPartitionID = PartitionID, @CurrentPartitionNumber = PartitionNumber, - @CurrentPartitionCount = PartitionCount, + @CurrentIsPartition = IsPartition, + @CurrentIsLastPartition = IsLastPartition, @CurrentInRowDataPageCount = InRowDataPageCount, @CurrentAlterIndexCompleted = AlterIndexCompleted, @CurrentUpdateStatisticsCompleted = UpdateStatisticsCompleted @@ -2279,9 +2295,6 @@ 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 - IF @CurrentAlterIndexCompleted = 0 AND @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) AND @CurrentOnReadOnlyFileGroup = 0 BEGIN -- Does the index exist? @@ -2318,35 +2331,63 @@ BEGIN -- Is the index fragmented? IF EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) OR @MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL BEGIN - SET @CurrentCommand = '' + IF NOT EXISTS (SELECT * FROM @PhysicalStats WHERE ObjectID = @CurrentObjectID AND IndexID = @CurrentIndexID) + BEGIN + SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + IF @CurrentIndexType IN(5, 6) + BEGIN + SET @CurrentCommand += 'SELECT object_id, index_id, partition_number, MAX(avg_fragmentation_in_percent), SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, NULL, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0 GROUP BY object_id, index_id, partition_number' + END + ELSE + BEGIN + SET @CurrentCommand += 'SELECT object_id, index_id, partition_number, avg_fragmentation_in_percent, page_count FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, NULL, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + END + + BEGIN TRY + INSERT INTO @PhysicalStats (ObjectID, IndexID, PartitionNumber, FragmentationLevel, PageCount) + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + + UPDATE @tmpIndexesStatistics + SET AlterIndexCompleted = 1 + WHERE ObjectID = @CurrentObjectID + AND IndexID = @CurrentIndexID + AND AlterIndexCompleted = 0 + + GOTO NoAction + END CATCH + END IF @CurrentPartitionNumber IS NULL BEGIN - 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, NULL, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + SELECT @CurrentFragmentationLevel = MAX(FragmentationLevel), + @CurrentPageCount = SUM(PageCount) + FROM @PhysicalStats + WHERE ObjectID = @CurrentObjectID + AND IndexID = @CurrentIndexID END ELSE BEGIN - SET @CurrentCommand += 'SELECT @ParamFragmentationLevel = avg_fragmentation_in_percent, @ParamPageCount = 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' + SELECT @CurrentFragmentationLevel = FragmentationLevel, + @CurrentPageCount = PageCount + FROM @PhysicalStats + WHERE ObjectID = @CurrentObjectID + AND IndexID = @CurrentIndexID + AND PartitionNumber = @CurrentPartitionNumber END - - BEGIN TRY - 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(max)) + ', ' + 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 - SET @ReturnCode = ERROR_NUMBER() - END - - GOTO NoAction - END CATCH END -- Select fragmentation group @@ -2563,7 +2604,7 @@ BEGIN IF @CurrentUpdateStatisticsCompleted = 0 AND @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) - AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) + AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentIsLastPartition = 1 OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) BEGIN -- Does the statistics exist? SET @CurrentCommand = '' @@ -2649,6 +2690,12 @@ BEGIN SET @ReturnCode = ERROR_NUMBER() END + UPDATE @tmpIndexesStatistics + SET UpdateStatisticsCompleted = 1 + WHERE ObjectID = @CurrentObjectID + AND StatisticsID = @CurrentStatisticsID + AND UpdateStatisticsCompleted = 0 + GOTO NoAction END CATCH END @@ -2817,6 +2864,25 @@ BEGIN AND [Order] = @CurrentIxOrder AND ID = @CurrentIxID + -- Update that index operations on remaining partitions are completed where no action is needed + IF @CurrentIndexID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsPartition = 1 AND (SELECT COUNT(DISTINCT FragmentationGroup) FROM @ActionsPreferred) < 3 + BEGIN + UPDATE tmpIndexesStatistics + SET AlterIndexCompleted = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @PhysicalStats PhysicalStats ON tmpIndexesStatistics.ObjectID = PhysicalStats.ObjectID AND tmpIndexesStatistics.IndexID = PhysicalStats.IndexID AND tmpIndexesStatistics.PartitionNumber = PhysicalStats.PartitionNumber + WHERE tmpIndexesStatistics.ObjectID = @CurrentObjectID + AND tmpIndexesStatistics.IndexID = @CurrentIndexID + AND tmpIndexesStatistics.AlterIndexCompleted = 0 + AND NOT EXISTS (SELECT * + FROM @ActionsPreferred ActionsPreferred + WHERE ActionsPreferred.FragmentationGroup = CASE + WHEN PhysicalStats.FragmentationLevel >= @FragmentationLevel2 THEN 'High' + WHEN PhysicalStats.FragmentationLevel >= @FragmentationLevel1 AND PhysicalStats.FragmentationLevel < @FragmentationLevel2 THEN 'Medium' + WHEN PhysicalStats.FragmentationLevel < @FragmentationLevel1 THEN 'Low' + END) + END + -- Update that statistics on remaining partitions are completed where no update is needed IF @CurrentStatisticsID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) BEGIN @@ -2857,11 +2923,11 @@ BEGIN SET @CurrentStatisticsName = NULL SET @CurrentPartitionID = NULL SET @CurrentPartitionNumber = NULL - SET @CurrentPartitionCount = NULL SET @CurrentInRowDataPageCount = NULL SET @CurrentAlterIndexCompleted = NULL SET @CurrentUpdateStatisticsCompleted = NULL SET @CurrentIsPartition = NULL + SET @CurrentIsLastPartition = NULL SET @CurrentIndexExists = NULL SET @CurrentStatisticsExists = NULL SET @CurrentIsImageText = NULL @@ -2957,6 +3023,7 @@ BEGIN TRUNCATE TABLE #ExistingObjects TRUNCATE TABLE #ExistingIndexes DELETE FROM @tmpResumableOperations + DELETE FROM @PhysicalStats DELETE FROM @IncrementalStatsProperties END -- End of database loop diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index dc7b49dd..277d3791 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: 2026-08-05 21:02:49 +Version: 2026-08-07 12:41:25 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 21:02:49 //-- + --// Version: 2026-08-07 12:41:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 21:02:49 //-- + --// Version: 2026-08-07 12:41:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4999,7 +4999,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 21:02:49 //-- + --// Version: 2026-08-07 12:41:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7022,7 +7022,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 21:02:49 //-- + --// Version: 2026-08-07 12:41:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7115,11 +7115,11 @@ BEGIN DECLARE @CurrentStatisticsName nvarchar(max) DECLARE @CurrentPartitionID bigint DECLARE @CurrentPartitionNumber int - DECLARE @CurrentPartitionCount int DECLARE @CurrentInRowDataPageCount bigint DECLARE @CurrentAlterIndexCompleted bit DECLARE @CurrentUpdateStatisticsCompleted bit DECLARE @CurrentIsPartition bit + DECLARE @CurrentIsLastPartition bit DECLARE @CurrentIndexExists bit DECLARE @CurrentStatisticsExists bit DECLARE @CurrentIsImageText bit @@ -7195,7 +7195,8 @@ BEGIN IsIncremental bit, PartitionID bigint, PartitionNumber int, - PartitionCount int, + IsPartition bit, + IsLastPartition bit, InRowDataPageCount bigint, StartPosition int, [Order] int DEFAULT 0, @@ -7235,6 +7236,7 @@ BEGIN IndexName nvarchar(128) COLLATE DATABASE_DEFAULT, IndexType int, DataSpaceID int, + IsPartitioned bit, AllowPageLocks bit, HasFilter bit, IsImageText bit, @@ -7286,6 +7288,13 @@ BEGIN StartPosition int, Selected bit) + DECLARE @PhysicalStats TABLE (ObjectID int, + IndexID int, + PartitionNumber int, + FragmentationLevel float, + PageCount bigint, + PRIMARY KEY (ObjectID, IndexID, PartitionNumber)) + DECLARE @IncrementalStatsProperties TABLE (ObjectID int, StatisticsID int, PartitionNumber int, @@ -8777,6 +8786,7 @@ BEGIN + ', indexes.[name] AS IndexName' + ', indexes.[type] AS IndexType' + ', indexes.data_space_id AS DataSpaceID' + + ', CASE WHEN EXISTS (SELECT * FROM sys.partition_schemes partition_schemes WHERE partition_schemes.data_space_id = indexes.data_space_id) THEN 1 ELSE 0 END AS IsPartitioned' + ', indexes.allow_page_locks AS AllowPageLocks' + ', indexes.has_filter AS HasFilter' + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') THEN '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] = indexes.object_id AND types.name IN(''image'',''text'',''ntext'')) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsImageText' @@ -8790,7 +8800,7 @@ BEGIN + ' AND indexes.is_disabled = 0' + ' AND indexes.is_hypothetical = 0' - INSERT INTO #Indexes (ObjectID, IndexID, IndexName, IndexType, DataSpaceID, AllowPageLocks, HasFilter, IsImageText, IsFileStream, IsColumnstoreOrdered, IsComputed, IsTimestamp) + INSERT INTO #Indexes (ObjectID, IndexID, IndexName, IndexType, DataSpaceID, IsPartitioned, AllowPageLocks, HasFilter, IsImageText, IsFileStream, IsColumnstoreOrdered, IsComputed, IsTimestamp) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -8875,6 +8885,7 @@ BEGIN + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.IsIncremental AS IsIncremental' ELSE ', NULL AS IsIncremental' END + ', ' + 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 'Indexes.IsPartitioned AS IsPartition' WHEN @PartitionLevel = 'N' THEN '0 AS IsPartition' END + ', ' + CASE WHEN (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' @@ -8896,7 +8907,7 @@ BEGIN + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, IsPartition, InRowDataPageCount) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages SET @Error = @@ERROR IF @Error <> 0 @@ -8927,12 +8938,13 @@ BEGIN + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON Indexes.DataSpaceID = 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.ObjectID AND indexes2.[index_id] = Indexes.IndexID) THEN 1' + ' WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.filegroups filegroups ON Indexes.DataSpaceID = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND Indexes.ObjectID = indexes2.[object_id] AND Indexes.IndexID = indexes2.index_id) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + ', 0 AS ResumableIndexOperation' + + ', 0 AS IsPartition' + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + ' WHERE Objects.ObjectType = ''U''' + ' AND Indexes.IndexType IN(3,4)' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, IsPartition) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -8970,6 +8982,7 @@ BEGIN + ', NULL 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 'Indexes.IsPartitioned AS IsPartition' WHEN @PartitionLevel = 'N' THEN '0 AS IsPartition' END + ', ' + CASE WHEN (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' @@ -8990,7 +9003,7 @@ BEGIN + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, IsPartition, InRowDataPageCount) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages SET @Error = @@ERROR IF @Error <> 0 @@ -9015,13 +9028,14 @@ BEGIN + ', Stats.[NoRecompute] AS NoRecompute' + ', Stats.IsIncremental AS IsIncremental' + ', NULL AS PartitionNumber' + + ', 0 AS IsPartition' + ' FROM #Stats Stats' + ' INNER JOIN #Objects Objects ON Stats.ObjectID = Objects.ObjectID' + ' WHERE Stats.IsIndex = 0' + ' AND Stats.IsIncremental = 0' + ' AND Objects.IsClusteredIndexDisabled = 0' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber, IsPartition) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -9042,6 +9056,7 @@ BEGIN + ', Stats.[NoRecompute] AS NoRecompute' + ', Stats.IsIncremental AS IsIncremental' + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_number' ELSE 'NULL' END + ' AS PartitionNumber' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN '1' ELSE '0' END + ' AS IsPartition' + ' FROM #Stats Stats' + ' INNER JOIN #Objects Objects ON Stats.ObjectID = Objects.ObjectID' IF @PartitionLevel = 'Y' @@ -9053,7 +9068,7 @@ BEGIN + ' AND Stats.IsIncremental = 1' + ' AND Objects.IsClusteredIndexDisabled = 0' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber, IsPartition) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -9062,21 +9077,21 @@ BEGIN END END - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.ResumableIndexOperation = 1 - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @tmpResumableOperations tmpResumableOperations ON tmpIndexesStatistics.ObjectID = tmpResumableOperations.ObjectID AND tmpIndexesStatistics.IndexID = tmpResumableOperations.IndexID AND (tmpIndexesStatistics.PartitionNumber = tmpResumableOperations.PartitionNumber OR tmpResumableOperations.PartitionNumber IS NULL) - OPTION (RECOMPILE) - IF @PartitionLevel = 'Y' BEGIN UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.PartitionCount = PartitionCounts.PartitionCount + SET tmpIndexesStatistics.IsLastPartition = CASE WHEN tmpIndexesStatistics.PartitionNumber = LastPartitionNumbers.LastPartitionNumber THEN 1 ELSE 0 END FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN (SELECT ObjectID, IndexID, COUNT(*) AS PartitionCount FROM @tmpIndexesStatistics WHERE IndexID IS NOT NULL GROUP BY ObjectID, IndexID) PartitionCounts ON tmpIndexesStatistics.ObjectID = PartitionCounts.ObjectID AND tmpIndexesStatistics.IndexID = PartitionCounts.IndexID + INNER JOIN (SELECT ObjectID, IndexID, MAX(PartitionNumber) AS LastPartitionNumber FROM @tmpIndexesStatistics WHERE IndexID IS NOT NULL AND PartitionNumber IS NOT NULL GROUP BY ObjectID, IndexID) LastPartitionNumbers ON tmpIndexesStatistics.ObjectID = LastPartitionNumbers.ObjectID AND tmpIndexesStatistics.IndexID = LastPartitionNumbers.IndexID OPTION (RECOMPILE) END + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.ResumableIndexOperation = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @tmpResumableOperations tmpResumableOperations ON tmpIndexesStatistics.ObjectID = tmpResumableOperations.ObjectID AND tmpIndexesStatistics.IndexID = tmpResumableOperations.IndexID AND (tmpIndexesStatistics.PartitionNumber = tmpResumableOperations.PartitionNumber OR tmpResumableOperations.PartitionNumber IS NULL) + OPTION (RECOMPILE) + IF @Indexes IS NULL BEGIN UPDATE tmpIndexesStatistics @@ -9134,7 +9149,7 @@ BEGIN UPDATE @tmpIndexesStatistics SET UpdateStatisticsCompleted = 1 WHERE StatisticsID IS NULL - OR (IndexID IS NOT NULL AND @PartitionLevel = 'Y' AND IsIncremental = 0 AND PartitionNumber <> PartitionCount AND PartitionNumber IS NOT NULL) + OR (IndexID IS NOT NULL AND @PartitionLevel = 'Y' AND IsIncremental = 0 AND IsLastPartition = 0) SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName' + ' FROM sys.objects objects' @@ -9231,7 +9246,8 @@ BEGIN @CurrentIsIncremental = IsIncremental, @CurrentPartitionID = PartitionID, @CurrentPartitionNumber = PartitionNumber, - @CurrentPartitionCount = PartitionCount, + @CurrentIsPartition = IsPartition, + @CurrentIsLastPartition = IsLastPartition, @CurrentInRowDataPageCount = InRowDataPageCount, @CurrentAlterIndexCompleted = AlterIndexCompleted, @CurrentUpdateStatisticsCompleted = UpdateStatisticsCompleted @@ -9245,9 +9261,6 @@ 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 - IF @CurrentAlterIndexCompleted = 0 AND @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) AND @CurrentOnReadOnlyFileGroup = 0 BEGIN -- Does the index exist? @@ -9284,35 +9297,63 @@ BEGIN -- Is the index fragmented? IF EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) OR @MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL BEGIN - SET @CurrentCommand = '' + IF NOT EXISTS (SELECT * FROM @PhysicalStats WHERE ObjectID = @CurrentObjectID AND IndexID = @CurrentIndexID) + BEGIN + SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + IF @CurrentIndexType IN(5, 6) + BEGIN + SET @CurrentCommand += 'SELECT object_id, index_id, partition_number, MAX(avg_fragmentation_in_percent), SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, NULL, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0 GROUP BY object_id, index_id, partition_number' + END + ELSE + BEGIN + SET @CurrentCommand += 'SELECT object_id, index_id, partition_number, avg_fragmentation_in_percent, page_count FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, NULL, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + END + + BEGIN TRY + INSERT INTO @PhysicalStats (ObjectID, IndexID, PartitionNumber, FragmentationLevel, PageCount) + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + + UPDATE @tmpIndexesStatistics + SET AlterIndexCompleted = 1 + WHERE ObjectID = @CurrentObjectID + AND IndexID = @CurrentIndexID + AND AlterIndexCompleted = 0 + + GOTO NoAction + END CATCH + END IF @CurrentPartitionNumber IS NULL BEGIN - 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, NULL, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + SELECT @CurrentFragmentationLevel = MAX(FragmentationLevel), + @CurrentPageCount = SUM(PageCount) + FROM @PhysicalStats + WHERE ObjectID = @CurrentObjectID + AND IndexID = @CurrentIndexID END ELSE BEGIN - SET @CurrentCommand += 'SELECT @ParamFragmentationLevel = avg_fragmentation_in_percent, @ParamPageCount = 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' + SELECT @CurrentFragmentationLevel = FragmentationLevel, + @CurrentPageCount = PageCount + FROM @PhysicalStats + WHERE ObjectID = @CurrentObjectID + AND IndexID = @CurrentIndexID + AND PartitionNumber = @CurrentPartitionNumber END - - BEGIN TRY - 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(max)) + ', ' + 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 - SET @ReturnCode = ERROR_NUMBER() - END - - GOTO NoAction - END CATCH END -- Select fragmentation group @@ -9529,7 +9570,7 @@ BEGIN IF @CurrentUpdateStatisticsCompleted = 0 AND @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) - AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) + AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentIsLastPartition = 1 OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) BEGIN -- Does the statistics exist? SET @CurrentCommand = '' @@ -9615,6 +9656,12 @@ BEGIN SET @ReturnCode = ERROR_NUMBER() END + UPDATE @tmpIndexesStatistics + SET UpdateStatisticsCompleted = 1 + WHERE ObjectID = @CurrentObjectID + AND StatisticsID = @CurrentStatisticsID + AND UpdateStatisticsCompleted = 0 + GOTO NoAction END CATCH END @@ -9783,6 +9830,25 @@ BEGIN AND [Order] = @CurrentIxOrder AND ID = @CurrentIxID + -- Update that index operations on remaining partitions are completed where no action is needed + IF @CurrentIndexID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsPartition = 1 AND (SELECT COUNT(DISTINCT FragmentationGroup) FROM @ActionsPreferred) < 3 + BEGIN + UPDATE tmpIndexesStatistics + SET AlterIndexCompleted = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @PhysicalStats PhysicalStats ON tmpIndexesStatistics.ObjectID = PhysicalStats.ObjectID AND tmpIndexesStatistics.IndexID = PhysicalStats.IndexID AND tmpIndexesStatistics.PartitionNumber = PhysicalStats.PartitionNumber + WHERE tmpIndexesStatistics.ObjectID = @CurrentObjectID + AND tmpIndexesStatistics.IndexID = @CurrentIndexID + AND tmpIndexesStatistics.AlterIndexCompleted = 0 + AND NOT EXISTS (SELECT * + FROM @ActionsPreferred ActionsPreferred + WHERE ActionsPreferred.FragmentationGroup = CASE + WHEN PhysicalStats.FragmentationLevel >= @FragmentationLevel2 THEN 'High' + WHEN PhysicalStats.FragmentationLevel >= @FragmentationLevel1 AND PhysicalStats.FragmentationLevel < @FragmentationLevel2 THEN 'Medium' + WHEN PhysicalStats.FragmentationLevel < @FragmentationLevel1 THEN 'Low' + END) + END + -- Update that statistics on remaining partitions are completed where no update is needed IF @CurrentStatisticsID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) BEGIN @@ -9823,11 +9889,11 @@ BEGIN SET @CurrentStatisticsName = NULL SET @CurrentPartitionID = NULL SET @CurrentPartitionNumber = NULL - SET @CurrentPartitionCount = NULL SET @CurrentInRowDataPageCount = NULL SET @CurrentAlterIndexCompleted = NULL SET @CurrentUpdateStatisticsCompleted = NULL SET @CurrentIsPartition = NULL + SET @CurrentIsLastPartition = NULL SET @CurrentIndexExists = NULL SET @CurrentStatisticsExists = NULL SET @CurrentIsImageText = NULL @@ -9923,6 +9989,7 @@ BEGIN TRUNCATE TABLE #ExistingObjects TRUNCATE TABLE #ExistingIndexes DELETE FROM @tmpResumableOperations + DELETE FROM @PhysicalStats DELETE FROM @IncrementalStatsProperties END -- End of database loop diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index b13138e9..5047aca7 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-05 21:02:49 +Version: 2026-08-07 12:41:25 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 21:02:49 //-- + --// Version: 2026-08-07 12:41:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 21:02:49 //-- + --// Version: 2026-08-07 12:41:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-05 21:02:49 //-- + --// Version: 2026-08-07 12:41:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2510,11 +2510,11 @@ BEGIN DECLARE @CurrentStatisticsName nvarchar(max) DECLARE @CurrentPartitionID bigint DECLARE @CurrentPartitionNumber int - DECLARE @CurrentPartitionCount int DECLARE @CurrentInRowDataPageCount bigint DECLARE @CurrentAlterIndexCompleted bit DECLARE @CurrentUpdateStatisticsCompleted bit DECLARE @CurrentIsPartition bit + DECLARE @CurrentIsLastPartition bit DECLARE @CurrentIndexExists bit DECLARE @CurrentStatisticsExists bit DECLARE @CurrentIsImageText bit @@ -2590,7 +2590,8 @@ BEGIN IsIncremental bit, PartitionID bigint, PartitionNumber int, - PartitionCount int, + IsPartition bit, + IsLastPartition bit, InRowDataPageCount bigint, StartPosition int, [Order] int DEFAULT 0, @@ -2630,6 +2631,7 @@ BEGIN IndexName nvarchar(128) COLLATE DATABASE_DEFAULT, IndexType int, DataSpaceID int, + IsPartitioned bit, AllowPageLocks bit, HasFilter bit, IsImageText bit, @@ -2681,6 +2683,13 @@ BEGIN StartPosition int, Selected bit) + DECLARE @PhysicalStats TABLE (ObjectID int, + IndexID int, + PartitionNumber int, + FragmentationLevel float, + PageCount bigint, + PRIMARY KEY (ObjectID, IndexID, PartitionNumber)) + DECLARE @IncrementalStatsProperties TABLE (ObjectID int, StatisticsID int, PartitionNumber int, @@ -4172,6 +4181,7 @@ BEGIN + ', indexes.[name] AS IndexName' + ', indexes.[type] AS IndexType' + ', indexes.data_space_id AS DataSpaceID' + + ', CASE WHEN EXISTS (SELECT * FROM sys.partition_schemes partition_schemes WHERE partition_schemes.data_space_id = indexes.data_space_id) THEN 1 ELSE 0 END AS IsPartitioned' + ', indexes.allow_page_locks AS AllowPageLocks' + ', indexes.has_filter AS HasFilter' + ', ' + CASE WHEN @EngineEdition IN (3, 5, 8) AND EXISTS(SELECT * FROM @ActionsPreferred WHERE [Action] = 'INDEX_REBUILD_ONLINE') THEN '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] = indexes.object_id AND types.name IN(''image'',''text'',''ntext'')) THEN 1 ELSE 0 END' ELSE 'NULL' END + ' AS IsImageText' @@ -4185,7 +4195,7 @@ BEGIN + ' AND indexes.is_disabled = 0' + ' AND indexes.is_hypothetical = 0' - INSERT INTO #Indexes (ObjectID, IndexID, IndexName, IndexType, DataSpaceID, AllowPageLocks, HasFilter, IsImageText, IsFileStream, IsColumnstoreOrdered, IsComputed, IsTimestamp) + INSERT INTO #Indexes (ObjectID, IndexID, IndexName, IndexType, DataSpaceID, IsPartitioned, AllowPageLocks, HasFilter, IsImageText, IsFileStream, IsColumnstoreOrdered, IsComputed, IsTimestamp) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -4270,6 +4280,7 @@ BEGIN + CASE WHEN @UpdateStatistics IN('ALL','INDEX') THEN ', Stats.IsIncremental AS IsIncremental' ELSE ', NULL AS IsIncremental' END + ', ' + 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 'Indexes.IsPartitioned AS IsPartition' WHEN @PartitionLevel = 'N' THEN '0 AS IsPartition' END + ', ' + CASE WHEN (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' @@ -4291,7 +4302,7 @@ BEGIN + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, IsPartition, InRowDataPageCount) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages SET @Error = @@ERROR IF @Error <> 0 @@ -4322,12 +4333,13 @@ BEGIN + CASE WHEN @CurrentDatabaseHasReadOnlyFileGroup = 1 THEN ', CASE WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.destination_data_spaces destination_data_spaces ON Indexes.DataSpaceID = 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.ObjectID AND indexes2.[index_id] = Indexes.IndexID) THEN 1' + ' WHEN EXISTS (SELECT * FROM sys.indexes indexes2 INNER JOIN sys.filegroups filegroups ON Indexes.DataSpaceID = filegroups.data_space_id WHERE filegroups.is_read_only = 1 AND Indexes.ObjectID = indexes2.[object_id] AND Indexes.IndexID = indexes2.index_id) THEN 1 ELSE 0 END AS OnReadOnlyFileGroup' ELSE ', 0 AS OnReadOnlyFileGroup' END + ', 0 AS ResumableIndexOperation' + + ', 0 AS IsPartition' + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' + ' WHERE Objects.ObjectType = ''U''' + ' AND Indexes.IndexType IN(3,4)' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, IsPartition) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -4365,6 +4377,7 @@ BEGIN + ', NULL 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 'Indexes.IsPartitioned AS IsPartition' WHEN @PartitionLevel = 'N' THEN '0 AS IsPartition' END + ', ' + CASE WHEN (@MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL) THEN 'dm_db_partition_stats.in_row_data_page_count AS InRowDataPageCount' ELSE 'NULL AS InRowDataPageCount' END + ' FROM #Indexes Indexes' + ' INNER JOIN #Objects Objects ON Indexes.ObjectID = Objects.ObjectID' @@ -4385,7 +4398,7 @@ BEGIN + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MinNumberOfPages > 0 THEN ' AND dm_db_partition_stats.in_row_data_page_count >= @ParamMinNumberOfPages' ELSE '' END + CASE WHEN (@UpdateStatistics = 'COLUMNS' OR @UpdateStatistics IS NULL) AND @MaxNumberOfPages IS NOT NULL THEN ' AND dm_db_partition_stats.in_row_data_page_count <= @ParamMaxNumberOfPages' ELSE '' END - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, InRowDataPageCount) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, IndexID, IndexName, IndexType, AllowPageLocks, HasFilter, IsImageText, IsFileStream, HasClusteredColumnstore, IsColumnstoreOrdered, IsComputed, IsClusteredIndexComputed, IsTimestamp, OnReadOnlyFileGroup, ResumableIndexOperation, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionID, PartitionNumber, IsPartition, InRowDataPageCount) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand, @params = N'@ParamMinNumberOfPages int, @ParamMaxNumberOfPages int', @ParamMinNumberOfPages = @MinNumberOfPages, @ParamMaxNumberOfPages = @MaxNumberOfPages SET @Error = @@ERROR IF @Error <> 0 @@ -4410,13 +4423,14 @@ BEGIN + ', Stats.[NoRecompute] AS NoRecompute' + ', Stats.IsIncremental AS IsIncremental' + ', NULL AS PartitionNumber' + + ', 0 AS IsPartition' + ' FROM #Stats Stats' + ' INNER JOIN #Objects Objects ON Stats.ObjectID = Objects.ObjectID' + ' WHERE Stats.IsIndex = 0' + ' AND Stats.IsIncremental = 0' + ' AND Objects.IsClusteredIndexDisabled = 0' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber, IsPartition) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -4437,6 +4451,7 @@ BEGIN + ', Stats.[NoRecompute] AS NoRecompute' + ', Stats.IsIncremental AS IsIncremental' + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN 'partitions.partition_number' ELSE 'NULL' END + ' AS PartitionNumber' + + ', ' + CASE WHEN @PartitionLevel = 'Y' THEN '1' ELSE '0' END + ' AS IsPartition' + ' FROM #Stats Stats' + ' INNER JOIN #Objects Objects ON Stats.ObjectID = Objects.ObjectID' IF @PartitionLevel = 'Y' @@ -4448,7 +4463,7 @@ BEGIN + ' AND Stats.IsIncremental = 1' + ' AND Objects.IsClusteredIndexDisabled = 0' - INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber) + INSERT INTO @tmpIndexesStatistics (SchemaID, SchemaName, ObjectID, ObjectName, ObjectType, IsMemoryOptimized, StatisticsID, StatisticsName, [NoRecompute], IsIncremental, PartitionNumber, IsPartition) EXECUTE @CurrentDatabase_sp_executesql @stmt = @CurrentCommand SET @Error = @@ERROR IF @Error <> 0 @@ -4457,21 +4472,21 @@ BEGIN END END - UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.ResumableIndexOperation = 1 - FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN @tmpResumableOperations tmpResumableOperations ON tmpIndexesStatistics.ObjectID = tmpResumableOperations.ObjectID AND tmpIndexesStatistics.IndexID = tmpResumableOperations.IndexID AND (tmpIndexesStatistics.PartitionNumber = tmpResumableOperations.PartitionNumber OR tmpResumableOperations.PartitionNumber IS NULL) - OPTION (RECOMPILE) - IF @PartitionLevel = 'Y' BEGIN UPDATE tmpIndexesStatistics - SET tmpIndexesStatistics.PartitionCount = PartitionCounts.PartitionCount + SET tmpIndexesStatistics.IsLastPartition = CASE WHEN tmpIndexesStatistics.PartitionNumber = LastPartitionNumbers.LastPartitionNumber THEN 1 ELSE 0 END FROM @tmpIndexesStatistics tmpIndexesStatistics - INNER JOIN (SELECT ObjectID, IndexID, COUNT(*) AS PartitionCount FROM @tmpIndexesStatistics WHERE IndexID IS NOT NULL GROUP BY ObjectID, IndexID) PartitionCounts ON tmpIndexesStatistics.ObjectID = PartitionCounts.ObjectID AND tmpIndexesStatistics.IndexID = PartitionCounts.IndexID + INNER JOIN (SELECT ObjectID, IndexID, MAX(PartitionNumber) AS LastPartitionNumber FROM @tmpIndexesStatistics WHERE IndexID IS NOT NULL AND PartitionNumber IS NOT NULL GROUP BY ObjectID, IndexID) LastPartitionNumbers ON tmpIndexesStatistics.ObjectID = LastPartitionNumbers.ObjectID AND tmpIndexesStatistics.IndexID = LastPartitionNumbers.IndexID OPTION (RECOMPILE) END + UPDATE tmpIndexesStatistics + SET tmpIndexesStatistics.ResumableIndexOperation = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @tmpResumableOperations tmpResumableOperations ON tmpIndexesStatistics.ObjectID = tmpResumableOperations.ObjectID AND tmpIndexesStatistics.IndexID = tmpResumableOperations.IndexID AND (tmpIndexesStatistics.PartitionNumber = tmpResumableOperations.PartitionNumber OR tmpResumableOperations.PartitionNumber IS NULL) + OPTION (RECOMPILE) + IF @Indexes IS NULL BEGIN UPDATE tmpIndexesStatistics @@ -4529,7 +4544,7 @@ BEGIN UPDATE @tmpIndexesStatistics SET UpdateStatisticsCompleted = 1 WHERE StatisticsID IS NULL - OR (IndexID IS NOT NULL AND @PartitionLevel = 'Y' AND IsIncremental = 0 AND PartitionNumber <> PartitionCount AND PartitionNumber IS NOT NULL) + OR (IndexID IS NOT NULL AND @PartitionLevel = 'Y' AND IsIncremental = 0 AND IsLastPartition = 0) SET @CurrentCommand = 'SELECT schemas.[name] AS SchemaName, objects.[name] AS ObjectName' + ' FROM sys.objects objects' @@ -4626,7 +4641,8 @@ BEGIN @CurrentIsIncremental = IsIncremental, @CurrentPartitionID = PartitionID, @CurrentPartitionNumber = PartitionNumber, - @CurrentPartitionCount = PartitionCount, + @CurrentIsPartition = IsPartition, + @CurrentIsLastPartition = IsLastPartition, @CurrentInRowDataPageCount = InRowDataPageCount, @CurrentAlterIndexCompleted = AlterIndexCompleted, @CurrentUpdateStatisticsCompleted = UpdateStatisticsCompleted @@ -4640,9 +4656,6 @@ 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 - IF @CurrentAlterIndexCompleted = 0 AND @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) AND @CurrentOnReadOnlyFileGroup = 0 BEGIN -- Does the index exist? @@ -4679,35 +4692,63 @@ BEGIN -- Is the index fragmented? IF EXISTS(SELECT [Priority], [Action], COUNT(*) FROM @ActionsPreferred GROUP BY [Priority], [Action] HAVING COUNT(*) <> 3) OR @MinNumberOfPages > 0 OR @MaxNumberOfPages IS NOT NULL BEGIN - SET @CurrentCommand = '' + IF NOT EXISTS (SELECT * FROM @PhysicalStats WHERE ObjectID = @CurrentObjectID AND IndexID = @CurrentIndexID) + BEGIN + SET @CurrentCommand = '' - IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + IF @LockTimeout IS NOT NULL SET @CurrentCommand = 'SET LOCK_TIMEOUT ' + CAST(@LockTimeout * 1000 AS nvarchar(max)) + '; ' + + IF @CurrentIndexType IN(5, 6) + BEGIN + SET @CurrentCommand += 'SELECT object_id, index_id, partition_number, MAX(avg_fragmentation_in_percent), SUM(page_count) FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, NULL, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0 GROUP BY object_id, index_id, partition_number' + END + ELSE + BEGIN + SET @CurrentCommand += 'SELECT object_id, index_id, partition_number, avg_fragmentation_in_percent, page_count FROM sys.dm_db_index_physical_stats(DB_ID(@ParamDatabaseName), @ParamObjectID, @ParamIndexID, NULL, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + END + + BEGIN TRY + INSERT INTO @PhysicalStats (ObjectID, IndexID, PartitionNumber, FragmentationLevel, PageCount) + EXECUTE sp_executesql @stmt = @CurrentCommand, @params = N'@ParamDatabaseName nvarchar(max), @ParamObjectID int, @ParamIndexID int', @ParamDatabaseName = @CurrentDatabaseName, @ParamObjectID = @CurrentObjectID, @ParamIndexID = @CurrentIndexID + END TRY + BEGIN CATCH + SET @ErrorMessage = 'Msg ' + CAST(ERROR_NUMBER() AS nvarchar(max)) + ', ' + 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 + SET @ReturnCode = ERROR_NUMBER() + END + + UPDATE @tmpIndexesStatistics + SET AlterIndexCompleted = 1 + WHERE ObjectID = @CurrentObjectID + AND IndexID = @CurrentIndexID + AND AlterIndexCompleted = 0 + + GOTO NoAction + END CATCH + END IF @CurrentPartitionNumber IS NULL BEGIN - 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, NULL, ''LIMITED'') WHERE alloc_unit_type_desc = ''IN_ROW_DATA'' AND index_level = 0' + SELECT @CurrentFragmentationLevel = MAX(FragmentationLevel), + @CurrentPageCount = SUM(PageCount) + FROM @PhysicalStats + WHERE ObjectID = @CurrentObjectID + AND IndexID = @CurrentIndexID END ELSE BEGIN - SET @CurrentCommand += 'SELECT @ParamFragmentationLevel = avg_fragmentation_in_percent, @ParamPageCount = 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' + SELECT @CurrentFragmentationLevel = FragmentationLevel, + @CurrentPageCount = PageCount + FROM @PhysicalStats + WHERE ObjectID = @CurrentObjectID + AND IndexID = @CurrentIndexID + AND PartitionNumber = @CurrentPartitionNumber END - - BEGIN TRY - 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(max)) + ', ' + 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 - SET @ReturnCode = ERROR_NUMBER() - END - - GOTO NoAction - END CATCH END -- Select fragmentation group @@ -4924,7 +4965,7 @@ BEGIN IF @CurrentUpdateStatisticsCompleted = 0 AND @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) - AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentPartitionNumber = @CurrentPartitionCount OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) + AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentIsLastPartition = 1 OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) BEGIN -- Does the statistics exist? SET @CurrentCommand = '' @@ -5010,6 +5051,12 @@ BEGIN SET @ReturnCode = ERROR_NUMBER() END + UPDATE @tmpIndexesStatistics + SET UpdateStatisticsCompleted = 1 + WHERE ObjectID = @CurrentObjectID + AND StatisticsID = @CurrentStatisticsID + AND UpdateStatisticsCompleted = 0 + GOTO NoAction END CATCH END @@ -5178,6 +5225,25 @@ BEGIN AND [Order] = @CurrentIxOrder AND ID = @CurrentIxID + -- Update that index operations on remaining partitions are completed where no action is needed + IF @CurrentIndexID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsPartition = 1 AND (SELECT COUNT(DISTINCT FragmentationGroup) FROM @ActionsPreferred) < 3 + BEGIN + UPDATE tmpIndexesStatistics + SET AlterIndexCompleted = 1 + FROM @tmpIndexesStatistics tmpIndexesStatistics + INNER JOIN @PhysicalStats PhysicalStats ON tmpIndexesStatistics.ObjectID = PhysicalStats.ObjectID AND tmpIndexesStatistics.IndexID = PhysicalStats.IndexID AND tmpIndexesStatistics.PartitionNumber = PhysicalStats.PartitionNumber + WHERE tmpIndexesStatistics.ObjectID = @CurrentObjectID + AND tmpIndexesStatistics.IndexID = @CurrentIndexID + AND tmpIndexesStatistics.AlterIndexCompleted = 0 + AND NOT EXISTS (SELECT * + FROM @ActionsPreferred ActionsPreferred + WHERE ActionsPreferred.FragmentationGroup = CASE + WHEN PhysicalStats.FragmentationLevel >= @FragmentationLevel2 THEN 'High' + WHEN PhysicalStats.FragmentationLevel >= @FragmentationLevel1 AND PhysicalStats.FragmentationLevel < @FragmentationLevel2 THEN 'Medium' + WHEN PhysicalStats.FragmentationLevel < @FragmentationLevel1 THEN 'Low' + END) + END + -- Update that statistics on remaining partitions are completed where no update is needed IF @CurrentStatisticsID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) BEGIN @@ -5218,11 +5284,11 @@ BEGIN SET @CurrentStatisticsName = NULL SET @CurrentPartitionID = NULL SET @CurrentPartitionNumber = NULL - SET @CurrentPartitionCount = NULL SET @CurrentInRowDataPageCount = NULL SET @CurrentAlterIndexCompleted = NULL SET @CurrentUpdateStatisticsCompleted = NULL SET @CurrentIsPartition = NULL + SET @CurrentIsLastPartition = NULL SET @CurrentIndexExists = NULL SET @CurrentStatisticsExists = NULL SET @CurrentIsImageText = NULL @@ -5318,6 +5384,7 @@ BEGIN TRUNCATE TABLE #ExistingObjects TRUNCATE TABLE #ExistingIndexes DELETE FROM @tmpResumableOperations + DELETE FROM @PhysicalStats DELETE FROM @IncrementalStatsProperties END -- End of database loop diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 5e34dd3f..0f4d0200 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -c8009564e0d09acb47c1414b0fb37ec6922806b839dd122fbf146e8e41d3aa9a CommandExecute.sql +796467da5dc67c03f6a5502cff1928054a847645918fcea8d7cbb7d1d74ee4e2 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -d7a3e13a86def129f3b86ceef206216be0c99e2268dc5418bee0e1297bdbfb33 DatabaseBackup.sql -0711269cc16818898174453c621650a501d24639c98a410fa7360e6a4fd53289 DatabaseIntegrityCheck.sql -762c6212940864d58b9458db724ec861b04dcc91c986ed348777f71f972037f5 IndexOptimize.sql -d05b03d06d91554343939cb28d1dcd890779ad029099dbd339a0f016dc5dfaa4 MaintenanceSolution.sql -0ef96156461007c8358e5d2d6a546d3583b54b6e1e249cad97e5c5ae014e7ec8 MaintenanceSolutionAzureSQLDatabase.sql +d75e0beaf0e805477af893052d2de1d8d152205ee1523c840582f5541b549f91 DatabaseBackup.sql +1730a7166a0f5e0ec95cba26d585300878c6fb69ff0dd16f9287ba95996ca33d DatabaseIntegrityCheck.sql +d85628568d0b2d6b1ed655d9016c0504fa62f1976869685b43254ad7e9b2474d IndexOptimize.sql +ef485e93c75a124259265b141c551c8b1328249838557318eaa1d0270787231d MaintenanceSolution.sql +32897f5aee3aa7a88f5824709178ad70431880b48b5e70cbe76281b6ef88bdaa MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From b85b842b2e955e613bbdea61be6ed4b3e7fc7c80 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Fri, 7 Aug 2026 22:56:42 +0200 Subject: [PATCH 154/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 32 +++++++++++--- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 17 ++++---- MaintenanceSolution.sql | 55 +++++++++++++++++-------- MaintenanceSolutionAzureSQLDatabase.sql | 23 +++++------ SHA256SUMS.txt | 12 +++--- 7 files changed, 90 insertions(+), 53 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 6ad60a50..0de88fda 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-07 12:41:25 //-- + --// Version: 2026-08-07 22:55:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index be846ee1..5dd932c3 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 12:41:25 //-- + --// Version: 2026-08-07 22:55:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1095,10 +1095,17 @@ BEGIN VALUES('The number of URLs for the parameters @URL and @MirrorURL has to be the same.', 16, 3) END - IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND @Version < 16 + IF EXISTS(SELECT * FROM @URLs WHERE DirectoryPath LIKE 's3://%/%') AND NOT ((@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND @EngineEdition IN(2, 3, 8)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Backup to S3-compatible storage is not supported in this version of SQL Server.', 16, 4) + VALUES('Backup to S3-compatible storage is not supported in this version and edition of SQL Server.', 16, 4) + END + + IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') + AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 'https://%/%') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('Striped backups across S3-compatible storage and Azure Blob storage are not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -1109,10 +1116,11 @@ BEGIN VALUES('The value for the parameter @MirrorURL is not supported.', 16, 1) END - IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath LIKE 's3://%/%') AND @Version < 16 + IF (EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 'https://%/%') AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath LIKE 's3://%/%')) + OR (EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath LIKE 'https://%/%')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Mirrored backups to S3-compatible storage are not supported in this version of SQL Server.', 16, 2) + VALUES('Mirrored backups across S3-compatible storage and Azure Blob storage are not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1386,6 +1394,12 @@ BEGIN VALUES('The value for the parameter @CopyOnly is not supported.', 16, 1) END + IF @CopyOnly = 'Y' AND @BackupType = 'DIFF' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('Differential copy-only backups are not supported.', 16, 2) + END + ---------------------------------------------------------------------------------------------------- IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL @@ -2364,6 +2378,12 @@ BEGIN VALUES('The value for the parameter @Init is not supported.', 16, 3) END + IF @Init = 'Y' AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @Init is not supported.', 16, 4) + END + ---------------------------------------------------------------------------------------------------- IF @Format NOT IN('Y','N') OR @Format IS NULL @@ -2442,7 +2462,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @BackupOptions IS NOT NULL AND @URL IS NULL + IF @BackupOptions IS NOT NULL AND NOT EXISTS(SELECT * FROM @URLs WHERE DirectoryPath LIKE 's3://%/%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The value for the parameter @BackupOptions is not supported.', 16, 1) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 1de6be02..b77b2ed4 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 12:41:25 //-- + --// Version: 2026-08-07 22:55:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 4306767e..bf41b055 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 12:41:25 //-- + --// Version: 2026-08-07 22:55:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -239,6 +239,7 @@ BEGIN UpdateStatisticsCompleted bit DEFAULT 0, Completed AS CASE WHEN AlterIndexCompleted = 1 AND UpdateStatisticsCompleted = 1 THEN 1 ELSE 0 END, PRIMARY KEY (Selected, Completed, [Order], ID), + INDEX IX_ObjectID_IndexID_PartitionNumber NONCLUSTERED (ObjectID, IndexID, PartitionNumber), INDEX IX_ObjectID_StatisticsID_PartitionNumber NONCLUSTERED (ObjectID, StatisticsID, PartitionNumber)) DROP TABLE IF EXISTS #SelectedIndexes @@ -969,11 +970,6 @@ BEGIN VALUES('The value for the parameter @FragmentationLevel1 is not supported.', 16, 1) END - IF @FragmentationLevel1 >= @FragmentationLevel2 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel1 is not supported.', 16, 2) - END ---------------------------------------------------------------------------------------------------- @@ -983,10 +979,12 @@ BEGIN VALUES('The value for the parameter @FragmentationLevel2 is not supported.', 16, 1) END + ---------------------------------------------------------------------------------------------------- + IF @FragmentationLevel2 <= @FragmentationLevel1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel2 is not supported.', 16, 2) + VALUES('The value for the parameter @FragmentationLevel2 has to be greater than the value for @FragmentationLevel1.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2865,7 +2863,7 @@ BEGIN AND ID = @CurrentIxID -- Update that index operations on remaining partitions are completed where no action is needed - IF @CurrentIndexID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsPartition = 1 AND (SELECT COUNT(DISTINCT FragmentationGroup) FROM @ActionsPreferred) < 3 + IF @CurrentAlterIndexCompleted = 0 AND @CurrentIndexID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsPartition = 1 AND (SELECT COUNT(DISTINCT FragmentationGroup) FROM @ActionsPreferred) < 3 BEGIN UPDATE tmpIndexesStatistics SET AlterIndexCompleted = 1 @@ -2874,6 +2872,7 @@ BEGIN WHERE tmpIndexesStatistics.ObjectID = @CurrentObjectID AND tmpIndexesStatistics.IndexID = @CurrentIndexID AND tmpIndexesStatistics.AlterIndexCompleted = 0 + AND tmpIndexesStatistics.ResumableIndexOperation = 0 AND NOT EXISTS (SELECT * FROM @ActionsPreferred ActionsPreferred WHERE ActionsPreferred.FragmentationGroup = CASE @@ -2884,7 +2883,7 @@ BEGIN END -- Update that statistics on remaining partitions are completed where no update is needed - IF @CurrentStatisticsID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) + IF @CurrentUpdateStatisticsCompleted = 0 AND @CurrentStatisticsID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) BEGIN UPDATE tmpIndexesStatistics SET UpdateStatisticsCompleted = 1 diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 277d3791..02ef540c 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: 2026-08-07 12:41:25 +Version: 2026-08-07 22:55:53 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 12:41:25 //-- + --// Version: 2026-08-07 22:55:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 12:41:25 //-- + --// Version: 2026-08-07 22:55:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1494,10 +1494,17 @@ BEGIN VALUES('The number of URLs for the parameters @URL and @MirrorURL has to be the same.', 16, 3) END - IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND @Version < 16 + IF EXISTS(SELECT * FROM @URLs WHERE DirectoryPath LIKE 's3://%/%') AND NOT ((@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND @EngineEdition IN(2, 3, 8)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Backup to S3-compatible storage is not supported in this version of SQL Server.', 16, 4) + VALUES('Backup to S3-compatible storage is not supported in this version and edition of SQL Server.', 16, 4) + END + + IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') + AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 'https://%/%') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('Striped backups across S3-compatible storage and Azure Blob storage are not supported.', 16, 4) END ---------------------------------------------------------------------------------------------------- @@ -1508,10 +1515,11 @@ BEGIN VALUES('The value for the parameter @MirrorURL is not supported.', 16, 1) END - IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath LIKE 's3://%/%') AND @Version < 16 + IF (EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 'https://%/%') AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath LIKE 's3://%/%')) + OR (EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath LIKE 'https://%/%')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Mirrored backups to S3-compatible storage are not supported in this version of SQL Server.', 16, 2) + VALUES('Mirrored backups across S3-compatible storage and Azure Blob storage are not supported.', 16, 2) END ---------------------------------------------------------------------------------------------------- @@ -1785,6 +1793,12 @@ BEGIN VALUES('The value for the parameter @CopyOnly is not supported.', 16, 1) END + IF @CopyOnly = 'Y' AND @BackupType = 'DIFF' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('Differential copy-only backups are not supported.', 16, 2) + END + ---------------------------------------------------------------------------------------------------- IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL @@ -2763,6 +2777,12 @@ BEGIN VALUES('The value for the parameter @Init is not supported.', 16, 3) END + IF @Init = 'Y' AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @Init is not supported.', 16, 4) + END + ---------------------------------------------------------------------------------------------------- IF @Format NOT IN('Y','N') OR @Format IS NULL @@ -2841,7 +2861,7 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @BackupOptions IS NOT NULL AND @URL IS NULL + IF @BackupOptions IS NOT NULL AND NOT EXISTS(SELECT * FROM @URLs WHERE DirectoryPath LIKE 's3://%/%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The value for the parameter @BackupOptions is not supported.', 16, 1) @@ -4999,7 +5019,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 12:41:25 //-- + --// Version: 2026-08-07 22:55:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7022,7 +7042,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 12:41:25 //-- + --// Version: 2026-08-07 22:55:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7205,6 +7225,7 @@ BEGIN UpdateStatisticsCompleted bit DEFAULT 0, Completed AS CASE WHEN AlterIndexCompleted = 1 AND UpdateStatisticsCompleted = 1 THEN 1 ELSE 0 END, PRIMARY KEY (Selected, Completed, [Order], ID), + INDEX IX_ObjectID_IndexID_PartitionNumber NONCLUSTERED (ObjectID, IndexID, PartitionNumber), INDEX IX_ObjectID_StatisticsID_PartitionNumber NONCLUSTERED (ObjectID, StatisticsID, PartitionNumber)) DROP TABLE IF EXISTS #SelectedIndexes @@ -7935,11 +7956,6 @@ BEGIN VALUES('The value for the parameter @FragmentationLevel1 is not supported.', 16, 1) END - IF @FragmentationLevel1 >= @FragmentationLevel2 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel1 is not supported.', 16, 2) - END ---------------------------------------------------------------------------------------------------- @@ -7949,10 +7965,12 @@ BEGIN VALUES('The value for the parameter @FragmentationLevel2 is not supported.', 16, 1) END + ---------------------------------------------------------------------------------------------------- + IF @FragmentationLevel2 <= @FragmentationLevel1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel2 is not supported.', 16, 2) + VALUES('The value for the parameter @FragmentationLevel2 has to be greater than the value for @FragmentationLevel1.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -9831,7 +9849,7 @@ BEGIN AND ID = @CurrentIxID -- Update that index operations on remaining partitions are completed where no action is needed - IF @CurrentIndexID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsPartition = 1 AND (SELECT COUNT(DISTINCT FragmentationGroup) FROM @ActionsPreferred) < 3 + IF @CurrentAlterIndexCompleted = 0 AND @CurrentIndexID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsPartition = 1 AND (SELECT COUNT(DISTINCT FragmentationGroup) FROM @ActionsPreferred) < 3 BEGIN UPDATE tmpIndexesStatistics SET AlterIndexCompleted = 1 @@ -9840,6 +9858,7 @@ BEGIN WHERE tmpIndexesStatistics.ObjectID = @CurrentObjectID AND tmpIndexesStatistics.IndexID = @CurrentIndexID AND tmpIndexesStatistics.AlterIndexCompleted = 0 + AND tmpIndexesStatistics.ResumableIndexOperation = 0 AND NOT EXISTS (SELECT * FROM @ActionsPreferred ActionsPreferred WHERE ActionsPreferred.FragmentationGroup = CASE @@ -9850,7 +9869,7 @@ BEGIN END -- Update that statistics on remaining partitions are completed where no update is needed - IF @CurrentStatisticsID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) + IF @CurrentUpdateStatisticsCompleted = 0 AND @CurrentStatisticsID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) BEGIN UPDATE tmpIndexesStatistics SET UpdateStatisticsCompleted = 1 diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 5047aca7..2117934b 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-07 12:41:25 +Version: 2026-08-07 22:55:53 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 12:41:25 //-- + --// Version: 2026-08-07 22:55:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 12:41:25 //-- + --// Version: 2026-08-07 22:55:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2417,7 +2417,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 12:41:25 //-- + --// Version: 2026-08-07 22:55:53 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2600,6 +2600,7 @@ BEGIN UpdateStatisticsCompleted bit DEFAULT 0, Completed AS CASE WHEN AlterIndexCompleted = 1 AND UpdateStatisticsCompleted = 1 THEN 1 ELSE 0 END, PRIMARY KEY (Selected, Completed, [Order], ID), + INDEX IX_ObjectID_IndexID_PartitionNumber NONCLUSTERED (ObjectID, IndexID, PartitionNumber), INDEX IX_ObjectID_StatisticsID_PartitionNumber NONCLUSTERED (ObjectID, StatisticsID, PartitionNumber)) DROP TABLE IF EXISTS #SelectedIndexes @@ -3330,11 +3331,6 @@ BEGIN VALUES('The value for the parameter @FragmentationLevel1 is not supported.', 16, 1) END - IF @FragmentationLevel1 >= @FragmentationLevel2 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel1 is not supported.', 16, 2) - END ---------------------------------------------------------------------------------------------------- @@ -3344,10 +3340,12 @@ BEGIN VALUES('The value for the parameter @FragmentationLevel2 is not supported.', 16, 1) END + ---------------------------------------------------------------------------------------------------- + IF @FragmentationLevel2 <= @FragmentationLevel1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel2 is not supported.', 16, 2) + VALUES('The value for the parameter @FragmentationLevel2 has to be greater than the value for @FragmentationLevel1.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5226,7 +5224,7 @@ BEGIN AND ID = @CurrentIxID -- Update that index operations on remaining partitions are completed where no action is needed - IF @CurrentIndexID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsPartition = 1 AND (SELECT COUNT(DISTINCT FragmentationGroup) FROM @ActionsPreferred) < 3 + IF @CurrentAlterIndexCompleted = 0 AND @CurrentIndexID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsPartition = 1 AND (SELECT COUNT(DISTINCT FragmentationGroup) FROM @ActionsPreferred) < 3 BEGIN UPDATE tmpIndexesStatistics SET AlterIndexCompleted = 1 @@ -5235,6 +5233,7 @@ BEGIN WHERE tmpIndexesStatistics.ObjectID = @CurrentObjectID AND tmpIndexesStatistics.IndexID = @CurrentIndexID AND tmpIndexesStatistics.AlterIndexCompleted = 0 + AND tmpIndexesStatistics.ResumableIndexOperation = 0 AND NOT EXISTS (SELECT * FROM @ActionsPreferred ActionsPreferred WHERE ActionsPreferred.FragmentationGroup = CASE @@ -5245,7 +5244,7 @@ BEGIN END -- Update that statistics on remaining partitions are completed where no update is needed - IF @CurrentStatisticsID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) + IF @CurrentUpdateStatisticsCompleted = 0 AND @CurrentStatisticsID IS NOT NULL AND @PartitionLevel = 'Y' AND @CurrentIsIncremental = 1 AND NOT (@OnlyModifiedStatistics = 'N' AND @StatisticsModificationLevel IS NULL) BEGIN UPDATE tmpIndexesStatistics SET UpdateStatisticsCompleted = 1 diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 0f4d0200..71bda93d 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -796467da5dc67c03f6a5502cff1928054a847645918fcea8d7cbb7d1d74ee4e2 CommandExecute.sql +0e6b75a39b225676dc87de4315031afe66dbae0a4c08bdd8ca62b4e744c9ac53 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -d75e0beaf0e805477af893052d2de1d8d152205ee1523c840582f5541b549f91 DatabaseBackup.sql -1730a7166a0f5e0ec95cba26d585300878c6fb69ff0dd16f9287ba95996ca33d DatabaseIntegrityCheck.sql -d85628568d0b2d6b1ed655d9016c0504fa62f1976869685b43254ad7e9b2474d IndexOptimize.sql -ef485e93c75a124259265b141c551c8b1328249838557318eaa1d0270787231d MaintenanceSolution.sql -32897f5aee3aa7a88f5824709178ad70431880b48b5e70cbe76281b6ef88bdaa MaintenanceSolutionAzureSQLDatabase.sql +b2aac58ace0a61d1b7a5b53a8ba874782ee1ded1ab0ce8d54098afeacbef077b DatabaseBackup.sql +52fa25bdb883a3d3da283771f5b00fb0c943e650d00878c77108544fd1d3c633 DatabaseIntegrityCheck.sql +1cd93251be2116264276af7d4ea0c22eafb177dc2d343ff7e202d9df87914c4e IndexOptimize.sql +d83927880d2b6cc11f8350474d4adb6804b410effcbfaefef23fb4e5c21b69f0 MaintenanceSolution.sql +f2c56463b989252e9cb72538c437c39a878ae600f3afd0b078f454fa9d50cdb0 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 2973473893e90d64bb0a7bef4ad8b7b84d29a54c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 8 Aug 2026 16:09:32 +0200 Subject: [PATCH 155/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 16 +++++- DatabaseIntegrityCheck.sql | 27 ++++++++- IndexOptimize.sql | 27 ++++++++- MaintenanceSolution.sql | 74 +++++++++++++++++++++++-- MaintenanceSolutionAzureSQLDatabase.sql | 58 +++++++++++++++++-- SHA256SUMS.txt | 12 ++-- 7 files changed, 197 insertions(+), 19 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 0de88fda..bb7bf5c5 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-07 22:55:53 //-- + --// Version: 2026-08-08 16:00:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 5dd932c3..a2cd7d8f 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 22:55:53 //-- + --// Version: 2026-08-08 16:00:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -182,6 +182,7 @@ BEGIN DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState nvarchar(max) DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) + DECLARE @CurrentSecondaryRoleAllowConnections nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) @@ -2958,6 +2959,10 @@ BEGIN AND is_local = 1 END + SELECT @CurrentSecondaryRoleAllowConnections = secondary_role_allow_connections_desc + FROM sys.availability_replicas + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID @@ -3031,6 +3036,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT @CurrentUserAccess = 'SINGLE_USER' AND NOT @CurrentInStandby = 1 + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) @@ -3146,6 +3152,12 @@ BEGIN SET @DatabaseMessage = 'Availability group database replica synchronization health: ' + ISNULL(@CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth,'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 + SET @DatabaseMessage = 'Availability group backup preference: ' + ISNULL(@CurrentAvailabilityGroupBackupPreference,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -3231,6 +3243,7 @@ BEGIN 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 @ContainedAvailabilityGroupListenerConnection = 0)) + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentAvailabilityGroupRole IS NULL) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) @@ -4531,6 +4544,7 @@ BEGIN SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = NULL SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL + SET @CurrentSecondaryRoleAllowConnections = NULL SET @CurrentIsPreferredBackupReplica = NULL SET @CurrentDistributedAvailabilityGroup = NULL SET @CurrentDistributedAvailabilityGroupReplicaID = NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index b77b2ed4..d83a0553 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 22:55:53 //-- + --// Version: 2026-08-08 16:00:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -91,6 +91,8 @@ BEGIN DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) + DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState nvarchar(max) + DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) DECLARE @CurrentSecondaryRoleAllowConnections nvarchar(max) DECLARE @CurrentIsPreferredBackupReplica bit @@ -1470,6 +1472,21 @@ BEGIN FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID + SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, + @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc + FROM sys.dm_hadr_database_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + AND database_id = DB_ID(@CurrentDatabaseName) + + IF @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState IS NULL AND @ContainedAvailabilityGroupListenerConnection = 1 + BEGIN + SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, + @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc + FROM sys.dm_hadr_database_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + AND DB_NAME(database_id) = @CurrentDatabaseName + END + SELECT @CurrentAvailabilityGroup = [name], @CurrentAvailabilityGroupBackupPreference = UPPER(automated_backup_preference_desc) FROM sys.availability_groups @@ -1512,6 +1529,12 @@ BEGIN SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + SET @DatabaseMessage = 'Availability group database replica synchronization state: ' + ISNULL(@CurrentAvailabilityGroupDatabaseReplicaSynchronizationState,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group database replica synchronization health: ' + ISNULL(@CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + IF @CurrentAvailabilityGroupRole = 'SECONDARY' BEGIN SET @DatabaseMessage = 'Readable Secondary: ' + ISNULL(@CurrentSecondaryRoleAllowConnections,'N/A') @@ -1967,6 +1990,8 @@ BEGIN SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL + SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = NULL + SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL SET @CurrentSecondaryRoleAllowConnections = NULL SET @CurrentIsPreferredBackupReplica = NULL diff --git a/IndexOptimize.sql b/IndexOptimize.sql index bf41b055..ca51b3c0 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 22:55:53 //-- + --// Version: 2026-08-08 16:00:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -113,6 +113,8 @@ BEGIN DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) + DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState nvarchar(max) + DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) @@ -1685,6 +1687,21 @@ BEGIN FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID + SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, + @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc + FROM sys.dm_hadr_database_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + AND database_id = DB_ID(@CurrentDatabaseName) + + IF @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState IS NULL AND @ContainedAvailabilityGroupListenerConnection = 1 + BEGIN + SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, + @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc + FROM sys.dm_hadr_database_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + AND DB_NAME(database_id) = @CurrentDatabaseName + END + SELECT @CurrentAvailabilityGroup = [name] FROM sys.availability_groups WHERE group_id = @CurrentAvailabilityGroupID @@ -1720,6 +1737,12 @@ BEGIN SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group database replica synchronization state: ' + ISNULL(@CurrentAvailabilityGroupDatabaseReplicaSynchronizationState,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group database replica synchronization health: ' + ISNULL(@CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END IF @CurrentDistributedAvailabilityGroup IS NOT NULL @@ -3006,6 +3029,8 @@ BEGIN SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL + SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = NULL + SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = NULL SET @CurrentDistributedAvailabilityGroup = NULL SET @CurrentDistributedAvailabilityGroupReplicaID = NULL SET @CurrentDistributedAvailabilityGroupRole = NULL diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 02ef540c..73abbc8b 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: 2026-08-07 22:55:53 +Version: 2026-08-08 16:00:55 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 22:55:53 //-- + --// Version: 2026-08-08 16:00:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 22:55:53 //-- + --// Version: 2026-08-08 16:00:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -581,6 +581,7 @@ BEGIN DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState nvarchar(max) DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) + DECLARE @CurrentSecondaryRoleAllowConnections nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) @@ -3357,6 +3358,10 @@ BEGIN AND is_local = 1 END + SELECT @CurrentSecondaryRoleAllowConnections = secondary_role_allow_connections_desc + FROM sys.availability_replicas + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + SELECT @CurrentAvailabilityGroupRole = role_desc FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID @@ -3430,6 +3435,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT @CurrentUserAccess = 'SINGLE_USER' AND NOT @CurrentInStandby = 1 + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) @@ -3545,6 +3551,12 @@ BEGIN SET @DatabaseMessage = 'Availability group database replica synchronization health: ' + ISNULL(@CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth,'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 + SET @DatabaseMessage = 'Availability group backup preference: ' + ISNULL(@CurrentAvailabilityGroupBackupPreference,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT @@ -3630,6 +3642,7 @@ BEGIN 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 @ContainedAvailabilityGroupListenerConnection = 0)) + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentAvailabilityGroupRole IS NULL) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) @@ -4930,6 +4943,7 @@ BEGIN SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = NULL SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL + SET @CurrentSecondaryRoleAllowConnections = NULL SET @CurrentIsPreferredBackupReplica = NULL SET @CurrentDistributedAvailabilityGroup = NULL SET @CurrentDistributedAvailabilityGroupReplicaID = NULL @@ -5019,7 +5033,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 22:55:53 //-- + --// Version: 2026-08-08 16:00:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5070,6 +5084,8 @@ BEGIN DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) + DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState nvarchar(max) + DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) DECLARE @CurrentSecondaryRoleAllowConnections nvarchar(max) DECLARE @CurrentIsPreferredBackupReplica bit @@ -6449,6 +6465,21 @@ BEGIN FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID + SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, + @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc + FROM sys.dm_hadr_database_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + AND database_id = DB_ID(@CurrentDatabaseName) + + IF @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState IS NULL AND @ContainedAvailabilityGroupListenerConnection = 1 + BEGIN + SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, + @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc + FROM sys.dm_hadr_database_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + AND DB_NAME(database_id) = @CurrentDatabaseName + END + SELECT @CurrentAvailabilityGroup = [name], @CurrentAvailabilityGroupBackupPreference = UPPER(automated_backup_preference_desc) FROM sys.availability_groups @@ -6491,6 +6522,12 @@ BEGIN SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + SET @DatabaseMessage = 'Availability group database replica synchronization state: ' + ISNULL(@CurrentAvailabilityGroupDatabaseReplicaSynchronizationState,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group database replica synchronization health: ' + ISNULL(@CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + IF @CurrentAvailabilityGroupRole = 'SECONDARY' BEGIN SET @DatabaseMessage = 'Readable Secondary: ' + ISNULL(@CurrentSecondaryRoleAllowConnections,'N/A') @@ -6946,6 +6983,8 @@ BEGIN SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL + SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = NULL + SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL SET @CurrentSecondaryRoleAllowConnections = NULL SET @CurrentIsPreferredBackupReplica = NULL @@ -7042,7 +7081,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 22:55:53 //-- + --// Version: 2026-08-08 16:00:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7099,6 +7138,8 @@ BEGIN DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) + DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState nvarchar(max) + DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) @@ -8671,6 +8712,21 @@ BEGIN FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID + SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, + @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc + FROM sys.dm_hadr_database_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + AND database_id = DB_ID(@CurrentDatabaseName) + + IF @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState IS NULL AND @ContainedAvailabilityGroupListenerConnection = 1 + BEGIN + SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, + @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc + FROM sys.dm_hadr_database_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + AND DB_NAME(database_id) = @CurrentDatabaseName + END + SELECT @CurrentAvailabilityGroup = [name] FROM sys.availability_groups WHERE group_id = @CurrentAvailabilityGroupID @@ -8706,6 +8762,12 @@ BEGIN SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group database replica synchronization state: ' + ISNULL(@CurrentAvailabilityGroupDatabaseReplicaSynchronizationState,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group database replica synchronization health: ' + ISNULL(@CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END IF @CurrentDistributedAvailabilityGroup IS NOT NULL @@ -9992,6 +10054,8 @@ BEGIN SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL + SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = NULL + SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = NULL SET @CurrentDistributedAvailabilityGroup = NULL SET @CurrentDistributedAvailabilityGroupReplicaID = NULL SET @CurrentDistributedAvailabilityGroupRole = NULL diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 2117934b..08e08b05 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-07 22:55:53 +Version: 2026-08-08 16:00:55 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 22:55:53 //-- + --// Version: 2026-08-08 16:00:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 22:55:53 //-- + --// Version: 2026-08-08 16:00:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -445,6 +445,8 @@ BEGIN DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) + DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState nvarchar(max) + DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth nvarchar(max) DECLARE @CurrentAvailabilityGroupBackupPreference nvarchar(max) DECLARE @CurrentSecondaryRoleAllowConnections nvarchar(max) DECLARE @CurrentIsPreferredBackupReplica bit @@ -1824,6 +1826,21 @@ BEGIN FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID + SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, + @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc + FROM sys.dm_hadr_database_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + AND database_id = DB_ID(@CurrentDatabaseName) + + IF @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState IS NULL AND @ContainedAvailabilityGroupListenerConnection = 1 + BEGIN + SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, + @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc + FROM sys.dm_hadr_database_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + AND DB_NAME(database_id) = @CurrentDatabaseName + END + SELECT @CurrentAvailabilityGroup = [name], @CurrentAvailabilityGroupBackupPreference = UPPER(automated_backup_preference_desc) FROM sys.availability_groups @@ -1866,6 +1883,12 @@ BEGIN SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + SET @DatabaseMessage = 'Availability group database replica synchronization state: ' + ISNULL(@CurrentAvailabilityGroupDatabaseReplicaSynchronizationState,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group database replica synchronization health: ' + ISNULL(@CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + IF @CurrentAvailabilityGroupRole = 'SECONDARY' BEGIN SET @DatabaseMessage = 'Readable Secondary: ' + ISNULL(@CurrentSecondaryRoleAllowConnections,'N/A') @@ -2321,6 +2344,8 @@ BEGIN SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL + SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = NULL + SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = NULL SET @CurrentAvailabilityGroupBackupPreference = NULL SET @CurrentSecondaryRoleAllowConnections = NULL SET @CurrentIsPreferredBackupReplica = NULL @@ -2417,7 +2442,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-07 22:55:53 //-- + --// Version: 2026-08-08 16:00:55 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2474,6 +2499,8 @@ BEGIN DECLARE @CurrentAvailabilityGroupID uniqueidentifier DECLARE @CurrentAvailabilityGroup nvarchar(max) DECLARE @CurrentAvailabilityGroupRole nvarchar(max) + DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState nvarchar(max) + DECLARE @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroup nvarchar(max) DECLARE @CurrentDistributedAvailabilityGroupReplicaID uniqueidentifier DECLARE @CurrentDistributedAvailabilityGroupRole nvarchar(max) @@ -4046,6 +4073,21 @@ BEGIN FROM sys.dm_hadr_availability_replica_states WHERE replica_id = @CurrentAvailabilityGroupReplicaID + SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, + @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc + FROM sys.dm_hadr_database_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + AND database_id = DB_ID(@CurrentDatabaseName) + + IF @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState IS NULL AND @ContainedAvailabilityGroupListenerConnection = 1 + BEGIN + SELECT @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = synchronization_state_desc, + @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = synchronization_health_desc + FROM sys.dm_hadr_database_replica_states + WHERE replica_id = @CurrentAvailabilityGroupReplicaID + AND DB_NAME(database_id) = @CurrentDatabaseName + END + SELECT @CurrentAvailabilityGroup = [name] FROM sys.availability_groups WHERE group_id = @CurrentAvailabilityGroupID @@ -4081,6 +4123,12 @@ BEGIN SET @DatabaseMessage = 'Availability group role: ' + ISNULL(@CurrentAvailabilityGroupRole,'N/A') RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group database replica synchronization state: ' + ISNULL(@CurrentAvailabilityGroupDatabaseReplicaSynchronizationState,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT + + SET @DatabaseMessage = 'Availability group database replica synchronization health: ' + ISNULL(@CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth,'N/A') + RAISERROR('%s',10,1,@DatabaseMessage) WITH NOWAIT END IF @CurrentDistributedAvailabilityGroup IS NOT NULL @@ -5367,6 +5415,8 @@ BEGIN SET @CurrentAvailabilityGroupID = NULL SET @CurrentAvailabilityGroup = NULL SET @CurrentAvailabilityGroupRole = NULL + SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationState = NULL + SET @CurrentAvailabilityGroupDatabaseReplicaSynchronizationHealth = NULL SET @CurrentDistributedAvailabilityGroup = NULL SET @CurrentDistributedAvailabilityGroupReplicaID = NULL SET @CurrentDistributedAvailabilityGroupRole = NULL diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 71bda93d..f135288e 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -0e6b75a39b225676dc87de4315031afe66dbae0a4c08bdd8ca62b4e744c9ac53 CommandExecute.sql +544a4e37c1e4c58625b6e70093043e78befd1924aeabeb81f8592bcb6b26760e CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -b2aac58ace0a61d1b7a5b53a8ba874782ee1ded1ab0ce8d54098afeacbef077b DatabaseBackup.sql -52fa25bdb883a3d3da283771f5b00fb0c943e650d00878c77108544fd1d3c633 DatabaseIntegrityCheck.sql -1cd93251be2116264276af7d4ea0c22eafb177dc2d343ff7e202d9df87914c4e IndexOptimize.sql -d83927880d2b6cc11f8350474d4adb6804b410effcbfaefef23fb4e5c21b69f0 MaintenanceSolution.sql -f2c56463b989252e9cb72538c437c39a878ae600f3afd0b078f454fa9d50cdb0 MaintenanceSolutionAzureSQLDatabase.sql +2cc8a864403f3e611e152f92c4cc7f0321f1732639e06409236058ba50932a86 DatabaseBackup.sql +46010b3074a0905e0a03a84d810d728122edbae9260ae2ca5308662c0d930987 DatabaseIntegrityCheck.sql +61c06a95b51c21ab2c3e64d82915dc10841f50a514d3011ea5d0461814c4678e IndexOptimize.sql +dbbfe1aee6319e9a7066817a343bc7f04786d6c668bc693889e9cfeec455b1fc MaintenanceSolution.sql +e1920c34889256f24af2304ab5e471c47b0c5da10e1cb98be6fa3a3df5301e29 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From eda7da441f5994279da87d58bec6449cafb89f30 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 8 Aug 2026 22:32:36 +0200 Subject: [PATCH 156/177] Add files via upload --- CommandExecute.sql | 18 +- DatabaseBackup.sql | 506 +++++++-------- DatabaseIntegrityCheck.sql | 132 ++-- IndexOptimize.sql | 162 +++-- MaintenanceSolution.sql | 816 +++++++++++------------- MaintenanceSolutionAzureSQLDatabase.sql | 310 +++++---- SHA256SUMS.txt | 12 +- 7 files changed, 931 insertions(+), 1025 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index bb7bf5c5..1d65e9d5 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-08 16:00:55 //-- + --// Version: 2026-08-08 22:31:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -103,25 +103,25 @@ BEGIN IF @DatabaseContext IS NULL OR NOT EXISTS (SELECT * FROM sys.databases WHERE name = @DatabaseContext) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseContext is not supported.', 16, 1) + VALUES('The value for the parameter @DatabaseContext is not supported. Specify the name of an existing database.', 16, 1) END IF @Command IS NULL OR @Command = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Command is not supported.', 16, 1) + VALUES('The value for the parameter @Command is not supported. The value cannot be NULL or empty.', 16, 1) END IF @CommandType IS NULL OR @CommandType = '' OR LEN(@CommandType) > 60 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CommandType is not supported.', 16, 1) + VALUES('The value for the parameter @CommandType is not supported. The value cannot be NULL or empty, and the maximum length is 60 characters.', 16, 1) END IF @Mode NOT IN(1,2) OR @Mode IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Mode is not supported.', 16, 1) + VALUES('The value for the parameter @Mode is not supported. Supported values are 1 and 2.', 16, 1) END IF (@EncryptionKey IS NULL AND @EncryptionKeyPlaceholder IS NOT NULL) OR (@EncryptionKey IS NOT NULL AND @EncryptionKeyPlaceholder IS NULL) @@ -133,25 +133,25 @@ BEGIN IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) + VALUES('The value for the parameter @LockMessageSeverity is not supported. Supported values are 10 and 16.', 16, 1) END IF LEN(@ExecuteAsUser) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExecuteAsUser is not supported.', 16, 1) + VALUES('The value for the parameter @ExecuteAsUser is not supported. The maximum length is 128 characters.', 16, 1) END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) + VALUES('The value for the parameter @LogToTable is not supported. Supported values are ''Y'' and ''N''.', 16, 1) END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Execute is not supported.', 16, 1) + VALUES('The value for the parameter @Execute is not supported. Supported values are ''Y'' and ''N''.', 16, 1) END ---------------------------------------------------------------------------------------------------- diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index a2cd7d8f..57a629cb 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 16:00:55 //-- + --// Version: 2026-08-08 22:31:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -496,13 +496,13 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1) + VALUES('ANSI_NULLS has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1) + VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-backup.html.', 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') @@ -526,25 +526,25 @@ BEGIN 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, [State]) - VALUES('The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1) + VALUES('The table Queue is missing. It is required when @DatabasesInParallel = ''Y''. 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, [State]) - VALUES('The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) + VALUES('The table QueueDatabase is missing. It is required when @DatabasesInParallel = ''Y''. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) END IF @@TRANCOUNT <> 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The transaction count is not 0.', 16, 1) + VALUES('The stored procedure cannot be executed inside a transaction. The transaction count (@@TRANCOUNT) has to be 0. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF @AmazonRDS = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The stored procedure DatabaseBackup is not supported on Amazon RDS.', 16, 1) + VALUES('The stored procedure DatabaseBackup is not supported on Amazon RDS. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -668,7 +668,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DATALENGTH(DatabaseName) = 0)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Databases is not supported.', 16, 1) + VALUES('The value for the parameter @Databases is not supported. The value could not be parsed into a list of databases. See https://ola.hallengren.com/sql-server-backup.html#Databases.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -760,22 +760,28 @@ 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 @IsHadrEnabled = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroups is not supported.', 16, 1) + VALUES('The value for the parameter @AvailabilityGroups is not supported. The value could not be parsed into a list of availability groups. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroups.', 16, 1) + END + + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameter @AvailabilityGroups can only be used when availability groups are enabled on the instance. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroups.', 16, 1) END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2) + VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -791,7 +797,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The names of the following databases are not supported: ' + @ErrorMessage + '.', 16, 1) + VALUES('The names of the following databases are not supported: ' + @ErrorMessage + '. A database name has to contain at least one character that can be used in file names. See https://ola.hallengren.com/sql-server-backup.html#Databases.', 16, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -804,7 +810,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The names of the following databases are not unique in the file system: ' + @ErrorMessage + '.', 16, 1) + VALUES('The names of the following databases are not unique in the file system: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-backup.html#Databases.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -902,43 +908,49 @@ 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 = 'NUL') OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Directory is not supported.', 16, 1) + VALUES('The value for the parameter @Directory is not supported. Specify a local path (e.g. D:\Backup), a UNC path (e.g. \\Server\Share), a path starting with / on Linux, or NUL, without leading or trailing spaces. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) END IF EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The same directory has been specified multiple times in the parameters @Directory and @MirrorDirectory.', 16, 2) + VALUES('The same directory has been specified multiple times in the parameters @Directory and @MirrorDirectory. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) 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]) - VALUES('The number of directories for the parameters @Directory and @MirrorDirectory has to be the same.', 16, 3) + VALUES('The number of directories for the parameters @Directory and @MirrorDirectory has to be the same. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END - IF (@Directory IS NOT NULL AND @EngineEdition = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @Directory IS NOT NULL AND @EngineEdition = 8 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Directory is not supported.', 16, 4) + VALUES('The parameter @Directory is not supported on Azure SQL Managed Instance. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) + END + + IF @Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameter @Directory is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) 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]) - VALUES('The value for the parameter @Directory is not supported.', 16, 5) + VALUES('The value for the parameter @Directory is not supported. Backup to NUL cannot be combined with other directories. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) 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]) - VALUES('Mirrored backup is not supported when backing up to NUL.', 16, 6) + VALUES('Mirrored backup is not supported when backing up to NUL. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Backup to NUL is only supported with SQL Server native backups.', 16, 7) + VALUES('Backup to NUL is only supported with SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -946,31 +958,31 @@ 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 IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 1) + VALUES('The value for the parameter @MirrorDirectory is not supported. Specify a local path (e.g. D:\Backup), a UNC path (e.g. \\Server\Share), or a path starting with / on Linux, without leading or trailing spaces. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END IF @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 2) + VALUES('The value for the parameter @MirrorDirectory is not supported. Redgate SQL Backup Pro and Idera SQL Safe Backup support only one mirror directory. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END IF @MirrorDirectory IS NOT NULL AND @EngineEdition = 8 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 3) + VALUES('The value for the parameter @MirrorDirectory is not supported. Mirrored backup is not supported on Azure SQL Managed Instance. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END IF @MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 4) + VALUES('The value for the parameter @MirrorDirectory is not supported. Mirrored backup is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND @EngineEdition <> 3) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorDirectory is not supported. Mirrored backup to disk is only available in Enterprise and Developer Edition.', 16, 5) + VALUES('The value for the parameter @MirrorDirectory is not supported. Mirrored backup to disk is not supported in this edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1000,7 +1012,7 @@ BEGIN IF NOT EXISTS (SELECT * FROM @DirectoryInfo WHERE FileExists = 0 AND FileIsADirectory = 1 AND ParentDirectoryExists = 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The directory ' + @CurrentRootDirectoryPath + ' does not exist.', 16, 1) + VALUES('The directory ' + @CurrentRootDirectoryPath + ' does not exist. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END UPDATE @Directories @@ -1081,32 +1093,32 @@ BEGIN IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND NOT (DirectoryPath LIKE 'https://%/%' OR DirectoryPath LIKE 's3://%/%')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @URL is not supported.', 16, 1) + VALUES('The value for the parameter @URL is not supported. The URL has to start with https:// (Azure Blob Storage) or s3:// (S3-compatible storage). See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) END IF EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The same URL has been specified multiple times in the parameters @URL and @MirrorURL.', 16, 2) + VALUES('The same URL has been specified multiple times in the parameters @URL and @MirrorURL. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) 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]) - VALUES('The number of URLs for the parameters @URL and @MirrorURL has to be the same.', 16, 3) + VALUES('The number of URLs for the parameters @URL and @MirrorURL has to be the same. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF EXISTS(SELECT * FROM @URLs WHERE DirectoryPath LIKE 's3://%/%') AND NOT ((@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND @EngineEdition IN(2, 3, 8)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Backup to S3-compatible storage is not supported in this version and edition of SQL Server.', 16, 4) + VALUES('Backup to S3-compatible storage is not supported in this version and edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) END IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 'https://%/%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Striped backups across S3-compatible storage and Azure Blob storage are not supported.', 16, 4) + VALUES('Striped backups across S3-compatible storage and Azure Blob Storage are not supported. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1114,14 +1126,14 @@ BEGIN IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND NOT (DirectoryPath LIKE 'https://%/%' OR DirectoryPath LIKE 's3://%/%')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorURL is not supported.', 16, 1) + VALUES('The value for the parameter @MirrorURL is not supported. The URL has to start with https:// (Azure Blob Storage) or s3:// (S3-compatible storage). See https://ola.hallengren.com/sql-server-backup.html#MirrorURL.', 16, 1) END IF (EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 'https://%/%') AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath LIKE 's3://%/%')) OR (EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath LIKE 'https://%/%')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Mirrored backups across S3-compatible storage and Azure Blob storage are not supported.', 16, 2) + VALUES('Mirrored backups across S3-compatible storage and Azure Blob Storage are not supported. See https://ola.hallengren.com/sql-server-backup.html#MirrorURL.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1225,7 +1237,7 @@ BEGIN IF @BackupType NOT IN ('FULL','DIFF','LOG') OR @BackupType IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BackupType is not supported.', 16, 1) + VALUES('The value for the parameter @BackupType is not supported. Supported values are FULL, DIFF and LOG. See https://ola.hallengren.com/sql-server-backup.html#BackupType.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1233,7 +1245,7 @@ BEGIN IF @EngineEdition = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('SQL Database Managed Instance only supports COPY_ONLY full backups.', 16, 1) + VALUES('Azure SQL Managed Instance only supports COPY_ONLY full backups. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1241,25 +1253,25 @@ BEGIN IF @Verify NOT IN ('Y','N') OR @Verify IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Verify is not supported.', 16, 1) + VALUES('The value for the parameter @Verify is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#Verify.', 16, 1) END IF @BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Verify is not supported. Verify is not supported with encrypted backups with Idera SQL Safe Backup.', 16, 2) + VALUES('Verify is not supported for encrypted backups with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#Verify.', 16, 1) END IF @Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Verify is not supported. Verify is not supported with Data Domain Boost.', 16, 3) + VALUES('Verify is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#Verify.', 16, 1) END IF @Verify = 'Y' AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.', 16, 4) + VALUES('Verify is not supported when backing up to NUL. See https://ola.hallengren.com/sql-server-backup.html#Verify.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1267,37 +1279,37 @@ BEGIN IF @CleanupTime < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupTime is not supported.', 16, 1) + VALUES('The value for the parameter @CleanupTime is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) END IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.', 16, 2) + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) END IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.', 16, 3) + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.', 16, 4) + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory structure. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) AND (SELECT COUNT(*) FROM (SELECT @FileExtensionFull AS FileExtension UNION SELECT @FileExtensionDiff UNION SELECT @FileExtensionLog) FileExtension) <> 3 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory and the file extensions are not unique.', 16, 5) + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory structure and the file extensions are not unique. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) END IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.', 16, 6) + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory structure. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1305,7 +1317,7 @@ BEGIN IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupMode is not supported.', 16, 1) + VALUES('The value for the parameter @CleanupMode is not supported. Supported values are BEFORE_BACKUP and AFTER_BACKUP. See https://ola.hallengren.com/sql-server-backup.html#CleanupMode.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1313,26 +1325,26 @@ BEGIN IF @Compress NOT IN ('Y','N') OR @Compress IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Compress is not supported.', 16, 1) + VALUES('The value for the parameter @Compress is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) END IF @Compress = 'Y' AND @BackupSoftware IS NULL AND NOT (@EngineEdition IN (3, 8) OR @EditionID IN (-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Compress is not supported. Backup compression is not supported in this edition of SQL Server.', 16, 2) + VALUES('Backup compression is not supported in this edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) END IF @Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevelNumeric IS NULL OR @CompressionLevelNumeric >= 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Compress is not supported.', 16, 3) + VALUES('Setting @Compress to ''N'' with LiteSpeed for SQL Server, Redgate SQL Backup Pro or Idera SQL Safe Backup requires @CompressionLevelNumeric = 0. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) END IF @Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevelNumeric = 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Compress is not supported.', 16, 4) + VALUES('Setting @Compress to ''Y'' cannot be combined with @CompressionLevelNumeric = 0. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1340,31 +1352,31 @@ BEGIN IF @CompressionAlgorithm NOT IN ('MS_XPRESS','QAT_DEFLATE','ZSTD') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionAlgorithm is not supported. The allowed values are MS_XPRESS, QAT_DEFLATE and ZSTD.', 16, 1) + VALUES('The value for the parameter @CompressionAlgorithm is not supported. Supported values are MS_XPRESS, QAT_DEFLATE and ZSTD. See https://ola.hallengren.com/sql-server-backup.html#CompressionAlgorithm.', 16, 1) END IF @CompressionAlgorithm IS NOT NULL AND NOT (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionAlgorithm is not supported. Specifying the compression algorithm is only supported in SQL Server 2022 and later.', 16, 2) + VALUES('The parameter @CompressionAlgorithm is not supported in this version and edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#CompressionAlgorithm.', 16, 1) END IF @CompressionAlgorithm = 'QAT_DEFLATE' AND NOT (@EngineEdition IN(2, 3)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to QAT_DEFLATE is only supported in Standard and Enterprise Edition.', 16, 3) + VALUES('Setting @CompressionAlgorithm to QAT_DEFLATE is not supported in this edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#CompressionAlgorithm.', 16, 1) END IF @CompressionAlgorithm = 'ZSTD' AND NOT (@Version >= 17 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to ZSTD is only supported in SQL Server 2025 and later.', 16, 4) + VALUES('Setting @CompressionAlgorithm to ZSTD is not supported in this version and edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#CompressionAlgorithm.', 16, 1) END IF @CompressionAlgorithm IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm is only supported with SQL Server native backup.', 16, 5) + VALUES('The parameter @CompressionAlgorithm is only supported with SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html#CompressionAlgorithm.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1372,19 +1384,19 @@ BEGIN IF @CompressionLevel IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevel is not supported. For third-party backup software, use the parameter @CompressionLevelNumeric.', 16, 1) + VALUES('The parameter @CompressionLevel is only supported with SQL Server native backups. For third-party backup software, use the parameter @CompressionLevelNumeric. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevel.', 16, 1) END IF @CompressionLevel NOT IN ('LOW','MEDIUM','HIGH') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevel is not supported. The supported values are LOW, MEDIUM and HIGH.', 16, 2) + VALUES('The value for the parameter @CompressionLevel is not supported. Supported values are LOW, MEDIUM and HIGH. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevel.', 16, 1) END IF @CompressionLevel IS NOT NULL AND NOT (@Version >= 17 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevel is not supported. Setting the compression level is only supported in SQL Server 2025 and later.', 16, 3) + VALUES('The parameter @CompressionLevel is not supported in this version and edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1392,13 +1404,13 @@ BEGIN IF @CopyOnly NOT IN ('Y','N') OR @CopyOnly IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CopyOnly is not supported.', 16, 1) + VALUES('The value for the parameter @CopyOnly is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#CopyOnly.', 16, 1) END IF @CopyOnly = 'Y' AND @BackupType = 'DIFF' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Differential copy-only backups are not supported.', 16, 2) + VALUES('Differential copy-only backups are not supported. See https://ola.hallengren.com/sql-server-backup.html#CopyOnly.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1406,13 +1418,13 @@ BEGIN IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ChangeBackupType is not supported.', 16, 1) + VALUES('The value for the parameter @ChangeBackupType is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#ChangeBackupType.', 16, 1) END IF @ChangeBackupType = 'Y' AND NOT @BackupType IN ('DIFF', 'LOG') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Setting @ChangeBackupType to ''Y'' is only supported with differential and log backups.', 16, 2) + VALUES('Setting @ChangeBackupType to ''Y'' is only supported with differential and log backups. See https://ola.hallengren.com/sql-server-backup.html#ChangeBackupType.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1420,37 +1432,37 @@ BEGIN IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BackupSoftware is not supported.', 16, 1) + VALUES('The value for the parameter @BackupSoftware is not supported. Supported values are LITESPEED, SQLBACKUP, SQLSAFE and DATA_DOMAIN_BOOST. See https://ola.hallengren.com/sql-server-backup.html#BackupSoftware.', 16, 1) END IF @BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BackupSoftware is not supported. Only native backups are supported on Linux.', 16, 2) + VALUES('The value for the parameter @BackupSoftware is not supported. Only native backups are supported on Linux. See https://ola.hallengren.com/sql-server-backup.html#BackupSoftware.', 16, 1) 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, [State]) - VALUES('LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.', 16, 3) + VALUES('LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.', 16, 1) END IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/sql-backup/.', 16, 4) + VALUES('Redgate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/sql-backup/.', 16, 1) 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, [State]) - VALUES('Idera SQL Safe Backup is not installed. Download https://www.idera.com/products/sql-safe-backup/.', 16, 5) + VALUES('Idera SQL Safe Backup is not installed. Download https://www.idera.com/products/sql-safe-backup/.', 16, 1) 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, [State]) - VALUES('EMC Data Domain Boost is not installed. Download https://www.dell.com/en-us/shop/storage-servers-and-networking-for-business/sf/powerprotect-data-domain.', 16, 6) + VALUES('Data Domain Boost is not installed. Download https://www.dell.com/en-us/shop/storage-servers-and-networking-for-business/sf/powerprotect-data-domain.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1458,7 +1470,7 @@ BEGIN IF @Checksum NOT IN ('Y','N') OR @Checksum IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Checksum is not supported.', 16, 1) + VALUES('The value for the parameter @Checksum is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#Checksum.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1466,31 +1478,31 @@ BEGIN IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BlockSize is not supported.', 16, 1) + VALUES('The value for the parameter @BlockSize is not supported. Supported values are 512, 1024, 2048, 4096, 8192, 16384, 32768 and 65536. See https://ola.hallengren.com/sql-server-backup.html#BlockSize.', 16, 1) END IF @BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BlockSize is not supported. This parameter is not supported with Redgate SQL Backup Pro.', 16, 2) + VALUES('The parameter @BlockSize is not supported with Redgate SQL Backup Pro. See https://ola.hallengren.com/sql-server-backup.html#BlockSize.', 16, 1) END IF @BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BlockSize is not supported. This parameter is not supported with Idera SQL Safe.', 16, 3) + VALUES('The parameter @BlockSize is not supported with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#BlockSize.', 16, 1) END IF @BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('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) + VALUES('BLOCKSIZE is not supported when backing up to URL with page blobs. See https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url.', 16, 1) END IF @BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BlockSize is not supported. This parameter is not supported with Data Domain Boost.', 16, 5) + VALUES('The parameter @BlockSize is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#BlockSize.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1498,19 +1510,19 @@ BEGIN IF @BufferCount <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BufferCount is not supported.', 16, 1) + VALUES('The value for the parameter @BufferCount is not supported. The value has to be greater than 0. See https://ola.hallengren.com/sql-server-backup.html#BufferCount.', 16, 1) END IF @BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BufferCount is not supported.', 16, 2) + VALUES('The parameter @BufferCount is not supported with Redgate SQL Backup Pro. See https://ola.hallengren.com/sql-server-backup.html#BufferCount.', 16, 1) END IF @BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BufferCount is not supported.', 16, 3) + VALUES('The parameter @BufferCount is not supported with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#BufferCount.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1518,37 +1530,37 @@ BEGIN IF @MaxTransferSize < 65536 OR @MaxTransferSize > 20971520 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 1) + VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 20971520. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END IF @MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 2) + VALUES('The value for the parameter @MaxTransferSize is not supported. The maximum value with Redgate SQL Backup Pro is 1048576. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END IF @MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 3) + VALUES('The parameter @MaxTransferSize is not supported with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END IF @MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('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) + VALUES('MAXTRANSFERSIZE is not supported when backing up to URL with page blobs. See https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url.', 16, 1) END IF @MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 5) + VALUES('The parameter @MaxTransferSize is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @MaxTransferSize > 4194304 AND @URL IS NULL AND @BackupSoftware IS NULL + IF @MaxTransferSize > 4194304 AND @Directory IS NOT NULL AND @BackupSoftware IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 6) + VALUES('The value for the parameter @MaxTransferSize is not supported. The maximum value for SQL Server native backups to disk is 4194304. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1556,61 +1568,61 @@ BEGIN IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 1) + VALUES('The value for the parameter @NumberOfFiles is not supported. The value has to be between 1 and 64. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 2) + VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files with Redgate SQL Backup Pro is 32. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 3) + VALUES('The value for the parameter @NumberOfFiles is not supported. The number of files has to be greater than or equal to the number of directories. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 4) + VALUES('The value for the parameter @NumberOfFiles is not supported. The number of files has to be evenly divisible by the number of directories. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('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) + VALUES('Backup striping to URL with page blobs is not supported. See https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url.', 16, 1) END IF @NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 6) + VALUES('The value for the parameter @NumberOfFiles is not supported. Mirrored backups with multiple files are not supported with Redgate SQL Backup Pro and Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 7) + VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files with Data Domain Boost is 32. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 8) + VALUES('The value for the parameter @NumberOfFiles is not supported. The number of files has to be greater than or equal to the number of URLs. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 9) + VALUES('The value for the parameter @NumberOfFiles is not supported. The number of files has to be evenly divisible by the number of URLs. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles > 32 AND @URL LIKE 's3%' AND @MirrorURL LIKE 's3%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored backups to S3 storage is 32.', 16, 10) + VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored backups to S3 storage is 32. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1618,13 +1630,13 @@ BEGIN IF @MinBackupSizeForMultipleFiles <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinBackupSizeForMultipleFiles is not supported.', 16, 1) + VALUES('The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The value has to be greater than 0. See https://ola.hallengren.com/sql-server-backup.html#MinBackupSizeForMultipleFiles.', 16, 1) END IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @NumberOfFiles IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.', 16, 2) + VALUES('The parameter @MinBackupSizeForMultipleFiles can only be used together with @NumberOfFiles. See https://ola.hallengren.com/sql-server-backup.html#MinBackupSizeForMultipleFiles.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1632,13 +1644,13 @@ BEGIN IF @MaxFileSize <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxFileSize is not supported.', 16, 1) + VALUES('The value for the parameter @MaxFileSize is not supported. The value has to be greater than 0. See https://ola.hallengren.com/sql-server-backup.html#MaxFileSize.', 16, 1) END IF @MaxFileSize IS NOT NULL AND @NumberOfFiles IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameters @MaxFileSize and @NumberOfFiles cannot be used together.', 16, 2) + VALUES('The parameters @MaxFileSize and @NumberOfFiles cannot be used together. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1646,31 +1658,31 @@ BEGIN IF (@BackupSoftware IS NULL AND @CompressionLevelNumeric IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 1) + VALUES('The parameter @CompressionLevelNumeric is only supported with third-party backup software. For SQL Server native backups, use the parameter @CompressionLevel. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevelNumeric.', 16, 1) END IF @BackupSoftware = 'LITESPEED' AND (@CompressionLevelNumeric < 0 OR @CompressionLevelNumeric > 8) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 2) + VALUES('The value for the parameter @CompressionLevelNumeric is not supported. With LiteSpeed for SQL Server, the value has to be between 0 and 8. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevelNumeric.', 16, 1) END IF @BackupSoftware = 'SQLBACKUP' AND (@CompressionLevelNumeric < 0 OR @CompressionLevelNumeric > 4) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 3) + VALUES('The value for the parameter @CompressionLevelNumeric is not supported. With Redgate SQL Backup Pro, the value has to be between 0 and 4. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevelNumeric.', 16, 1) END IF @BackupSoftware = 'SQLSAFE' AND (@CompressionLevelNumeric < 1 OR @CompressionLevelNumeric > 4) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 4) + VALUES('The value for the parameter @CompressionLevelNumeric is not supported. With Idera SQL Safe Backup, the value has to be between 1 and 4. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevelNumeric.', 16, 1) END IF @CompressionLevelNumeric IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 5) + VALUES('The parameter @CompressionLevelNumeric is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevelNumeric.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1678,25 +1690,25 @@ BEGIN IF LEN(@Description) > 255 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Description is not supported.', 16, 1) + VALUES('The value for the parameter @Description is not supported. The maximum length is 255 characters. See https://ola.hallengren.com/sql-server-backup.html#Description.', 16, 1) END IF @BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Description is not supported.', 16, 2) + VALUES('The value for the parameter @Description is not supported. The maximum length with LiteSpeed for SQL Server is 128 characters. See https://ola.hallengren.com/sql-server-backup.html#Description.', 16, 1) END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Description is not supported.', 16, 3) + VALUES('The value for the parameter @Description is not supported. The maximum length with Data Domain Boost is 254 characters. See https://ola.hallengren.com/sql-server-backup.html#Description.', 16, 1) END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @Description LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Description is not supported.', 16, 4) + VALUES('The value for the parameter @Description is not supported. Double quotes (") are not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#Description.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1704,13 +1716,13 @@ BEGIN IF LEN(@BackupSetName) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BackupSetName is not supported.', 16, 1) + VALUES('The value for the parameter @BackupSetName is not supported. The maximum length is 128 characters. See https://ola.hallengren.com/sql-server-backup.html#BackupSetName.', 16, 1) END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @BackupSetName LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BackupSetName is not supported.', 16, 2) + VALUES('The value for the parameter @BackupSetName is not supported. Double quotes (") are not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#BackupSetName.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1718,25 +1730,25 @@ BEGIN IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Threads is not supported.', 16, 1) + VALUES('The parameter @Threads is only supported with LiteSpeed for SQL Server, Redgate SQL Backup Pro and Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#Threads.', 16, 1) END IF @BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Threads is not supported.', 16, 2) + VALUES('The value for the parameter @Threads is not supported. With LiteSpeed for SQL Server, the value has to be between 1 and 32. See https://ola.hallengren.com/sql-server-backup.html#Threads.', 16, 1) END IF @BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Threads is not supported.', 16, 3) + VALUES('The value for the parameter @Threads is not supported. With Redgate SQL Backup Pro, the value has to be between 2 and 32. See https://ola.hallengren.com/sql-server-backup.html#Threads.', 16, 1) END IF @BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Threads is not supported.', 16, 4) + VALUES('The value for the parameter @Threads is not supported. With Idera SQL Safe Backup, the value has to be between 1 and 64. See https://ola.hallengren.com/sql-server-backup.html#Threads.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1744,13 +1756,13 @@ BEGIN IF @Throttle < 1 OR @Throttle > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Throttle is not supported.', 16, 1) + VALUES('The value for the parameter @Throttle is not supported. The value has to be between 1 and 100. See https://ola.hallengren.com/sql-server-backup.html#Throttle.', 16, 1) END IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Throttle is not supported.', 16, 2) + VALUES('The parameter @Throttle is only supported with LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#Throttle.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1758,19 +1770,19 @@ BEGIN IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Encrypt is not supported.', 16, 1) + VALUES('The value for the parameter @Encrypt is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#Encrypt.', 16, 1) END IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@EngineEdition IN(3, 8) OR @EditionID IN(-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Encrypt is not supported.', 16, 2) + VALUES('Backup encryption is not supported in this edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#Encrypt.', 16, 1) END IF @Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Encrypt is not supported.', 16, 3) + VALUES('The value for the parameter @Encrypt is not supported. Encrypted backups are not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#Encrypt.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1778,31 +1790,31 @@ BEGIN 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]) - VALUES('The value for the parameter @EncryptionAlgorithm is not supported.', 16, 1) + VALUES('The value for the parameter @EncryptionAlgorithm is not supported. Supported values for SQL Server native backups are AES_128, AES_192, AES_256 and TRIPLE_DES_3KEY. See https://ola.hallengren.com/sql-server-backup.html#EncryptionAlgorithm.', 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]) - VALUES('The value for the parameter @EncryptionAlgorithm is not supported.', 16, 2) + VALUES('The value for the parameter @EncryptionAlgorithm is not supported. Supported values with LiteSpeed for SQL Server are RC2_40, RC2_56, RC2_112, RC2_128, TRIPLE_DES_3KEY, RC4_128, AES_128, AES_192 and AES_256. See https://ola.hallengren.com/sql-server-backup.html#EncryptionAlgorithm.', 16, 1) 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]) - VALUES('The value for the parameter @EncryptionAlgorithm is not supported.', 16, 3) + VALUES('The value for the parameter @EncryptionAlgorithm is not supported. Supported values with Redgate SQL Backup Pro are AES_128 and AES_256. See https://ola.hallengren.com/sql-server-backup.html#EncryptionAlgorithm.', 16, 1) END IF @BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @EncryptionAlgorithm is not supported.', 16, 4) + VALUES('The value for the parameter @EncryptionAlgorithm is not supported. Supported values with Idera SQL Safe Backup are AES_128 and AES_256. See https://ola.hallengren.com/sql-server-backup.html#EncryptionAlgorithm.', 16, 1) END IF @EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @EncryptionAlgorithm is not supported.', 16, 5) + VALUES('The parameter @EncryptionAlgorithm is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#EncryptionAlgorithm.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1810,25 +1822,25 @@ BEGIN IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ServerCertificate is not supported.', 16, 1) + VALUES('The parameter @ServerCertificate can only be used together with @Encrypt = ''Y'' and SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html#ServerCertificate.', 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]) - VALUES('The value for the parameter @ServerCertificate is not supported.', 16, 2) + VALUES('You need to specify one of the parameters @ServerCertificate and @ServerAsymmetricKey when performing encrypted SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) 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]) - VALUES('The value for the parameter @ServerCertificate is not supported.', 16, 3) + VALUES('You can only specify one of the parameters @ServerCertificate and @ServerAsymmetricKey. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF @ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ServerCertificate is not supported.', 16, 4) + VALUES('The value for the parameter @ServerCertificate is not supported. The certificate does not exist in the master database. See https://ola.hallengren.com/sql-server-backup.html#ServerCertificate.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1836,25 +1848,13 @@ BEGIN IF NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('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]) - VALUES('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]) - VALUES('The value for the parameter @ServerAsymmetricKey is not supported.', 16, 3) + VALUES('The parameter @ServerAsymmetricKey can only be used together with @Encrypt = ''Y'' and SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html#ServerAsymmetricKey.', 16, 1) 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]) - VALUES('The value for the parameter @ServerAsymmetricKey is not supported.', 16, 4) + VALUES('The value for the parameter @ServerAsymmetricKey is not supported. The asymmetric key does not exist in the master database. See https://ola.hallengren.com/sql-server-backup.html#ServerAsymmetricKey.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1862,25 +1862,25 @@ BEGIN IF @EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @EncryptionKey is not supported.', 16, 1) + VALUES('The parameter @EncryptionKey is only supported with third-party backup software. For SQL Server native backups, use @ServerCertificate or @ServerAsymmetricKey. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) END IF @EncryptionKey IS NOT NULL AND @Encrypt = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @EncryptionKey is not supported.', 16, 2) + VALUES('The parameter @EncryptionKey can only be used together with @Encrypt = ''Y''. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) END IF @EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @EncryptionKey is not supported.', 16, 3) + VALUES('You need to specify @EncryptionKey when performing encrypted backups with LiteSpeed for SQL Server, Redgate SQL Backup Pro or Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) END IF @EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @EncryptionKey is not supported.', 16, 4) + VALUES('The parameter @EncryptionKey is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1888,13 +1888,13 @@ BEGIN IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ReadWriteFileGroups is not supported.', 16, 1) + VALUES('The value for the parameter @ReadWriteFileGroups is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#ReadWriteFileGroups.', 16, 1) END IF @ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ReadWriteFileGroups is not supported.', 16, 2) + VALUES('Setting @ReadWriteFileGroups to ''Y'' is not supported for transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#ReadWriteFileGroups.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1902,7 +1902,7 @@ BEGIN IF @OverrideBackupPreference NOT IN('Y','N') OR @OverrideBackupPreference IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @OverrideBackupPreference is not supported.', 16, 1) + VALUES('The value for the parameter @OverrideBackupPreference is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#OverrideBackupPreference.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1910,19 +1910,19 @@ BEGIN IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NoRecovery is not supported.', 16, 1) + VALUES('The value for the parameter @NoRecovery is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#NoRecovery.', 16, 1) END IF @NoRecovery = 'Y' AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NoRecovery is not supported.', 16, 2) + VALUES('Setting @NoRecovery to ''Y'' is only supported for transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#NoRecovery.', 16, 1) END IF @NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NoRecovery is not supported.', 16, 3) + VALUES('Setting @NoRecovery to ''Y'' is not supported with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#NoRecovery.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1930,19 +1930,19 @@ BEGIN IF @URL IS NOT NULL AND @Directory IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @URL is not supported.', 16, 1) + VALUES('The parameters @URL and @Directory cannot be used together. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF @URL IS NOT NULL AND @MirrorDirectory IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @URL is not supported.', 16, 2) + VALUES('The parameters @URL and @MirrorDirectory cannot be used together. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF @URL IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @URL is not supported.', 16, 3) + VALUES('Backup to URL is only supported with SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1950,19 +1950,19 @@ BEGIN IF @Credential IS NOT NULL AND @URL IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Credential is not supported.', 16, 1) + VALUES('The parameter @Credential can only be used together with @URL. See https://ola.hallengren.com/sql-server-backup.html#Credential.', 16, 1) END IF @URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) IN('SHARED ACCESS SIGNATURE','MANAGED IDENTITY','S3 ACCESS KEY')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Credential is not supported.', 16, 2) + VALUES('When backing up to URL, you need to specify @Credential or create a credential with the identity SHARED ACCESS SIGNATURE, MANAGED IDENTITY or S3 ACCESS KEY. See https://ola.hallengren.com/sql-server-backup.html#Credential.', 16, 1) END IF @Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Credential is not supported.', 16, 3) + VALUES('The value for the parameter @Credential is not supported. The credential does not exist. See https://ola.hallengren.com/sql-server-backup.html#Credential.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1970,13 +1970,13 @@ BEGIN IF @MirrorCleanupTime < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorCleanupTime is not supported.', 16, 1) + VALUES('The value for the parameter @MirrorCleanupTime is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-backup.html#MirrorCleanupTime.', 16, 1) END IF @MirrorCleanupTime IS NOT NULL AND @MirrorDirectory IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorCleanupTime is not supported.', 16, 2) + VALUES('The parameter @MirrorCleanupTime can only be used together with @MirrorDirectory. See https://ola.hallengren.com/sql-server-backup.html#MirrorCleanupTime.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1984,7 +1984,7 @@ BEGIN IF @MirrorCleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @MirrorCleanupMode IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorCleanupMode is not supported.', 16, 1) + VALUES('The value for the parameter @MirrorCleanupMode is not supported. Supported values are BEFORE_BACKUP and AFTER_BACKUP. See https://ola.hallengren.com/sql-server-backup.html#MirrorCleanupMode.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1992,25 +1992,25 @@ BEGIN IF @MirrorURL IS NOT NULL AND @Directory IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorURL is not supported.', 16, 1) + VALUES('The parameters @MirrorURL and @Directory cannot be used together. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF @MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorURL is not supported.', 16, 2) + VALUES('The parameters @MirrorURL and @MirrorDirectory cannot be used together. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF @MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorURL is not supported.', 16, 3) + VALUES('Mirrored backup to URL is only supported with SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html#MirrorURL.', 16, 1) END IF @MirrorURL IS NOT NULL AND @URL IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorURL is not supported.', 16, 4) + VALUES('The parameter @MirrorURL can only be used together with @URL. See https://ola.hallengren.com/sql-server-backup.html#MirrorURL.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2018,7 +2018,7 @@ BEGIN IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Updateability is not supported.', 16, 1) + VALUES('The value for the parameter @Updateability is not supported. Supported values are ALL, READ_ONLY and READ_WRITE. See https://ola.hallengren.com/sql-server-backup.html#Updateability.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2026,13 +2026,13 @@ BEGIN IF @AdaptiveCompression NOT IN('SIZE','SPEED') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AdaptiveCompression is not supported.', 16, 1) + VALUES('The value for the parameter @AdaptiveCompression is not supported. Supported values are SIZE and SPEED. See https://ola.hallengren.com/sql-server-backup.html#AdaptiveCompression.', 16, 1) END IF @AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AdaptiveCompression is not supported.', 16, 2) + VALUES('The parameter @AdaptiveCompression is only supported with LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#AdaptiveCompression.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2040,19 +2040,19 @@ BEGIN IF @MinModificationLevel <= 0 OR @MinModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinModificationLevel is not supported.', 16, 1) + VALUES('The value for the parameter @MinModificationLevel is not supported. The value has to be greater than 0 and less than or equal to 100. See https://ola.hallengren.com/sql-server-backup.html#MinModificationLevel.', 16, 1) END IF @MinModificationLevel IS NOT NULL AND @ChangeBackupType = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 2) + VALUES('The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''. See https://ola.hallengren.com/sql-server-backup.html#MinModificationLevel.', 16, 1) END IF @MinModificationLevel IS NOT NULL AND @BackupType NOT IN('DIFF','LOG') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @MinModificationLevel can only be used for differential and transaction log backups.', 16, 3) + VALUES('The parameter @MinModificationLevel can only be used for differential and transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#MinModificationLevel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2060,13 +2060,13 @@ BEGIN IF @MinDatabaseSizeForDifferentialBackup <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinDatabaseSizeForDifferentialBackup is not supported.', 16, 1) + VALUES('The value for the parameter @MinDatabaseSizeForDifferentialBackup is not supported. The value has to be greater than 0. See https://ola.hallengren.com/sql-server-backup.html#MinDatabaseSizeForDifferentialBackup.', 16, 1) END IF @MinDatabaseSizeForDifferentialBackup IS NOT NULL AND @BackupType <> 'DIFF' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @MinDatabaseSizeForDifferentialBackup can only be used for differential backups.', 16, 2) + VALUES('The parameter @MinDatabaseSizeForDifferentialBackup can only be used for differential backups. See https://ola.hallengren.com/sql-server-backup.html#MinDatabaseSizeForDifferentialBackup.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2074,7 +2074,7 @@ BEGIN IF @MinLogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinLogSizeSinceLastLogBackup is not supported.', 16, 1) + VALUES('The parameter @MinLogSizeSinceLastLogBackup can only be used for transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#MinLogSizeSinceLastLogBackup.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2082,7 +2082,7 @@ BEGIN IF @MinTimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinTimeSinceLastLogBackup is not supported.', 16, 1) + VALUES('The parameter @MinTimeSinceLastLogBackup can only be used for transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#MinTimeSinceLastLogBackup.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2090,7 +2090,7 @@ BEGIN IF (@MinTimeSinceLastLogBackup IS NOT NULL AND @MinLogSizeSinceLastLogBackup IS NULL) OR (@MinTimeSinceLastLogBackup IS NULL AND @MinLogSizeSinceLastLogBackup IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameters @MinTimeSinceLastLogBackup and @MinLogSizeSinceLastLogBackup can only be used together.', 16, 1) + VALUES('The parameters @MinTimeSinceLastLogBackup and @MinLogSizeSinceLastLogBackup can only be used together. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2098,19 +2098,19 @@ BEGIN IF @DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostHost is not supported.', 16, 1) + VALUES('The parameter @DataDomainBoostHost can only be used together with @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostHost.', 16, 1) END IF @DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostHost is not supported.', 16, 2) + VALUES('You need to specify @DataDomainBoostHost when @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostHost.', 16, 1) END IF @DataDomainBoostHost LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostHost is not supported.', 16, 3) + VALUES('The value for the parameter @DataDomainBoostHost is not supported. Double quotes (") are not supported. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostHost.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2118,19 +2118,19 @@ BEGIN IF @DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostUser is not supported.', 16, 1) + VALUES('The parameter @DataDomainBoostUser can only be used together with @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostUser.', 16, 1) END IF @DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostUser is not supported.', 16, 2) + VALUES('You need to specify @DataDomainBoostUser when @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostUser.', 16, 1) END IF @DataDomainBoostUser LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostUser is not supported.', 16, 3) + VALUES('The value for the parameter @DataDomainBoostUser is not supported. Double quotes (") are not supported. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostUser.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2138,19 +2138,19 @@ BEGIN IF @DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 1) + VALUES('The parameter @DataDomainBoostDevicePath can only be used together with @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostDevicePath.', 16, 1) END IF @DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 2) + VALUES('You need to specify @DataDomainBoostDevicePath when @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostDevicePath.', 16, 1) END IF @DataDomainBoostDevicePath LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 3) + VALUES('The value for the parameter @DataDomainBoostDevicePath is not supported. Double quotes (") are not supported. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostDevicePath.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2158,13 +2158,13 @@ BEGIN IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 1) + VALUES('The parameter @DataDomainBoostLockboxPath can only be used together with @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostLockboxPath.', 16, 1) END IF @DataDomainBoostLockboxPath LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 2) + VALUES('The value for the parameter @DataDomainBoostLockboxPath is not supported. Double quotes (") are not supported. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostLockboxPath.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2172,13 +2172,13 @@ BEGIN IF @DataDomainBoostNoOutputTable NOT IN('Y','N') OR @DataDomainBoostNoOutputTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 1) + VALUES('The value for the parameter @DataDomainBoostNoOutputTable is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostNoOutputTable.', 16, 1) END IF @DataDomainBoostNoOutputTable = 'Y' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 2) + VALUES('The parameter @DataDomainBoostNoOutputTable can only be used together with @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostNoOutputTable.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2186,7 +2186,7 @@ BEGIN IF @DirectoryStructure = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DirectoryStructure is not supported.', 16, 1) + VALUES('The value for the parameter @DirectoryStructure is not supported. The value cannot be an empty string. See https://ola.hallengren.com/sql-server-backup.html#DirectoryStructure.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2194,7 +2194,7 @@ BEGIN IF @AvailabilityGroupDirectoryStructure = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.', 16, 1) + VALUES('The value for the parameter @AvailabilityGroupDirectoryStructure is not supported. The value cannot be an empty string. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupDirectoryStructure.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2202,7 +2202,7 @@ BEGIN IF @DirectoryStructureCase NOT IN('LOWER','UPPER') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DirectoryStructureCase is not supported.', 16, 1) + VALUES('The value for the parameter @DirectoryStructureCase is not supported. Supported values are LOWER and UPPER. See https://ola.hallengren.com/sql-server-backup.html#DirectoryStructureCase.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2210,37 +2210,37 @@ BEGIN IF @FileName IS NULL OR @FileName = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileName is not supported.', 16, 1) + VALUES('The value for the parameter @FileName is not supported. The value cannot be NULL or empty. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) END IF @FileName NOT LIKE '%.{FileExtension}' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileName is not supported.', 16, 2) + VALUES('The value for the parameter @FileName is not supported. The file name has to end with .{FileExtension}. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) END IF (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileName is not supported.', 16, 3) + VALUES('The value for the parameter @FileName is not supported. The token {FileNumber} is required when @NumberOfFiles is greater than 1. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) END IF @FileName LIKE '%{DirectorySeparator}%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileName is not supported.', 16, 4) + VALUES('The value for the parameter @FileName is not supported. The token {DirectorySeparator} cannot be used in the file name. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) END IF @FileName LIKE '%/%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileName is not supported.', 16, 5) + VALUES('The value for the parameter @FileName is not supported. The character / cannot be used in the file name. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) END IF @FileName LIKE '%\%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileName is not supported.', 16, 6) + VALUES('The value for the parameter @FileName is not supported. The character \ cannot be used in the file name. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2248,43 +2248,43 @@ BEGIN IF (@IsHadrEnabled = 1 AND @AvailabilityGroupFileName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 1) + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported. The value cannot be NULL when the server is part of an availability group. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END IF @AvailabilityGroupFileName = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 2) + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported. The value cannot be an empty string. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END IF @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 3) + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported. The file name has to end with .{FileExtension}. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END IF (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 4) + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported. The token {FileNumber} is required when @NumberOfFiles is greater than 1. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END IF @AvailabilityGroupFileName LIKE '%{DirectorySeparator}%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 5) + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported. The token {DirectorySeparator} cannot be used in the file name. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END IF @AvailabilityGroupFileName LIKE '%/%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 6) + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported. The character / cannot be used in the file name. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END IF @AvailabilityGroupFileName LIKE '%\%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 7) + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported. The character \ cannot be used in the file name. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2292,7 +2292,7 @@ BEGIN IF @FileNameCase NOT IN('LOWER','UPPER') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileNameCase is not supported.', 16, 1) + VALUES('The value for the parameter @FileNameCase is not supported. Supported values are LOWER and UPPER. See https://ola.hallengren.com/sql-server-backup.html#FileNameCase.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2300,7 +2300,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(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @DirectoryStructure contains one or more tokens that are not supported.', 16, 1) + VALUES('The parameter @DirectoryStructure contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#DirectoryStructure.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2308,7 +2308,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(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS AvailabilityGroupDirectoryStructure) Temp WHERE AvailabilityGroupDirectoryStructure LIKE '%{%' OR AvailabilityGroupDirectoryStructure LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.', 16, 1) + VALUES('The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupDirectoryStructure.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2316,7 +2316,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(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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]) - VALUES('The parameter @FileName contains one or more tokens that are not supported.', 16, 1) + VALUES('The parameter @FileName contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2324,7 +2324,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(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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]) - VALUES('The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.', 16, 1) + VALUES('The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2332,7 +2332,7 @@ BEGIN IF @TokenTimezone NOT IN('LOCAL','UTC') OR @TokenTimezone IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @TokenTimezone is not supported.', 16, 1) + VALUES('The value for the parameter @TokenTimezone is not supported. Supported values are LOCAL and UTC. See https://ola.hallengren.com/sql-server-backup.html#TokenTimezone.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2340,7 +2340,7 @@ BEGIN IF @FileExtensionFull LIKE '%.%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileExtensionFull is not supported.', 16, 1) + VALUES('The value for the parameter @FileExtensionFull is not supported. Specify the file extension without a leading period. See https://ola.hallengren.com/sql-server-backup.html#FileExtensionFull.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2348,7 +2348,7 @@ BEGIN IF @FileExtensionDiff LIKE '%.%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileExtensionDiff is not supported.', 16, 1) + VALUES('The value for the parameter @FileExtensionDiff is not supported. Specify the file extension without a leading period. See https://ola.hallengren.com/sql-server-backup.html#FileExtensionDiff.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2356,7 +2356,7 @@ BEGIN IF @FileExtensionLog LIKE '%.%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileExtensionLog is not supported.', 16, 1) + VALUES('The value for the parameter @FileExtensionLog is not supported. Specify the file extension without a leading period. See https://ola.hallengren.com/sql-server-backup.html#FileExtensionLog.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2364,25 +2364,25 @@ BEGIN IF @Init NOT IN('Y','N') OR @Init IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Init is not supported.', 16, 1) + VALUES('The value for the parameter @Init is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#Init.', 16, 1) END IF @Init = 'Y' AND @BackupType = 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Init is not supported.', 16, 2) + VALUES('Setting @Init to ''Y'' is not supported for transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#Init.', 16, 1) END IF @Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Init is not supported.', 16, 3) + VALUES('Setting @Init to ''Y'' is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#Init.', 16, 1) END IF @Init = 'Y' AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Init is not supported.', 16, 4) + VALUES('Setting @Init to ''Y'' is not supported when backing up to S3-compatible storage. See https://ola.hallengren.com/sql-server-backup.html#Init.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2390,19 +2390,19 @@ BEGIN IF @Format NOT IN('Y','N') OR @Format IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Format is not supported.', 16, 1) + VALUES('The value for the parameter @Format is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#Format.', 16, 1) END IF @Format = 'Y' AND @BackupType = 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Format is not supported.', 16, 2) + VALUES('Setting @Format to ''Y'' is not supported for transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#Format.', 16, 1) END IF @Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Format is not supported.', 16, 3) + VALUES('Setting @Format to ''Y'' is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#Format.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2410,25 +2410,19 @@ BEGIN IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ObjectLevelRecoveryMap is not supported.', 16, 1) - END - - IF @ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ObjectLevelRecoveryMap is not supported.', 16, 2) + VALUES('The value for the parameter @ObjectLevelRecoveryMap is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#ObjectLevelRecoveryMap.', 16, 1) END - IF @ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED' + IF @ObjectLevelRecoveryMap = 'Y' AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ObjectLevelRecoveryMap is not supported.', 16, 3) + VALUES('Setting @ObjectLevelRecoveryMap to ''Y'' is only supported with LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#ObjectLevelRecoveryMap.', 16, 1) END IF @ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ObjectLevelRecoveryMap is not supported.', 16, 4) + VALUES('Setting @ObjectLevelRecoveryMap to ''Y'' is not supported for transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#ObjectLevelRecoveryMap.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2436,7 +2430,7 @@ BEGIN IF @ExcludeLogShippedFromLogBackup NOT IN('Y','N') OR @ExcludeLogShippedFromLogBackup IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExcludeLogShippedFromLogBackup is not supported.', 16, 1) + VALUES('The value for the parameter @ExcludeLogShippedFromLogBackup is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#ExcludeLogShippedFromLogBackup.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2444,13 +2438,13 @@ BEGIN IF @ExcludeSeedingFromLogBackup NOT IN('Y','N') OR @ExcludeSeedingFromLogBackup IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExcludeSeedingFromLogBackup is not supported.', 16, 1) + VALUES('The value for the parameter @ExcludeSeedingFromLogBackup is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#ExcludeSeedingFromLogBackup.', 16, 1) END IF @ExcludeSeedingFromLogBackup = 'Y' AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @ExcludeSeedingFromLogBackup can only be used for log backups.', 16, 2) + VALUES('The parameter @ExcludeSeedingFromLogBackup can only be used for log backups. See https://ola.hallengren.com/sql-server-backup.html#ExcludeSeedingFromLogBackup.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2458,7 +2452,7 @@ BEGIN IF @DirectoryCheck NOT IN('Y','N') OR @DirectoryCheck IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DirectoryCheck is not supported.', 16, 1) + VALUES('The value for the parameter @DirectoryCheck is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#DirectoryCheck.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2466,7 +2460,7 @@ BEGIN IF @BackupOptions IS NOT NULL AND NOT EXISTS(SELECT * FROM @URLs WHERE DirectoryPath LIKE 's3://%/%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BackupOptions is not supported.', 16, 1) + VALUES('The parameter @BackupOptions can only be used when backing up to S3-compatible storage. See https://ola.hallengren.com/sql-server-backup.html#BackupOptions.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2474,7 +2468,7 @@ BEGIN IF @Stats <= 0 OR @Stats > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Stats is not supported.', 16, 1) + VALUES('The value for the parameter @Stats is not supported. The value has to be between 1 and 100. See https://ola.hallengren.com/sql-server-backup.html#Stats.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2482,7 +2476,7 @@ BEGIN IF @ExpireDate IS NOT NULL AND @BackupSoftware <> 'LITESPEED' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExpireDate is not supported.', 16, 1) + VALUES('The parameter @ExpireDate is only supported with SQL Server native backups and LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#ExpireDate.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2490,13 +2484,13 @@ BEGIN IF @RetainDays < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @RetainDays is not supported.', 16, 1) + VALUES('The value for the parameter @RetainDays is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-backup.html#RetainDays.', 16, 1) END IF @RetainDays IS NOT NULL AND @BackupSoftware <> 'LITESPEED' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @RetainDays is not supported.', 16, 2) + VALUES('The parameter @RetainDays is only supported with SQL Server native backups and LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#RetainDays.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2504,7 +2498,7 @@ BEGIN IF @AllowNonCopyOnlyBackupsOnForwarder NOT IN('Y','N') OR @AllowNonCopyOnlyBackupsOnForwarder IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AllowNonCopyOnlyBackupsOnForwarder is not supported.', 16, 1) + VALUES('The value for the parameter @AllowNonCopyOnlyBackupsOnForwarder is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#AllowNonCopyOnlyBackupsOnForwarder.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2512,7 +2506,7 @@ BEGIN IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StringDelimiter is not supported.', 16, 1) + VALUES('The value for the parameter @StringDelimiter is not supported. The value has to be exactly one character. See https://ola.hallengren.com/sql-server-backup.html#StringDelimiter.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2520,13 +2514,13 @@ BEGIN 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, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 1) + VALUES('The value for the parameter @DatabaseOrder is not supported. Supported values are DATABASE_NAME_ASC, DATABASE_NAME_DESC, DATABASE_SIZE_ASC, DATABASE_SIZE_DESC, LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC and LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC. See https://ola.hallengren.com/sql-server-backup.html#DatabaseOrder.', 16, 1) END IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 2) + VALUES('The parameter @DatabaseOrder is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-backup.html#DatabaseOrder.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2534,13 +2528,13 @@ BEGIN IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) + VALUES('The value for the parameter @DatabasesInParallel is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#DatabasesInParallel.', 16, 1) END IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 2) + VALUES('The parameter @DatabasesInParallel is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-backup.html#DatabasesInParallel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2548,7 +2542,7 @@ BEGIN IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) + VALUES('The value for the parameter @LogToTable is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#LogToTable.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2556,15 +2550,7 @@ BEGIN IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Execute is not supported.', 16, 1) - END - - ---------------------------------------------------------------------------------------------------- - - IF EXISTS(SELECT * FROM @Errors) - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The documentation is available at https://ola.hallengren.com/sql-server-backup.html.', 16, 1) + VALUES('The value for the parameter @Execute is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#Execute.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2580,7 +2566,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-backup.html#Databases.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') @@ -2592,7 +2578,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroups.', 10, 1) END ---------------------------------------------------------------------------------------------------- @@ -2602,7 +2588,7 @@ BEGIN IF UPPER(@@SERVERNAME) <> UPPER(@ServerName) AND @IsHadrEnabled = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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) + VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @IsClustered = 0 THEN 'https://learn.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN @IsClustered = 1 THEN 'https://learn.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16, 1) END ---------------------------------------------------------------------------------------------------- diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index d83a0553..61446be7 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 16:00:55 //-- + --// Version: 2026-08-08 22:31:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -338,13 +338,13 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1) + VALUES('ANSI_NULLS has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1) + VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-integrity-check.html.', 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') @@ -368,19 +368,19 @@ BEGIN 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, [State]) - VALUES('The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1) + VALUES('The table Queue is missing. It is required when @DatabasesInParallel = ''Y''. 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, [State]) - VALUES('The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) + VALUES('The table QueueDatabase is missing. It is required when @DatabasesInParallel = ''Y''. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) END IF @@TRANCOUNT <> 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The transaction count is not 0.', 16, 1) + VALUES('The stored procedure cannot be executed inside a transaction. The transaction count (@@TRANCOUNT) has to be 0. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -504,7 +504,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DATALENGTH(DatabaseName) = 0)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Databases is not supported.', 16, 1) + VALUES('The value for the parameter @Databases is not supported. The value could not be parsed into a list of databases. See https://ola.hallengren.com/sql-server-integrity-check.html#Databases.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -596,22 +596,28 @@ 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 @IsHadrEnabled = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroups is not supported.', 16, 1) + VALUES('The value for the parameter @AvailabilityGroups is not supported. The value could not be parsed into a list of availability groups. See https://ola.hallengren.com/sql-server-integrity-check.html#AvailabilityGroups.', 16, 1) + END + + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameter @AvailabilityGroups can only be used when availability groups are enabled on the instance. See https://ola.hallengren.com/sql-server-integrity-check.html#AvailabilityGroups.', 16, 1) END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2) + VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -750,31 +756,31 @@ BEGIN IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 1) + VALUES('The value for the parameter @CheckCommands is not supported. Supported values are CHECKDB, CHECKFILEGROUP, CHECKALLOC, CHECKTABLE and CHECKCATALOG. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) END IF EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 2) + VALUES('The value for the parameter @CheckCommands is not supported. The same check command has been specified more than once. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) END IF NOT EXISTS (SELECT * FROM @SelectedCheckCommands) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 3) + VALUES('The value for the parameter @CheckCommands is not supported. The value cannot be NULL or empty. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) 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]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 4) + VALUES('The value for the parameter @CheckCommands is not supported. CHECKDB cannot be combined with CHECKFILEGROUP, CHECKALLOC, CHECKTABLE or CHECKCATALOG. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) 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]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 5) + VALUES('The value for the parameter @CheckCommands is not supported. CHECKFILEGROUP cannot be combined with CHECKALLOC or CHECKTABLE. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -782,7 +788,7 @@ BEGIN IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @PhysicalOnly is not supported.', 16, 1) + VALUES('The value for the parameter @PhysicalOnly is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#PhysicalOnly.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -790,13 +796,13 @@ BEGIN IF @DataPurity NOT IN ('Y','N') OR @DataPurity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataPurity is not supported.', 16, 1) + VALUES('The value for the parameter @DataPurity is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#DataPurity.', 16, 1) END IF @PhysicalOnly = 'Y' AND @DataPurity = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameters @PhysicalOnly and @DataPurity cannot be used together.', 16, 2) + VALUES('The parameters @PhysicalOnly and @DataPurity cannot be used together. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -804,7 +810,7 @@ BEGIN IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NoIndex is not supported.', 16, 1) + VALUES('The value for the parameter @NoIndex is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#NoIndex.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -812,13 +818,13 @@ BEGIN IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExtendedLogicalChecks is not supported.', 16, 1) + VALUES('The value for the parameter @ExtendedLogicalChecks is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#ExtendedLogicalChecks.', 16, 1) END IF @PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameters @PhysicalOnly and @ExtendedLogicalChecks cannot be used together.', 16, 2) + VALUES('The parameters @PhysicalOnly and @ExtendedLogicalChecks cannot be used together. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -826,7 +832,7 @@ BEGIN IF @NoInformationalMessages NOT IN ('Y','N') OR @NoInformationalMessages IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NoInformationalMessages is not supported.', 16, 1) + VALUES('The value for the parameter @NoInformationalMessages is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#NoInformationalMessages.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -834,7 +840,7 @@ BEGIN IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @TabLock is not supported.', 16, 1) + VALUES('The value for the parameter @TabLock is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#TabLock.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -842,19 +848,19 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileGroups is not supported.', 16, 1) + VALUES('The value for the parameter @FileGroups is not supported. The value contains one or more items that could not be parsed. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 16, 1) END IF @FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileGroups is not supported.', 16, 2) + VALUES('The value for the parameter @FileGroups is not supported. The value could not be parsed into a list of filegroups. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 16, 1) END IF @FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileGroups is not supported.', 16, 3) + VALUES('The parameter @FileGroups can only be used together with @CheckCommands = ''CHECKFILEGROUP''. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -862,19 +868,19 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Objects is not supported.', 16, 1) + VALUES('The value for the parameter @Objects is not supported. The value contains one or more items that could not be parsed. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 16, 1) END IF (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Objects is not supported.', 16, 2) + VALUES('The value for the parameter @Objects is not supported. The value could not be parsed into a list of objects. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 16, 1) END IF (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Objects is not supported.', 16, 3) + VALUES('The parameter @Objects can only be used together with @CheckCommands = ''CHECKTABLE''. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -882,7 +888,7 @@ BEGIN IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxDOP is not supported.', 16, 1) + VALUES('The value for the parameter @MaxDOP is not supported. The value has to be between 0 and 64. See https://ola.hallengren.com/sql-server-integrity-check.html#MaxDOP.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -890,7 +896,7 @@ BEGIN IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupReplicas is not supported.', 16, 1) + VALUES('The value for the parameter @AvailabilityGroupReplicas is not supported. Supported values are ALL, PRIMARY, SECONDARY and PREFERRED_BACKUP_REPLICA. See https://ola.hallengren.com/sql-server-integrity-check.html#AvailabilityGroupReplicas.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -898,7 +904,7 @@ BEGIN IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Updateability is not supported.', 16, 1) + VALUES('The value for the parameter @Updateability is not supported. Supported values are ALL, READ_ONLY and READ_WRITE. See https://ola.hallengren.com/sql-server-integrity-check.html#Updateability.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -906,21 +912,15 @@ BEGIN IF @TimeLimit < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @TimeLimit is not supported.', 16, 1) + VALUES('The value for the parameter @TimeLimit is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-integrity-check.html#TimeLimit.', 16, 1) END ---------------------------------------------------------------------------------------------------- - IF @LockTimeout < 0 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported.', 16, 1) - END - - IF @LockTimeout > 86400 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported.', 16, 2) + IF @LockTimeout < 0 OR @LockTimeout > 86400 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @LockTimeout is not supported. The value has to be between 0 and 86400. See https://ola.hallengren.com/sql-server-integrity-check.html#LockTimeout.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -928,7 +928,7 @@ BEGIN IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) + VALUES('The value for the parameter @LockMessageSeverity is not supported. Supported values are 10 and 16. See https://ola.hallengren.com/sql-server-integrity-check.html#LockMessageSeverity.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -936,7 +936,7 @@ BEGIN IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StringDelimiter is not supported.', 16, 1) + VALUES('The value for the parameter @StringDelimiter is not supported. The value has to be exactly one character. See https://ola.hallengren.com/sql-server-integrity-check.html#StringDelimiter.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -944,31 +944,31 @@ BEGIN 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') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 1) + VALUES('The value for the parameter @DatabaseOrder is not supported. Supported values are 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 and REPLICA_LAST_GOOD_CHECK_DESC. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) END IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 14.03029 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported. DATABASEPROPERTYEX(''DatabaseName'', ''LastGoodCheckDbTime'') is not available in this version of SQL Server.', 16, 2) + VALUES('The value for the parameter @DatabaseOrder is not supported. DATABASEPROPERTYEX(''DatabaseName'', ''LastGoodCheckDbTime'') is not available in this version of SQL Server. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) END IF @DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @LogToTable = ''Y''.', 16, 3) + VALUES('The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @LogToTable = ''Y''. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) 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]) - VALUES('The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @CheckCommands = ''CHECKDB''.', 16, 4) + VALUES('The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @CheckCommands = ''CHECKDB''. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) END IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported. This parameter is not supported in Azure SQL Database.', 16, 5) + VALUES('The parameter @DatabaseOrder is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -976,13 +976,13 @@ BEGIN IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) + VALUES('The value for the parameter @DatabasesInParallel is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabasesInParallel.', 16, 1) END IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported. This parameter is not supported in Azure SQL Database.', 16, 2) + VALUES('The parameter @DatabasesInParallel is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabasesInParallel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -990,7 +990,7 @@ BEGIN IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) + VALUES('The value for the parameter @LogToTable is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#LogToTable.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -998,15 +998,7 @@ BEGIN IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Execute is not supported.', 16, 1) - END - - ---------------------------------------------------------------------------------------------------- - - IF EXISTS(SELECT * FROM @Errors) - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) + VALUES('The value for the parameter @Execute is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#Execute.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1022,7 +1014,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#Databases.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1034,7 +1026,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @FileGroups parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @FileGroups parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1046,7 +1038,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @Objects parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @Objects parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') @@ -1058,7 +1050,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#AvailabilityGroups.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1071,7 +1063,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1084,7 +1076,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 10, 1) END ---------------------------------------------------------------------------------------------------- @@ -1094,7 +1086,7 @@ BEGIN IF UPPER(@@SERVERNAME) <> UPPER(@ServerName) AND @IsHadrEnabled = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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) + VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @IsClustered = 0 THEN 'https://learn.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN @IsClustered = 1 THEN 'https://learn.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16, 1) END ---------------------------------------------------------------------------------------------------- diff --git a/IndexOptimize.sql b/IndexOptimize.sql index ca51b3c0..672532e4 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 16:00:55 //-- + --// Version: 2026-08-08 22:31:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -517,13 +517,13 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1) + VALUES('ANSI_NULLS has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1) + VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 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') @@ -547,19 +547,19 @@ BEGIN 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, [State]) - VALUES('The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1) + VALUES('The table Queue is missing. It is required when @DatabasesInParallel = ''Y''. 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, [State]) - VALUES('The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) + VALUES('The table QueueDatabase is missing. It is required when @DatabasesInParallel = ''Y''. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) END IF @@TRANCOUNT <> 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The transaction count is not 0.', 16, 1) + VALUES('The stored procedure cannot be executed inside a transaction. The transaction count (@@TRANCOUNT) has to be 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -682,7 +682,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DATALENGTH(DatabaseName) = 0)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Databases is not supported.', 16, 1) + VALUES('The value for the parameter @Databases is not supported. The value could not be parsed into a list of databases. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Databases.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -774,22 +774,28 @@ 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 @IsHadrEnabled = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroups is not supported.', 16, 1) + VALUES('The value for the parameter @AvailabilityGroups is not supported. The value could not be parsed into a list of availability groups. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#AvailabilityGroups.', 16, 1) + END + + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameter @AvailabilityGroups can only be used when availability groups are enabled on the instance. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#AvailabilityGroups.', 16, 1) END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2) + VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -927,13 +933,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLow is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationLow is not supported. Supported values are INDEX_REBUILD_ONLINE, INDEX_REBUILD_OFFLINE and INDEX_REORGANIZE. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLow.', 16, 1) END IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLow is not supported.', 16, 2) + VALUES('The value for the parameter @FragmentationLow is not supported. The same action has been specified more than once. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLow.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -941,13 +947,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationMedium is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationMedium is not supported. Supported values are INDEX_REBUILD_ONLINE, INDEX_REBUILD_OFFLINE and INDEX_REORGANIZE. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationMedium.', 16, 1) END IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationMedium is not supported.', 16, 2) + VALUES('The value for the parameter @FragmentationMedium is not supported. The same action has been specified more than once. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationMedium.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -955,13 +961,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'High' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationHigh is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationHigh is not supported. Supported values are INDEX_REBUILD_ONLINE, INDEX_REBUILD_OFFLINE and INDEX_REORGANIZE. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationHigh.', 16, 1) END IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationHigh is not supported.', 16, 2) + VALUES('The value for the parameter @FragmentationHigh is not supported. The same action has been specified more than once. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationHigh.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -969,7 +975,7 @@ BEGIN IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel1 is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationLevel1 is not supported. The value has to be greater than 0 and less than 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLevel1.', 16, 1) END @@ -978,7 +984,7 @@ BEGIN IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel2 is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationLevel2 is not supported. The value has to be greater than 0 and less than 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLevel2.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -986,7 +992,7 @@ BEGIN IF @FragmentationLevel2 <= @FragmentationLevel1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel2 has to be greater than the value for @FragmentationLevel1.', 16, 1) + VALUES('The value for the parameter @FragmentationLevel2 has to be greater than the value for @FragmentationLevel1. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLevel2.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -994,7 +1000,7 @@ BEGIN IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinNumberOfPages is not supported.', 16, 1) + VALUES('The value for the parameter @MinNumberOfPages is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MinNumberOfPages.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1002,7 +1008,7 @@ BEGIN IF @MaxNumberOfPages < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxNumberOfPages is not supported.', 16, 1) + VALUES('The value for the parameter @MaxNumberOfPages is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MaxNumberOfPages.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1010,7 +1016,7 @@ BEGIN IF @MinNumberOfPages > @MaxNumberOfPages BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxNumberOfPages has to be greater than or equal to the value for @MinNumberOfPages.', 16, 1) + VALUES('The value for the parameter @MaxNumberOfPages has to be greater than or equal to the value for @MinNumberOfPages. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MaxNumberOfPages.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1018,7 +1024,7 @@ BEGIN IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @SortInTempdb is not supported.', 16, 1) + VALUES('The value for the parameter @SortInTempdb is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#SortInTempdb.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1026,7 +1032,7 @@ BEGIN IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxDOP is not supported.', 16, 1) + VALUES('The value for the parameter @MaxDOP is not supported. The value has to be between 0 and 64. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MaxDOP.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1034,7 +1040,7 @@ BEGIN IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FillFactor is not supported.', 16, 1) + VALUES('The value for the parameter @FillFactor is not supported. The value has to be between 1 and 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FillFactor.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1042,7 +1048,7 @@ BEGIN IF @PadIndex NOT IN('Y','N') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @PadIndex is not supported.', 16, 1) + VALUES('The value for the parameter @PadIndex is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#PadIndex.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1050,7 +1056,7 @@ BEGIN IF @DataCompression NOT IN('NONE', 'PAGE', 'ROW') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataCompression is not supported.', 16, 1) + VALUES('The value for the parameter @DataCompression is not supported. Supported values are NONE, PAGE and ROW. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DataCompression.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1058,13 +1064,13 @@ BEGIN IF @WaitAtLowPriorityMaxDuration < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1) + VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#WaitAtLowPriorityMaxDuration.', 16, 1) END IF @WaitAtLowPriorityAbortAfterWait = 'SELF' AND @WaitAtLowPriorityMaxDuration = 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 2) + VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported. The value has to be greater than 0 when @WaitAtLowPriorityAbortAfterWait = ''SELF''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#WaitAtLowPriorityMaxDuration.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1072,7 +1078,7 @@ BEGIN IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16, 1) + VALUES('The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported. Supported values are NONE, SELF and BLOCKERS. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#WaitAtLowPriorityAbortAfterWait.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1080,7 +1086,7 @@ BEGIN 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]) - VALUES('The parameters @WaitAtLowPriorityMaxDuration and @WaitAtLowPriorityAbortAfterWait can only be used together.', 16, 1) + VALUES('The parameters @WaitAtLowPriorityMaxDuration and @WaitAtLowPriorityAbortAfterWait can only be used together. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1088,13 +1094,13 @@ BEGIN IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Resumable is not supported.', 16, 1) + VALUES('The value for the parameter @Resumable is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Resumable.', 16, 1) END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 2) + VALUES('You can only specify one of the parameters @Resumable and @SortInTempdb. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1102,7 +1108,7 @@ BEGIN IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LOBCompaction is not supported.', 16, 1) + VALUES('The value for the parameter @LOBCompaction is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#LOBCompaction.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1110,7 +1116,7 @@ BEGIN IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @UpdateStatistics is not supported.', 16, 1) + VALUES('The value for the parameter @UpdateStatistics is not supported. Supported values are ALL, COLUMNS and INDEX. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#UpdateStatistics.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1118,7 +1124,7 @@ BEGIN IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @OnlyModifiedStatistics is not supported.', 16, 1) + VALUES('The value for the parameter @OnlyModifiedStatistics is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#OnlyModifiedStatistics.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1126,7 +1132,7 @@ BEGIN IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsModificationLevel is not supported.', 16, 1) + VALUES('The value for the parameter @StatisticsModificationLevel is not supported. The value has to be greater than 0 and less than or equal to 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsModificationLevel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1134,7 +1140,7 @@ BEGIN IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.', 16, 1) + VALUES('You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1142,7 +1148,7 @@ BEGIN IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsSample is not supported.', 16, 1) + VALUES('The value for the parameter @StatisticsSample is not supported. The value has to be between 1 and 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsSample.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1150,25 +1156,25 @@ BEGIN IF @StatisticsPersistSample NOT IN('Y','N') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsPersistSample is not supported.', 16, 1) + VALUES('The value for the parameter @StatisticsPersistSample is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsPersistSample.', 16, 1) END IF @StatisticsPersistSample IS NOT NULL AND @StatisticsSample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @StatisticsPersistSample can only be used together with @StatisticsSample.', 16, 2) + VALUES('The parameter @StatisticsPersistSample can only be used together with @StatisticsSample. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsPersistSample.', 16, 1) END IF @StatisticsPersistSample IS NOT NULL AND @StatisticsResample = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3) + VALUES('The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.03006 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsPersistSample is not supported.', 16, 4) + VALUES('The value for the parameter @StatisticsPersistSample is not supported. PERSIST_SAMPLE_PERCENT is not supported in this version of SQL Server. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsPersistSample.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1176,13 +1182,13 @@ BEGIN IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsResample is not supported.', 16, 1) + VALUES('The value for the parameter @StatisticsResample is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsResample.', 16, 1) END IF @StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsResample is not supported.', 16, 2) + VALUES('Setting @StatisticsResample to ''Y'' cannot be combined with @StatisticsSample. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsResample.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1190,7 +1196,7 @@ BEGIN IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @PartitionLevel is not supported.', 16, 1) + VALUES('The value for the parameter @PartitionLevel is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#PartitionLevel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1198,7 +1204,7 @@ BEGIN IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MSShippedObjects is not supported.', 16, 1) + VALUES('The value for the parameter @MSShippedObjects is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MSShippedObjects.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1206,13 +1212,13 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Indexes is not supported.', 16, 1) + VALUES('The value for the parameter @Indexes is not supported. The value contains one or more items that could not be parsed. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Indexes.', 16, 1) END IF @Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Indexes is not supported.', 16, 2) + VALUES('The value for the parameter @Indexes is not supported. The value could not be parsed into a list of indexes. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Indexes.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1220,35 +1226,23 @@ BEGIN IF @TimeLimit < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @TimeLimit is not supported.', 16, 1) + VALUES('The value for the parameter @TimeLimit is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#TimeLimit.', 16, 1) END ---------------------------------------------------------------------------------------------------- - IF @Delay < 0 + IF @Delay < 0 OR @Delay >= 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Delay is not supported.', 16, 1) - END - - IF @Delay >= 86400 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Delay is not supported.', 16, 2) + VALUES('The value for the parameter @Delay is not supported. The value has to be greater than or equal to 0 and less than 86400. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Delay.', 16, 1) END ---------------------------------------------------------------------------------------------------- - IF @LockTimeout < 0 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported.', 16, 1) - END - - IF @LockTimeout > 86400 + IF @LockTimeout < 0 OR @LockTimeout > 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported.', 16, 2) + VALUES('The value for the parameter @LockTimeout is not supported. The value has to be between 0 and 86400. See https://ola.hallengren.com/sql-server-integrity-check.html#LockTimeout.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1256,7 +1250,7 @@ BEGIN IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) + VALUES('The value for the parameter @LockMessageSeverity is not supported. Supported values are 10 and 16. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#LockMessageSeverity.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1264,7 +1258,7 @@ BEGIN IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StringDelimiter is not supported.', 16, 1) + VALUES('The value for the parameter @StringDelimiter is not supported. The value has to be exactly one character. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StringDelimiter.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1272,13 +1266,13 @@ BEGIN IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 1) + VALUES('The value for the parameter @DatabaseOrder is not supported. Supported values are DATABASE_NAME_ASC, DATABASE_NAME_DESC, DATABASE_SIZE_ASC and DATABASE_SIZE_DESC. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DatabaseOrder.', 16, 1) END IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 2) + VALUES('The parameter @DatabaseOrder is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DatabaseOrder.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1286,13 +1280,13 @@ BEGIN IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) + VALUES('The value for the parameter @DatabasesInParallel is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DatabasesInParallel.', 16, 1) END IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 2) + VALUES('The parameter @DatabasesInParallel is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DatabasesInParallel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1300,7 +1294,7 @@ BEGIN IF LEN(@ExecuteAsUser) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExecuteAsUser is not supported.', 16, 1) + VALUES('The value for the parameter @ExecuteAsUser is not supported. The maximum length is 128 characters. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#ExecuteAsUser.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1308,7 +1302,7 @@ BEGIN IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) + VALUES('The value for the parameter @LogToTable is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#LogToTable.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1316,15 +1310,7 @@ BEGIN IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Execute is not supported.', 16, 1) - END - - ---------------------------------------------------------------------------------------------------- - - IF EXISTS(SELECT * FROM @Errors) - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) + VALUES('The value for the parameter @Execute is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Execute.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1340,7 +1326,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Databases.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1352,7 +1338,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @Indexes parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @Indexes parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Indexes.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') @@ -1364,7 +1350,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#AvailabilityGroups.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1377,7 +1363,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Indexes.', 10, 1) END ---------------------------------------------------------------------------------------------------- diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 73abbc8b..884a6c8f 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: 2026-08-08 16:00:55 +Version: 2026-08-08 22:31:52 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 16:00:55 //-- + --// Version: 2026-08-08 22:31:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -198,25 +198,25 @@ BEGIN IF @DatabaseContext IS NULL OR NOT EXISTS (SELECT * FROM sys.databases WHERE name = @DatabaseContext) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseContext is not supported.', 16, 1) + VALUES('The value for the parameter @DatabaseContext is not supported. Specify the name of an existing database.', 16, 1) END IF @Command IS NULL OR @Command = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Command is not supported.', 16, 1) + VALUES('The value for the parameter @Command is not supported. The value cannot be NULL or empty.', 16, 1) END IF @CommandType IS NULL OR @CommandType = '' OR LEN(@CommandType) > 60 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CommandType is not supported.', 16, 1) + VALUES('The value for the parameter @CommandType is not supported. The value cannot be NULL or empty, and the maximum length is 60 characters.', 16, 1) END IF @Mode NOT IN(1,2) OR @Mode IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Mode is not supported.', 16, 1) + VALUES('The value for the parameter @Mode is not supported. Supported values are 1 and 2.', 16, 1) END IF (@EncryptionKey IS NULL AND @EncryptionKeyPlaceholder IS NOT NULL) OR (@EncryptionKey IS NOT NULL AND @EncryptionKeyPlaceholder IS NULL) @@ -228,25 +228,25 @@ BEGIN IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) + VALUES('The value for the parameter @LockMessageSeverity is not supported. Supported values are 10 and 16.', 16, 1) END IF LEN(@ExecuteAsUser) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExecuteAsUser is not supported.', 16, 1) + VALUES('The value for the parameter @ExecuteAsUser is not supported. The maximum length is 128 characters.', 16, 1) END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) + VALUES('The value for the parameter @LogToTable is not supported. Supported values are ''Y'' and ''N''.', 16, 1) END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Execute is not supported.', 16, 1) + VALUES('The value for the parameter @Execute is not supported. Supported values are ''Y'' and ''N''.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 16:00:55 //-- + --// Version: 2026-08-08 22:31:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -895,13 +895,13 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1) + VALUES('ANSI_NULLS has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1) + VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-backup.html.', 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') @@ -925,25 +925,25 @@ BEGIN 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, [State]) - VALUES('The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1) + VALUES('The table Queue is missing. It is required when @DatabasesInParallel = ''Y''. 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, [State]) - VALUES('The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) + VALUES('The table QueueDatabase is missing. It is required when @DatabasesInParallel = ''Y''. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) END IF @@TRANCOUNT <> 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The transaction count is not 0.', 16, 1) + VALUES('The stored procedure cannot be executed inside a transaction. The transaction count (@@TRANCOUNT) has to be 0. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF @AmazonRDS = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The stored procedure DatabaseBackup is not supported on Amazon RDS.', 16, 1) + VALUES('The stored procedure DatabaseBackup is not supported on Amazon RDS. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1067,7 +1067,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DATALENGTH(DatabaseName) = 0)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Databases is not supported.', 16, 1) + VALUES('The value for the parameter @Databases is not supported. The value could not be parsed into a list of databases. See https://ola.hallengren.com/sql-server-backup.html#Databases.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1159,22 +1159,28 @@ 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 @IsHadrEnabled = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @AvailabilityGroups is not supported. The value could not be parsed into a list of availability groups. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroups.', 16, 1) + END + + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroups is not supported.', 16, 1) + VALUES('The parameter @AvailabilityGroups can only be used when availability groups are enabled on the instance. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroups.', 16, 1) END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2) + VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1190,7 +1196,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The names of the following databases are not supported: ' + @ErrorMessage + '.', 16, 1) + VALUES('The names of the following databases are not supported: ' + @ErrorMessage + '. A database name has to contain at least one character that can be used in file names. See https://ola.hallengren.com/sql-server-backup.html#Databases.', 16, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1203,7 +1209,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The names of the following databases are not unique in the file system: ' + @ErrorMessage + '.', 16, 1) + VALUES('The names of the following databases are not unique in the file system: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-backup.html#Databases.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1301,43 +1307,49 @@ 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 = 'NUL') OR DirectoryPath IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Directory is not supported.', 16, 1) + VALUES('The value for the parameter @Directory is not supported. Specify a local path (e.g. D:\Backup), a UNC path (e.g. \\Server\Share), a path starting with / on Linux, or NUL, without leading or trailing spaces. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) END IF EXISTS (SELECT * FROM @Directories GROUP BY DirectoryPath HAVING COUNT(*) <> 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The same directory has been specified multiple times in the parameters @Directory and @MirrorDirectory.', 16, 2) + VALUES('The same directory has been specified multiple times in the parameters @Directory and @MirrorDirectory. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) 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]) - VALUES('The number of directories for the parameters @Directory and @MirrorDirectory has to be the same.', 16, 3) + VALUES('The number of directories for the parameters @Directory and @MirrorDirectory has to be the same. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) + END + + IF @Directory IS NOT NULL AND @EngineEdition = 8 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameter @Directory is not supported on Azure SQL Managed Instance. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) END - IF (@Directory IS NOT NULL AND @EngineEdition = 8) OR (@Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST') + IF @Directory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Directory is not supported.', 16, 4) + VALUES('The parameter @Directory is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) 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]) - VALUES('The value for the parameter @Directory is not supported.', 16, 5) + VALUES('The value for the parameter @Directory is not supported. Backup to NUL cannot be combined with other directories. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) 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]) - VALUES('Mirrored backup is not supported when backing up to NUL.', 16, 6) + VALUES('Mirrored backup is not supported when backing up to NUL. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF EXISTS (SELECT * FROM @Directories WHERE Mirror = 0 AND DirectoryPath = 'NUL') AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Backup to NUL is only supported with SQL Server native backups.', 16, 7) + VALUES('Backup to NUL is only supported with SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1345,31 +1357,31 @@ 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 IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 1) + VALUES('The value for the parameter @MirrorDirectory is not supported. Specify a local path (e.g. D:\Backup), a UNC path (e.g. \\Server\Share), or a path starting with / on Linux, without leading or trailing spaces. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END IF @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 2) + VALUES('The value for the parameter @MirrorDirectory is not supported. Redgate SQL Backup Pro and Idera SQL Safe Backup support only one mirror directory. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END IF @MirrorDirectory IS NOT NULL AND @EngineEdition = 8 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 3) + VALUES('The value for the parameter @MirrorDirectory is not supported. Mirrored backup is not supported on Azure SQL Managed Instance. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END IF @MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorDirectory is not supported.', 16, 4) + VALUES('The value for the parameter @MirrorDirectory is not supported. Mirrored backup is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END IF (@BackupSoftware IS NULL AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND @EngineEdition <> 3) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorDirectory is not supported. Mirrored backup to disk is only available in Enterprise and Developer Edition.', 16, 5) + VALUES('The value for the parameter @MirrorDirectory is not supported. Mirrored backup to disk is not supported in this edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1399,7 +1411,7 @@ BEGIN IF NOT EXISTS (SELECT * FROM @DirectoryInfo WHERE FileExists = 0 AND FileIsADirectory = 1 AND ParentDirectoryExists = 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The directory ' + @CurrentRootDirectoryPath + ' does not exist.', 16, 1) + VALUES('The directory ' + @CurrentRootDirectoryPath + ' does not exist. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END UPDATE @Directories @@ -1480,32 +1492,32 @@ BEGIN IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND NOT (DirectoryPath LIKE 'https://%/%' OR DirectoryPath LIKE 's3://%/%')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @URL is not supported.', 16, 1) + VALUES('The value for the parameter @URL is not supported. The URL has to start with https:// (Azure Blob Storage) or s3:// (S3-compatible storage). See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) END IF EXISTS (SELECT * FROM @URLs GROUP BY DirectoryPath HAVING COUNT(*) <> 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The same URL has been specified multiple times in the parameters @URL and @MirrorURL.', 16, 2) + VALUES('The same URL has been specified multiple times in the parameters @URL and @MirrorURL. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) 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]) - VALUES('The number of URLs for the parameters @URL and @MirrorURL has to be the same.', 16, 3) + VALUES('The number of URLs for the parameters @URL and @MirrorURL has to be the same. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF EXISTS(SELECT * FROM @URLs WHERE DirectoryPath LIKE 's3://%/%') AND NOT ((@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND @EngineEdition IN(2, 3, 8)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Backup to S3-compatible storage is not supported in this version and edition of SQL Server.', 16, 4) + VALUES('Backup to S3-compatible storage is not supported in this version and edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) END IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 'https://%/%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Striped backups across S3-compatible storage and Azure Blob storage are not supported.', 16, 4) + VALUES('Striped backups across S3-compatible storage and Azure Blob Storage are not supported. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1513,14 +1525,14 @@ BEGIN IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND NOT (DirectoryPath LIKE 'https://%/%' OR DirectoryPath LIKE 's3://%/%')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorURL is not supported.', 16, 1) + VALUES('The value for the parameter @MirrorURL is not supported. The URL has to start with https:// (Azure Blob Storage) or s3:// (S3-compatible storage). See https://ola.hallengren.com/sql-server-backup.html#MirrorURL.', 16, 1) END IF (EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 'https://%/%') AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath LIKE 's3://%/%')) OR (EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND DirectoryPath LIKE 'https://%/%')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Mirrored backups across S3-compatible storage and Azure Blob storage are not supported.', 16, 2) + VALUES('Mirrored backups across S3-compatible storage and Azure Blob Storage are not supported. See https://ola.hallengren.com/sql-server-backup.html#MirrorURL.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1624,7 +1636,7 @@ BEGIN IF @BackupType NOT IN ('FULL','DIFF','LOG') OR @BackupType IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BackupType is not supported.', 16, 1) + VALUES('The value for the parameter @BackupType is not supported. Supported values are FULL, DIFF and LOG. See https://ola.hallengren.com/sql-server-backup.html#BackupType.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1632,7 +1644,7 @@ BEGIN IF @EngineEdition = 8 AND NOT (@BackupType = 'FULL' AND @CopyOnly = 'Y') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('SQL Database Managed Instance only supports COPY_ONLY full backups.', 16, 1) + VALUES('Azure SQL Managed Instance only supports COPY_ONLY full backups. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1640,25 +1652,25 @@ BEGIN IF @Verify NOT IN ('Y','N') OR @Verify IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Verify is not supported.', 16, 1) + VALUES('The value for the parameter @Verify is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#Verify.', 16, 1) END IF @BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND @Verify = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Verify is not supported. Verify is not supported with encrypted backups with Idera SQL Safe Backup.', 16, 2) + VALUES('Verify is not supported for encrypted backups with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#Verify.', 16, 1) END IF @Verify = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Verify is not supported. Verify is not supported with Data Domain Boost.', 16, 3) + VALUES('Verify is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#Verify.', 16, 1) END IF @Verify = 'Y' AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Verify is not supported. Verify is not supported when backing up to NUL.', 16, 4) + VALUES('Verify is not supported when backing up to NUL. See https://ola.hallengren.com/sql-server-backup.html#Verify.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1666,37 +1678,37 @@ BEGIN IF @CleanupTime < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupTime is not supported.', 16, 1) + VALUES('The value for the parameter @CleanupTime is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) END IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage.', 16, 2) + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) END IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL.', 16, 3) + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to NUL. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{DatabaseName}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{DatabaseName}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory.', 16, 4) + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {DatabaseName} is not part of the directory structure. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) END IF @CleanupTime IS NOT NULL AND ((@DirectoryStructure NOT LIKE '%{BackupType}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{BackupType}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) AND (SELECT COUNT(*) FROM (SELECT @FileExtensionFull AS FileExtension UNION SELECT @FileExtensionDiff UNION SELECT @FileExtensionLog) FileExtension) <> 3 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory and the file extensions are not unique.', 16, 5) + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {BackupType} is not part of the directory structure and the file extensions are not unique. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) END IF @CleanupTime IS NOT NULL AND @CopyOnly = 'Y' AND ((@DirectoryStructure NOT LIKE '%{CopyOnly}%' OR @DirectoryStructure IS NULL) OR (@IsHadrEnabled = 1 AND (@AvailabilityGroupDirectoryStructure NOT LIKE '%{CopyOnly}%' OR @AvailabilityGroupDirectoryStructure IS NULL))) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory.', 16, 6) + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported if the token {CopyOnly} is not part of the directory structure. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1704,7 +1716,7 @@ BEGIN IF @CleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @CleanupMode IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupMode is not supported.', 16, 1) + VALUES('The value for the parameter @CleanupMode is not supported. Supported values are BEFORE_BACKUP and AFTER_BACKUP. See https://ola.hallengren.com/sql-server-backup.html#CleanupMode.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1712,26 +1724,26 @@ BEGIN IF @Compress NOT IN ('Y','N') OR @Compress IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Compress is not supported.', 16, 1) + VALUES('The value for the parameter @Compress is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) END IF @Compress = 'Y' AND @BackupSoftware IS NULL AND NOT (@EngineEdition IN (3, 8) OR @EditionID IN (-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Compress is not supported. Backup compression is not supported in this edition of SQL Server.', 16, 2) + VALUES('Backup compression is not supported in this edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) END IF @Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevelNumeric IS NULL OR @CompressionLevelNumeric >= 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Compress is not supported.', 16, 3) + VALUES('Setting @Compress to ''N'' with LiteSpeed for SQL Server, Redgate SQL Backup Pro or Idera SQL Safe Backup requires @CompressionLevelNumeric = 0. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) END IF @Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevelNumeric = 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Compress is not supported.', 16, 4) + VALUES('Setting @Compress to ''Y'' cannot be combined with @CompressionLevelNumeric = 0. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1739,31 +1751,31 @@ BEGIN IF @CompressionAlgorithm NOT IN ('MS_XPRESS','QAT_DEFLATE','ZSTD') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionAlgorithm is not supported. The allowed values are MS_XPRESS, QAT_DEFLATE and ZSTD.', 16, 1) + VALUES('The value for the parameter @CompressionAlgorithm is not supported. Supported values are MS_XPRESS, QAT_DEFLATE and ZSTD. See https://ola.hallengren.com/sql-server-backup.html#CompressionAlgorithm.', 16, 1) END IF @CompressionAlgorithm IS NOT NULL AND NOT (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionAlgorithm is not supported. Specifying the compression algorithm is only supported in SQL Server 2022 and later.', 16, 2) + VALUES('The parameter @CompressionAlgorithm is not supported in this version and edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#CompressionAlgorithm.', 16, 1) END IF @CompressionAlgorithm = 'QAT_DEFLATE' AND NOT (@EngineEdition IN(2, 3)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to QAT_DEFLATE is only supported in Standard and Enterprise Edition.', 16, 3) + VALUES('Setting @CompressionAlgorithm to QAT_DEFLATE is not supported in this edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#CompressionAlgorithm.', 16, 1) END IF @CompressionAlgorithm = 'ZSTD' AND NOT (@Version >= 17 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm to ZSTD is only supported in SQL Server 2025 and later.', 16, 4) + VALUES('Setting @CompressionAlgorithm to ZSTD is not supported in this version and edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#CompressionAlgorithm.', 16, 1) END IF @CompressionAlgorithm IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionAlgorithm is not supported. Setting the compression algorithm is only supported with SQL Server native backup.', 16, 5) + VALUES('The parameter @CompressionAlgorithm is only supported with SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html#CompressionAlgorithm.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1771,19 +1783,19 @@ BEGIN IF @CompressionLevel IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevel is not supported. For third-party backup software, use the parameter @CompressionLevelNumeric.', 16, 1) + VALUES('The parameter @CompressionLevel is only supported with SQL Server native backups. For third-party backup software, use the parameter @CompressionLevelNumeric. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevel.', 16, 1) END IF @CompressionLevel NOT IN ('LOW','MEDIUM','HIGH') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevel is not supported. The supported values are LOW, MEDIUM and HIGH.', 16, 2) + VALUES('The value for the parameter @CompressionLevel is not supported. Supported values are LOW, MEDIUM and HIGH. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevel.', 16, 1) END IF @CompressionLevel IS NOT NULL AND NOT (@Version >= 17 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevel is not supported. Setting the compression level is only supported in SQL Server 2025 and later.', 16, 3) + VALUES('The parameter @CompressionLevel is not supported in this version and edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1791,13 +1803,13 @@ BEGIN IF @CopyOnly NOT IN ('Y','N') OR @CopyOnly IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CopyOnly is not supported.', 16, 1) + VALUES('The value for the parameter @CopyOnly is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#CopyOnly.', 16, 1) END IF @CopyOnly = 'Y' AND @BackupType = 'DIFF' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Differential copy-only backups are not supported.', 16, 2) + VALUES('Differential copy-only backups are not supported. See https://ola.hallengren.com/sql-server-backup.html#CopyOnly.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1805,13 +1817,13 @@ BEGIN IF @ChangeBackupType NOT IN ('Y','N') OR @ChangeBackupType IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ChangeBackupType is not supported.', 16, 1) + VALUES('The value for the parameter @ChangeBackupType is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#ChangeBackupType.', 16, 1) END IF @ChangeBackupType = 'Y' AND NOT @BackupType IN ('DIFF', 'LOG') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Setting @ChangeBackupType to ''Y'' is only supported with differential and log backups.', 16, 2) + VALUES('Setting @ChangeBackupType to ''Y'' is only supported with differential and log backups. See https://ola.hallengren.com/sql-server-backup.html#ChangeBackupType.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1819,37 +1831,37 @@ BEGIN IF @BackupSoftware NOT IN ('LITESPEED','SQLBACKUP','SQLSAFE','DATA_DOMAIN_BOOST') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BackupSoftware is not supported.', 16, 1) + VALUES('The value for the parameter @BackupSoftware is not supported. Supported values are LITESPEED, SQLBACKUP, SQLSAFE and DATA_DOMAIN_BOOST. See https://ola.hallengren.com/sql-server-backup.html#BackupSoftware.', 16, 1) END IF @BackupSoftware IS NOT NULL AND @HostPlatform = 'Linux' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BackupSoftware is not supported. Only native backups are supported on Linux.', 16, 2) + VALUES('The value for the parameter @BackupSoftware is not supported. Only native backups are supported on Linux. See https://ola.hallengren.com/sql-server-backup.html#BackupSoftware.', 16, 1) 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, [State]) - VALUES('LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.', 16, 3) + VALUES('LiteSpeed for SQL Server is not installed. Download https://www.quest.com/products/litespeed-for-sql-server/.', 16, 1) END IF @BackupSoftware = 'SQLBACKUP' AND NOT EXISTS (SELECT * FROM [master].sys.objects WHERE [type] = 'X' AND [name] = 'sqlbackup') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Red Gate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/sql-backup/.', 16, 4) + VALUES('Redgate SQL Backup Pro is not installed. Download https://www.red-gate.com/products/sql-backup/.', 16, 1) 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, [State]) - VALUES('Idera SQL Safe Backup is not installed. Download https://www.idera.com/products/sql-safe-backup/.', 16, 5) + VALUES('Idera SQL Safe Backup is not installed. Download https://www.idera.com/products/sql-safe-backup/.', 16, 1) 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, [State]) - VALUES('EMC Data Domain Boost is not installed. Download https://www.dell.com/en-us/shop/storage-servers-and-networking-for-business/sf/powerprotect-data-domain.', 16, 6) + VALUES('Data Domain Boost is not installed. Download https://www.dell.com/en-us/shop/storage-servers-and-networking-for-business/sf/powerprotect-data-domain.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1857,7 +1869,7 @@ BEGIN IF @Checksum NOT IN ('Y','N') OR @Checksum IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Checksum is not supported.', 16, 1) + VALUES('The value for the parameter @Checksum is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#Checksum.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1865,31 +1877,31 @@ BEGIN IF @BlockSize NOT IN (512,1024,2048,4096,8192,16384,32768,65536) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BlockSize is not supported.', 16, 1) + VALUES('The value for the parameter @BlockSize is not supported. Supported values are 512, 1024, 2048, 4096, 8192, 16384, 32768 and 65536. See https://ola.hallengren.com/sql-server-backup.html#BlockSize.', 16, 1) END IF @BlockSize IS NOT NULL AND @BackupSoftware = 'SQLBACKUP' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BlockSize is not supported. This parameter is not supported with Redgate SQL Backup Pro.', 16, 2) + VALUES('The parameter @BlockSize is not supported with Redgate SQL Backup Pro. See https://ola.hallengren.com/sql-server-backup.html#BlockSize.', 16, 1) END IF @BlockSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BlockSize is not supported. This parameter is not supported with Idera SQL Safe.', 16, 3) + VALUES('The parameter @BlockSize is not supported with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#BlockSize.', 16, 1) END IF @BlockSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('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) + VALUES('BLOCKSIZE is not supported when backing up to URL with page blobs. See https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url.', 16, 1) END IF @BlockSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BlockSize is not supported. This parameter is not supported with Data Domain Boost.', 16, 5) + VALUES('The parameter @BlockSize is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#BlockSize.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1897,19 +1909,19 @@ BEGIN IF @BufferCount <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BufferCount is not supported.', 16, 1) + VALUES('The value for the parameter @BufferCount is not supported. The value has to be greater than 0. See https://ola.hallengren.com/sql-server-backup.html#BufferCount.', 16, 1) END IF @BufferCount IS NOT NULL AND @BackupSoftware = 'SQLBACKUP' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BufferCount is not supported.', 16, 2) + VALUES('The parameter @BufferCount is not supported with Redgate SQL Backup Pro. See https://ola.hallengren.com/sql-server-backup.html#BufferCount.', 16, 1) END IF @BufferCount IS NOT NULL AND @BackupSoftware = 'SQLSAFE' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BufferCount is not supported.', 16, 3) + VALUES('The parameter @BufferCount is not supported with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#BufferCount.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1917,37 +1929,37 @@ BEGIN IF @MaxTransferSize < 65536 OR @MaxTransferSize > 20971520 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 1) + VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 20971520. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END IF @MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 2) + VALUES('The value for the parameter @MaxTransferSize is not supported. The maximum value with Redgate SQL Backup Pro is 1048576. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END IF @MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 3) + VALUES('The parameter @MaxTransferSize is not supported with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END IF @MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('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) + VALUES('MAXTRANSFERSIZE is not supported when backing up to URL with page blobs. See https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url.', 16, 1) END IF @MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 5) + VALUES('The parameter @MaxTransferSize is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @MaxTransferSize > 4194304 AND @URL IS NULL AND @BackupSoftware IS NULL + IF @MaxTransferSize > 4194304 AND @Directory IS NOT NULL AND @BackupSoftware IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported.', 16, 6) + VALUES('The value for the parameter @MaxTransferSize is not supported. The maximum value for SQL Server native backups to disk is 4194304. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1955,61 +1967,61 @@ BEGIN IF @NumberOfFiles < 1 OR @NumberOfFiles > 64 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 1) + VALUES('The value for the parameter @NumberOfFiles is not supported. The value has to be between 1 and 64. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles > 32 AND @BackupSoftware = 'SQLBACKUP' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 2) + VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files with Redgate SQL Backup Pro is 32. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles < (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 3) + VALUES('The value for the parameter @NumberOfFiles is not supported. The number of files has to be greater than or equal to the number of directories. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @Directories WHERE Mirror = 0) > 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 4) + VALUES('The value for the parameter @NumberOfFiles is not supported. The number of files has to be evenly divisible by the number of directories. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @URL IS NOT NULL AND @Credential IS NOT NULL AND @NumberOfFiles <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('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) + VALUES('Backup striping to URL with page blobs is not supported. See https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url.', 16, 1) END IF @NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 6) + VALUES('The value for the parameter @NumberOfFiles is not supported. Mirrored backups with multiple files are not supported with Redgate SQL Backup Pro and Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 7) + VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files with Data Domain Boost is 32. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles < (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 8) + VALUES('The value for the parameter @NumberOfFiles is not supported. The number of files has to be greater than or equal to the number of URLs. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles % (SELECT NULLIF(COUNT(*),0) FROM @URLs WHERE Mirror = 0) > 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported.', 16, 9) + VALUES('The value for the parameter @NumberOfFiles is not supported. The number of files has to be evenly divisible by the number of URLs. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles > 32 AND @URL LIKE 's3%' AND @MirrorURL LIKE 's3%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored backups to S3 storage is 32.', 16, 10) + VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored backups to S3 storage is 32. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2017,13 +2029,13 @@ BEGIN IF @MinBackupSizeForMultipleFiles <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinBackupSizeForMultipleFiles is not supported.', 16, 1) + VALUES('The value for the parameter @MinBackupSizeForMultipleFiles is not supported. The value has to be greater than 0. See https://ola.hallengren.com/sql-server-backup.html#MinBackupSizeForMultipleFiles.', 16, 1) END IF @MinBackupSizeForMultipleFiles IS NOT NULL AND @NumberOfFiles IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinBackupSizeForMultipleFiles is not supported. This parameter can only be used together with @NumberOfFiles.', 16, 2) + VALUES('The parameter @MinBackupSizeForMultipleFiles can only be used together with @NumberOfFiles. See https://ola.hallengren.com/sql-server-backup.html#MinBackupSizeForMultipleFiles.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2031,13 +2043,13 @@ BEGIN IF @MaxFileSize <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxFileSize is not supported.', 16, 1) + VALUES('The value for the parameter @MaxFileSize is not supported. The value has to be greater than 0. See https://ola.hallengren.com/sql-server-backup.html#MaxFileSize.', 16, 1) END IF @MaxFileSize IS NOT NULL AND @NumberOfFiles IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameters @MaxFileSize and @NumberOfFiles cannot be used together.', 16, 2) + VALUES('The parameters @MaxFileSize and @NumberOfFiles cannot be used together. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2045,31 +2057,31 @@ BEGIN IF (@BackupSoftware IS NULL AND @CompressionLevelNumeric IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 1) + VALUES('The parameter @CompressionLevelNumeric is only supported with third-party backup software. For SQL Server native backups, use the parameter @CompressionLevel. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevelNumeric.', 16, 1) END IF @BackupSoftware = 'LITESPEED' AND (@CompressionLevelNumeric < 0 OR @CompressionLevelNumeric > 8) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 2) + VALUES('The value for the parameter @CompressionLevelNumeric is not supported. With LiteSpeed for SQL Server, the value has to be between 0 and 8. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevelNumeric.', 16, 1) END IF @BackupSoftware = 'SQLBACKUP' AND (@CompressionLevelNumeric < 0 OR @CompressionLevelNumeric > 4) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 3) + VALUES('The value for the parameter @CompressionLevelNumeric is not supported. With Redgate SQL Backup Pro, the value has to be between 0 and 4. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevelNumeric.', 16, 1) END IF @BackupSoftware = 'SQLSAFE' AND (@CompressionLevelNumeric < 1 OR @CompressionLevelNumeric > 4) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 4) + VALUES('The value for the parameter @CompressionLevelNumeric is not supported. With Idera SQL Safe Backup, the value has to be between 1 and 4. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevelNumeric.', 16, 1) END IF @CompressionLevelNumeric IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CompressionLevelNumeric is not supported.', 16, 5) + VALUES('The parameter @CompressionLevelNumeric is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#CompressionLevelNumeric.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2077,25 +2089,25 @@ BEGIN IF LEN(@Description) > 255 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Description is not supported.', 16, 1) + VALUES('The value for the parameter @Description is not supported. The maximum length is 255 characters. See https://ola.hallengren.com/sql-server-backup.html#Description.', 16, 1) END IF @BackupSoftware = 'LITESPEED' AND LEN(@Description) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Description is not supported.', 16, 2) + VALUES('The value for the parameter @Description is not supported. The maximum length with LiteSpeed for SQL Server is 128 characters. See https://ola.hallengren.com/sql-server-backup.html#Description.', 16, 1) END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND LEN(@Description) > 254 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Description is not supported.', 16, 3) + VALUES('The value for the parameter @Description is not supported. The maximum length with Data Domain Boost is 254 characters. See https://ola.hallengren.com/sql-server-backup.html#Description.', 16, 1) END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @Description LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Description is not supported.', 16, 4) + VALUES('The value for the parameter @Description is not supported. Double quotes (") are not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#Description.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2103,13 +2115,13 @@ BEGIN IF LEN(@BackupSetName) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BackupSetName is not supported.', 16, 1) + VALUES('The value for the parameter @BackupSetName is not supported. The maximum length is 128 characters. See https://ola.hallengren.com/sql-server-backup.html#BackupSetName.', 16, 1) END IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @BackupSetName LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BackupSetName is not supported.', 16, 2) + VALUES('The value for the parameter @BackupSetName is not supported. Double quotes (") are not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#BackupSetName.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2117,25 +2129,25 @@ BEGIN IF @Threads IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED','SQLBACKUP','SQLSAFE') OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Threads is not supported.', 16, 1) + VALUES('The parameter @Threads is only supported with LiteSpeed for SQL Server, Redgate SQL Backup Pro and Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#Threads.', 16, 1) END IF @BackupSoftware = 'LITESPEED' AND (@Threads < 1 OR @Threads > 32) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Threads is not supported.', 16, 2) + VALUES('The value for the parameter @Threads is not supported. With LiteSpeed for SQL Server, the value has to be between 1 and 32. See https://ola.hallengren.com/sql-server-backup.html#Threads.', 16, 1) END IF @BackupSoftware = 'SQLBACKUP' AND (@Threads < 2 OR @Threads > 32) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Threads is not supported.', 16, 3) + VALUES('The value for the parameter @Threads is not supported. With Redgate SQL Backup Pro, the value has to be between 2 and 32. See https://ola.hallengren.com/sql-server-backup.html#Threads.', 16, 1) END IF @BackupSoftware = 'SQLSAFE' AND (@Threads < 1 OR @Threads > 64) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Threads is not supported.', 16, 4) + VALUES('The value for the parameter @Threads is not supported. With Idera SQL Safe Backup, the value has to be between 1 and 64. See https://ola.hallengren.com/sql-server-backup.html#Threads.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2143,13 +2155,13 @@ BEGIN IF @Throttle < 1 OR @Throttle > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Throttle is not supported.', 16, 1) + VALUES('The value for the parameter @Throttle is not supported. The value has to be between 1 and 100. See https://ola.hallengren.com/sql-server-backup.html#Throttle.', 16, 1) END IF @Throttle IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Throttle is not supported.', 16, 2) + VALUES('The parameter @Throttle is only supported with LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#Throttle.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2157,19 +2169,19 @@ BEGIN IF @Encrypt NOT IN('Y','N') OR @Encrypt IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Encrypt is not supported.', 16, 1) + VALUES('The value for the parameter @Encrypt is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#Encrypt.', 16, 1) END IF @Encrypt = 'Y' AND @BackupSoftware IS NULL AND NOT (@EngineEdition IN(3, 8) OR @EditionID IN(-1534726760, -1785266663)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Encrypt is not supported.', 16, 2) + VALUES('Backup encryption is not supported in this edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#Encrypt.', 16, 1) END IF @Encrypt = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Encrypt is not supported.', 16, 3) + VALUES('The value for the parameter @Encrypt is not supported. Encrypted backups are not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#Encrypt.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2177,31 +2189,31 @@ BEGIN 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]) - VALUES('The value for the parameter @EncryptionAlgorithm is not supported.', 16, 1) + VALUES('The value for the parameter @EncryptionAlgorithm is not supported. Supported values for SQL Server native backups are AES_128, AES_192, AES_256 and TRIPLE_DES_3KEY. See https://ola.hallengren.com/sql-server-backup.html#EncryptionAlgorithm.', 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]) - VALUES('The value for the parameter @EncryptionAlgorithm is not supported.', 16, 2) + VALUES('The value for the parameter @EncryptionAlgorithm is not supported. Supported values with LiteSpeed for SQL Server are RC2_40, RC2_56, RC2_112, RC2_128, TRIPLE_DES_3KEY, RC4_128, AES_128, AES_192 and AES_256. See https://ola.hallengren.com/sql-server-backup.html#EncryptionAlgorithm.', 16, 1) 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]) - VALUES('The value for the parameter @EncryptionAlgorithm is not supported.', 16, 3) + VALUES('The value for the parameter @EncryptionAlgorithm is not supported. Supported values with Redgate SQL Backup Pro are AES_128 and AES_256. See https://ola.hallengren.com/sql-server-backup.html#EncryptionAlgorithm.', 16, 1) END IF @BackupSoftware = 'SQLSAFE' AND @Encrypt = 'Y' AND (@EncryptionAlgorithm NOT IN('AES_128','AES_256') OR @EncryptionAlgorithm IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @EncryptionAlgorithm is not supported.', 16, 4) + VALUES('The value for the parameter @EncryptionAlgorithm is not supported. Supported values with Idera SQL Safe Backup are AES_128 and AES_256. See https://ola.hallengren.com/sql-server-backup.html#EncryptionAlgorithm.', 16, 1) END IF @EncryptionAlgorithm IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @EncryptionAlgorithm is not supported.', 16, 5) + VALUES('The parameter @EncryptionAlgorithm is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#EncryptionAlgorithm.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2209,25 +2221,25 @@ BEGIN IF (NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerCertificate IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ServerCertificate is not supported.', 16, 1) + VALUES('The parameter @ServerCertificate can only be used together with @Encrypt = ''Y'' and SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html#ServerCertificate.', 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]) - VALUES('The value for the parameter @ServerCertificate is not supported.', 16, 2) + VALUES('You need to specify one of the parameters @ServerCertificate and @ServerAsymmetricKey when performing encrypted SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) 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]) - VALUES('The value for the parameter @ServerCertificate is not supported.', 16, 3) + VALUES('You can only specify one of the parameters @ServerCertificate and @ServerAsymmetricKey. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF @ServerCertificate IS NOT NULL AND NOT EXISTS(SELECT * FROM master.sys.certificates WHERE name = @ServerCertificate) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ServerCertificate is not supported.', 16, 4) + VALUES('The value for the parameter @ServerCertificate is not supported. The certificate does not exist in the master database. See https://ola.hallengren.com/sql-server-backup.html#ServerCertificate.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2235,25 +2247,13 @@ BEGIN IF NOT (@BackupSoftware IS NULL AND @Encrypt = 'Y') AND @ServerAsymmetricKey IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('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]) - VALUES('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]) - VALUES('The value for the parameter @ServerAsymmetricKey is not supported.', 16, 3) + VALUES('The parameter @ServerAsymmetricKey can only be used together with @Encrypt = ''Y'' and SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html#ServerAsymmetricKey.', 16, 1) 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]) - VALUES('The value for the parameter @ServerAsymmetricKey is not supported.', 16, 4) + VALUES('The value for the parameter @ServerAsymmetricKey is not supported. The asymmetric key does not exist in the master database. See https://ola.hallengren.com/sql-server-backup.html#ServerAsymmetricKey.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2261,25 +2261,25 @@ BEGIN IF @EncryptionKey IS NOT NULL AND @BackupSoftware IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @EncryptionKey is not supported.', 16, 1) + VALUES('The parameter @EncryptionKey is only supported with third-party backup software. For SQL Server native backups, use @ServerCertificate or @ServerAsymmetricKey. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) END IF @EncryptionKey IS NOT NULL AND @Encrypt = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @EncryptionKey is not supported.', 16, 2) + VALUES('The parameter @EncryptionKey can only be used together with @Encrypt = ''Y''. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) END IF @EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @EncryptionKey is not supported.', 16, 3) + VALUES('You need to specify @EncryptionKey when performing encrypted backups with LiteSpeed for SQL Server, Redgate SQL Backup Pro or Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) END IF @EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @EncryptionKey is not supported.', 16, 4) + VALUES('The parameter @EncryptionKey is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2287,13 +2287,13 @@ BEGIN IF @ReadWriteFileGroups NOT IN('Y','N') OR @ReadWriteFileGroups IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ReadWriteFileGroups is not supported.', 16, 1) + VALUES('The value for the parameter @ReadWriteFileGroups is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#ReadWriteFileGroups.', 16, 1) END IF @ReadWriteFileGroups = 'Y' AND @BackupType = 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ReadWriteFileGroups is not supported.', 16, 2) + VALUES('Setting @ReadWriteFileGroups to ''Y'' is not supported for transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#ReadWriteFileGroups.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2301,7 +2301,7 @@ BEGIN IF @OverrideBackupPreference NOT IN('Y','N') OR @OverrideBackupPreference IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @OverrideBackupPreference is not supported.', 16, 1) + VALUES('The value for the parameter @OverrideBackupPreference is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#OverrideBackupPreference.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2309,19 +2309,19 @@ BEGIN IF @NoRecovery NOT IN('Y','N') OR @NoRecovery IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NoRecovery is not supported.', 16, 1) + VALUES('The value for the parameter @NoRecovery is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#NoRecovery.', 16, 1) END IF @NoRecovery = 'Y' AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NoRecovery is not supported.', 16, 2) + VALUES('Setting @NoRecovery to ''Y'' is only supported for transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#NoRecovery.', 16, 1) END IF @NoRecovery = 'Y' AND @BackupSoftware = 'SQLSAFE' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NoRecovery is not supported.', 16, 3) + VALUES('Setting @NoRecovery to ''Y'' is not supported with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#NoRecovery.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2329,19 +2329,19 @@ BEGIN IF @URL IS NOT NULL AND @Directory IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @URL is not supported.', 16, 1) + VALUES('The parameters @URL and @Directory cannot be used together. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF @URL IS NOT NULL AND @MirrorDirectory IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @URL is not supported.', 16, 2) + VALUES('The parameters @URL and @MirrorDirectory cannot be used together. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF @URL IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @URL is not supported.', 16, 3) + VALUES('Backup to URL is only supported with SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2349,19 +2349,19 @@ BEGIN IF @Credential IS NOT NULL AND @URL IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Credential is not supported.', 16, 1) + VALUES('The parameter @Credential can only be used together with @URL. See https://ola.hallengren.com/sql-server-backup.html#Credential.', 16, 1) END IF @URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE UPPER(credential_identity) IN('SHARED ACCESS SIGNATURE','MANAGED IDENTITY','S3 ACCESS KEY')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Credential is not supported.', 16, 2) + VALUES('When backing up to URL, you need to specify @Credential or create a credential with the identity SHARED ACCESS SIGNATURE, MANAGED IDENTITY or S3 ACCESS KEY. See https://ola.hallengren.com/sql-server-backup.html#Credential.', 16, 1) END IF @Credential IS NOT NULL AND NOT EXISTS(SELECT * FROM sys.credentials WHERE name = @Credential) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Credential is not supported.', 16, 3) + VALUES('The value for the parameter @Credential is not supported. The credential does not exist. See https://ola.hallengren.com/sql-server-backup.html#Credential.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2369,13 +2369,13 @@ BEGIN IF @MirrorCleanupTime < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorCleanupTime is not supported.', 16, 1) + VALUES('The value for the parameter @MirrorCleanupTime is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-backup.html#MirrorCleanupTime.', 16, 1) END IF @MirrorCleanupTime IS NOT NULL AND @MirrorDirectory IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorCleanupTime is not supported.', 16, 2) + VALUES('The parameter @MirrorCleanupTime can only be used together with @MirrorDirectory. See https://ola.hallengren.com/sql-server-backup.html#MirrorCleanupTime.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2383,7 +2383,7 @@ BEGIN IF @MirrorCleanupMode NOT IN('BEFORE_BACKUP','AFTER_BACKUP') OR @MirrorCleanupMode IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorCleanupMode is not supported.', 16, 1) + VALUES('The value for the parameter @MirrorCleanupMode is not supported. Supported values are BEFORE_BACKUP and AFTER_BACKUP. See https://ola.hallengren.com/sql-server-backup.html#MirrorCleanupMode.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2391,25 +2391,25 @@ BEGIN IF @MirrorURL IS NOT NULL AND @Directory IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorURL is not supported.', 16, 1) + VALUES('The parameters @MirrorURL and @Directory cannot be used together. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF @MirrorURL IS NOT NULL AND @MirrorDirectory IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorURL is not supported.', 16, 2) + VALUES('The parameters @MirrorURL and @MirrorDirectory cannot be used together. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END IF @MirrorURL IS NOT NULL AND @BackupSoftware IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorURL is not supported.', 16, 3) + VALUES('Mirrored backup to URL is only supported with SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html#MirrorURL.', 16, 1) END IF @MirrorURL IS NOT NULL AND @URL IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorURL is not supported.', 16, 4) + VALUES('The parameter @MirrorURL can only be used together with @URL. See https://ola.hallengren.com/sql-server-backup.html#MirrorURL.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2417,7 +2417,7 @@ BEGIN IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Updateability is not supported.', 16, 1) + VALUES('The value for the parameter @Updateability is not supported. Supported values are ALL, READ_ONLY and READ_WRITE. See https://ola.hallengren.com/sql-server-backup.html#Updateability.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2425,13 +2425,13 @@ BEGIN IF @AdaptiveCompression NOT IN('SIZE','SPEED') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AdaptiveCompression is not supported.', 16, 1) + VALUES('The value for the parameter @AdaptiveCompression is not supported. Supported values are SIZE and SPEED. See https://ola.hallengren.com/sql-server-backup.html#AdaptiveCompression.', 16, 1) END IF @AdaptiveCompression IS NOT NULL AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AdaptiveCompression is not supported.', 16, 2) + VALUES('The parameter @AdaptiveCompression is only supported with LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#AdaptiveCompression.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2439,19 +2439,19 @@ BEGIN IF @MinModificationLevel <= 0 OR @MinModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinModificationLevel is not supported.', 16, 1) + VALUES('The value for the parameter @MinModificationLevel is not supported. The value has to be greater than 0 and less than or equal to 100. See https://ola.hallengren.com/sql-server-backup.html#MinModificationLevel.', 16, 1) END IF @MinModificationLevel IS NOT NULL AND @ChangeBackupType = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''.', 16, 2) + VALUES('The parameter @MinModificationLevel can only be used together with @ChangeBackupType = ''Y''. See https://ola.hallengren.com/sql-server-backup.html#MinModificationLevel.', 16, 1) END IF @MinModificationLevel IS NOT NULL AND @BackupType NOT IN('DIFF','LOG') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @MinModificationLevel can only be used for differential and transaction log backups.', 16, 3) + VALUES('The parameter @MinModificationLevel can only be used for differential and transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#MinModificationLevel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2459,13 +2459,13 @@ BEGIN IF @MinDatabaseSizeForDifferentialBackup <= 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinDatabaseSizeForDifferentialBackup is not supported.', 16, 1) + VALUES('The value for the parameter @MinDatabaseSizeForDifferentialBackup is not supported. The value has to be greater than 0. See https://ola.hallengren.com/sql-server-backup.html#MinDatabaseSizeForDifferentialBackup.', 16, 1) END IF @MinDatabaseSizeForDifferentialBackup IS NOT NULL AND @BackupType <> 'DIFF' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @MinDatabaseSizeForDifferentialBackup can only be used for differential backups.', 16, 2) + VALUES('The parameter @MinDatabaseSizeForDifferentialBackup can only be used for differential backups. See https://ola.hallengren.com/sql-server-backup.html#MinDatabaseSizeForDifferentialBackup.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2473,7 +2473,7 @@ BEGIN IF @MinLogSizeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinLogSizeSinceLastLogBackup is not supported.', 16, 1) + VALUES('The parameter @MinLogSizeSinceLastLogBackup can only be used for transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#MinLogSizeSinceLastLogBackup.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2481,7 +2481,7 @@ BEGIN IF @MinTimeSinceLastLogBackup IS NOT NULL AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinTimeSinceLastLogBackup is not supported.', 16, 1) + VALUES('The parameter @MinTimeSinceLastLogBackup can only be used for transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#MinTimeSinceLastLogBackup.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2489,7 +2489,7 @@ BEGIN IF (@MinTimeSinceLastLogBackup IS NOT NULL AND @MinLogSizeSinceLastLogBackup IS NULL) OR (@MinTimeSinceLastLogBackup IS NULL AND @MinLogSizeSinceLastLogBackup IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameters @MinTimeSinceLastLogBackup and @MinLogSizeSinceLastLogBackup can only be used together.', 16, 1) + VALUES('The parameters @MinTimeSinceLastLogBackup and @MinLogSizeSinceLastLogBackup can only be used together. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2497,19 +2497,19 @@ BEGIN IF @DataDomainBoostHost IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostHost is not supported.', 16, 1) + VALUES('The parameter @DataDomainBoostHost can only be used together with @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostHost.', 16, 1) END IF @DataDomainBoostHost IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostHost is not supported.', 16, 2) + VALUES('You need to specify @DataDomainBoostHost when @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostHost.', 16, 1) END IF @DataDomainBoostHost LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostHost is not supported.', 16, 3) + VALUES('The value for the parameter @DataDomainBoostHost is not supported. Double quotes (") are not supported. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostHost.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2517,19 +2517,19 @@ BEGIN IF @DataDomainBoostUser IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostUser is not supported.', 16, 1) + VALUES('The parameter @DataDomainBoostUser can only be used together with @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostUser.', 16, 1) END IF @DataDomainBoostUser IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostUser is not supported.', 16, 2) + VALUES('You need to specify @DataDomainBoostUser when @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostUser.', 16, 1) END IF @DataDomainBoostUser LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostUser is not supported.', 16, 3) + VALUES('The value for the parameter @DataDomainBoostUser is not supported. Double quotes (") are not supported. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostUser.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2537,19 +2537,19 @@ BEGIN IF @DataDomainBoostDevicePath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 1) + VALUES('The parameter @DataDomainBoostDevicePath can only be used together with @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostDevicePath.', 16, 1) END IF @DataDomainBoostDevicePath IS NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 2) + VALUES('You need to specify @DataDomainBoostDevicePath when @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostDevicePath.', 16, 1) END IF @DataDomainBoostDevicePath LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostDevicePath is not supported.', 16, 3) + VALUES('The value for the parameter @DataDomainBoostDevicePath is not supported. Double quotes (") are not supported. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostDevicePath.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2557,13 +2557,13 @@ BEGIN IF @DataDomainBoostLockboxPath IS NOT NULL AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 1) + VALUES('The parameter @DataDomainBoostLockboxPath can only be used together with @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostLockboxPath.', 16, 1) END IF @DataDomainBoostLockboxPath LIKE '%"%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostLockboxPath is not supported.', 16, 2) + VALUES('The value for the parameter @DataDomainBoostLockboxPath is not supported. Double quotes (") are not supported. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostLockboxPath.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2571,13 +2571,13 @@ BEGIN IF @DataDomainBoostNoOutputTable NOT IN('Y','N') OR @DataDomainBoostNoOutputTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 1) + VALUES('The value for the parameter @DataDomainBoostNoOutputTable is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostNoOutputTable.', 16, 1) END IF @DataDomainBoostNoOutputTable = 'Y' AND (@BackupSoftware <> 'DATA_DOMAIN_BOOST' OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataDomainBoostNoOutputTable is not supported.', 16, 2) + VALUES('The parameter @DataDomainBoostNoOutputTable can only be used together with @BackupSoftware = ''DATA_DOMAIN_BOOST''. See https://ola.hallengren.com/sql-server-backup.html#DataDomainBoostNoOutputTable.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2585,7 +2585,7 @@ BEGIN IF @DirectoryStructure = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DirectoryStructure is not supported.', 16, 1) + VALUES('The value for the parameter @DirectoryStructure is not supported. The value cannot be an empty string. See https://ola.hallengren.com/sql-server-backup.html#DirectoryStructure.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2593,7 +2593,7 @@ BEGIN IF @AvailabilityGroupDirectoryStructure = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupDirectoryStructure is not supported.', 16, 1) + VALUES('The value for the parameter @AvailabilityGroupDirectoryStructure is not supported. The value cannot be an empty string. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupDirectoryStructure.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2601,7 +2601,7 @@ BEGIN IF @DirectoryStructureCase NOT IN('LOWER','UPPER') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DirectoryStructureCase is not supported.', 16, 1) + VALUES('The value for the parameter @DirectoryStructureCase is not supported. Supported values are LOWER and UPPER. See https://ola.hallengren.com/sql-server-backup.html#DirectoryStructureCase.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2609,37 +2609,37 @@ BEGIN IF @FileName IS NULL OR @FileName = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileName is not supported.', 16, 1) + VALUES('The value for the parameter @FileName is not supported. The value cannot be NULL or empty. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) END IF @FileName NOT LIKE '%.{FileExtension}' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileName is not supported.', 16, 2) + VALUES('The value for the parameter @FileName is not supported. The file name has to end with .{FileExtension}. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) END IF (@NumberOfFiles > 1 AND @FileName NOT LIKE '%{FileNumber}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileName is not supported.', 16, 3) + VALUES('The value for the parameter @FileName is not supported. The token {FileNumber} is required when @NumberOfFiles is greater than 1. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) END IF @FileName LIKE '%{DirectorySeparator}%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileName is not supported.', 16, 4) + VALUES('The value for the parameter @FileName is not supported. The token {DirectorySeparator} cannot be used in the file name. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) END IF @FileName LIKE '%/%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileName is not supported.', 16, 5) + VALUES('The value for the parameter @FileName is not supported. The character / cannot be used in the file name. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) END IF @FileName LIKE '%\%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileName is not supported.', 16, 6) + VALUES('The value for the parameter @FileName is not supported. The character \ cannot be used in the file name. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2647,43 +2647,43 @@ BEGIN IF (@IsHadrEnabled = 1 AND @AvailabilityGroupFileName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 1) + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported. The value cannot be NULL when the server is part of an availability group. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END IF @AvailabilityGroupFileName = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 2) + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported. The value cannot be an empty string. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END IF @AvailabilityGroupFileName NOT LIKE '%.{FileExtension}' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 3) + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported. The file name has to end with .{FileExtension}. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END IF (@NumberOfFiles > 1 AND @AvailabilityGroupFileName NOT LIKE '%{FileNumber}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 4) + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported. The token {FileNumber} is required when @NumberOfFiles is greater than 1. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END IF @AvailabilityGroupFileName LIKE '%{DirectorySeparator}%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 5) + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported. The token {DirectorySeparator} cannot be used in the file name. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END IF @AvailabilityGroupFileName LIKE '%/%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 6) + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported. The character / cannot be used in the file name. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END IF @AvailabilityGroupFileName LIKE '%\%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupFileName is not supported.', 16, 7) + VALUES('The value for the parameter @AvailabilityGroupFileName is not supported. The character \ cannot be used in the file name. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2691,7 +2691,7 @@ BEGIN IF @FileNameCase NOT IN('LOWER','UPPER') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileNameCase is not supported.', 16, 1) + VALUES('The value for the parameter @FileNameCase is not supported. Supported values are LOWER and UPPER. See https://ola.hallengren.com/sql-server-backup.html#FileNameCase.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2699,7 +2699,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(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @DirectoryStructure contains one or more tokens that are not supported.', 16, 1) + VALUES('The parameter @DirectoryStructure contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#DirectoryStructure.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2707,7 +2707,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(@AvailabilityGroupDirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS AvailabilityGroupDirectoryStructure) Temp WHERE AvailabilityGroupDirectoryStructure LIKE '%{%' OR AvailabilityGroupDirectoryStructure LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported.', 16, 1) + VALUES('The parameter @AvailabilityGroupDirectoryStructure contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupDirectoryStructure.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2715,7 +2715,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(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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]) - VALUES('The parameter @FileName contains one or more tokens that are not supported.', 16, 1) + VALUES('The parameter @FileName contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2723,7 +2723,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(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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]) - VALUES('The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported.', 16, 1) + VALUES('The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2731,7 +2731,7 @@ BEGIN IF @TokenTimezone NOT IN('LOCAL','UTC') OR @TokenTimezone IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @TokenTimezone is not supported.', 16, 1) + VALUES('The value for the parameter @TokenTimezone is not supported. Supported values are LOCAL and UTC. See https://ola.hallengren.com/sql-server-backup.html#TokenTimezone.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2739,7 +2739,7 @@ BEGIN IF @FileExtensionFull LIKE '%.%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileExtensionFull is not supported.', 16, 1) + VALUES('The value for the parameter @FileExtensionFull is not supported. Specify the file extension without a leading period. See https://ola.hallengren.com/sql-server-backup.html#FileExtensionFull.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2747,7 +2747,7 @@ BEGIN IF @FileExtensionDiff LIKE '%.%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileExtensionDiff is not supported.', 16, 1) + VALUES('The value for the parameter @FileExtensionDiff is not supported. Specify the file extension without a leading period. See https://ola.hallengren.com/sql-server-backup.html#FileExtensionDiff.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2755,7 +2755,7 @@ BEGIN IF @FileExtensionLog LIKE '%.%' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileExtensionLog is not supported.', 16, 1) + VALUES('The value for the parameter @FileExtensionLog is not supported. Specify the file extension without a leading period. See https://ola.hallengren.com/sql-server-backup.html#FileExtensionLog.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2763,25 +2763,25 @@ BEGIN IF @Init NOT IN('Y','N') OR @Init IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Init is not supported.', 16, 1) + VALUES('The value for the parameter @Init is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#Init.', 16, 1) END IF @Init = 'Y' AND @BackupType = 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Init is not supported.', 16, 2) + VALUES('Setting @Init to ''Y'' is not supported for transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#Init.', 16, 1) END IF @Init = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Init is not supported.', 16, 3) + VALUES('Setting @Init to ''Y'' is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#Init.', 16, 1) END IF @Init = 'Y' AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Init is not supported.', 16, 4) + VALUES('Setting @Init to ''Y'' is not supported when backing up to S3-compatible storage. See https://ola.hallengren.com/sql-server-backup.html#Init.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2789,19 +2789,19 @@ BEGIN IF @Format NOT IN('Y','N') OR @Format IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Format is not supported.', 16, 1) + VALUES('The value for the parameter @Format is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#Format.', 16, 1) END IF @Format = 'Y' AND @BackupType = 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Format is not supported.', 16, 2) + VALUES('Setting @Format to ''Y'' is not supported for transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#Format.', 16, 1) END IF @Format = 'Y' AND @BackupSoftware = 'DATA_DOMAIN_BOOST' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Format is not supported.', 16, 3) + VALUES('Setting @Format to ''Y'' is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#Format.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2809,25 +2809,19 @@ BEGIN IF @ObjectLevelRecoveryMap NOT IN('Y','N') OR @ObjectLevelRecoveryMap IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ObjectLevelRecoveryMap is not supported.', 16, 1) - END - - IF @ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware IS NULL - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ObjectLevelRecoveryMap is not supported.', 16, 2) + VALUES('The value for the parameter @ObjectLevelRecoveryMap is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#ObjectLevelRecoveryMap.', 16, 1) END - IF @ObjectLevelRecoveryMap = 'Y' AND @BackupSoftware <> 'LITESPEED' + IF @ObjectLevelRecoveryMap = 'Y' AND (@BackupSoftware NOT IN('LITESPEED') OR @BackupSoftware IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ObjectLevelRecoveryMap is not supported.', 16, 3) + VALUES('Setting @ObjectLevelRecoveryMap to ''Y'' is only supported with LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#ObjectLevelRecoveryMap.', 16, 1) END IF @ObjectLevelRecoveryMap = 'Y' AND @BackupType = 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ObjectLevelRecoveryMap is not supported.', 16, 4) + VALUES('Setting @ObjectLevelRecoveryMap to ''Y'' is not supported for transaction log backups. See https://ola.hallengren.com/sql-server-backup.html#ObjectLevelRecoveryMap.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2835,7 +2829,7 @@ BEGIN IF @ExcludeLogShippedFromLogBackup NOT IN('Y','N') OR @ExcludeLogShippedFromLogBackup IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExcludeLogShippedFromLogBackup is not supported.', 16, 1) + VALUES('The value for the parameter @ExcludeLogShippedFromLogBackup is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#ExcludeLogShippedFromLogBackup.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2843,13 +2837,13 @@ BEGIN IF @ExcludeSeedingFromLogBackup NOT IN('Y','N') OR @ExcludeSeedingFromLogBackup IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExcludeSeedingFromLogBackup is not supported.', 16, 1) + VALUES('The value for the parameter @ExcludeSeedingFromLogBackup is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#ExcludeSeedingFromLogBackup.', 16, 1) END IF @ExcludeSeedingFromLogBackup = 'Y' AND @BackupType <> 'LOG' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @ExcludeSeedingFromLogBackup can only be used for log backups.', 16, 2) + VALUES('The parameter @ExcludeSeedingFromLogBackup can only be used for log backups. See https://ola.hallengren.com/sql-server-backup.html#ExcludeSeedingFromLogBackup.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2857,7 +2851,7 @@ BEGIN IF @DirectoryCheck NOT IN('Y','N') OR @DirectoryCheck IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DirectoryCheck is not supported.', 16, 1) + VALUES('The value for the parameter @DirectoryCheck is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#DirectoryCheck.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2865,7 +2859,7 @@ BEGIN IF @BackupOptions IS NOT NULL AND NOT EXISTS(SELECT * FROM @URLs WHERE DirectoryPath LIKE 's3://%/%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @BackupOptions is not supported.', 16, 1) + VALUES('The parameter @BackupOptions can only be used when backing up to S3-compatible storage. See https://ola.hallengren.com/sql-server-backup.html#BackupOptions.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2873,7 +2867,7 @@ BEGIN IF @Stats <= 0 OR @Stats > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Stats is not supported.', 16, 1) + VALUES('The value for the parameter @Stats is not supported. The value has to be between 1 and 100. See https://ola.hallengren.com/sql-server-backup.html#Stats.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2881,7 +2875,7 @@ BEGIN IF @ExpireDate IS NOT NULL AND @BackupSoftware <> 'LITESPEED' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExpireDate is not supported.', 16, 1) + VALUES('The parameter @ExpireDate is only supported with SQL Server native backups and LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#ExpireDate.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2889,13 +2883,13 @@ BEGIN IF @RetainDays < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @RetainDays is not supported.', 16, 1) + VALUES('The value for the parameter @RetainDays is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-backup.html#RetainDays.', 16, 1) END IF @RetainDays IS NOT NULL AND @BackupSoftware <> 'LITESPEED' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @RetainDays is not supported.', 16, 2) + VALUES('The parameter @RetainDays is only supported with SQL Server native backups and LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#RetainDays.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2903,7 +2897,7 @@ BEGIN IF @AllowNonCopyOnlyBackupsOnForwarder NOT IN('Y','N') OR @AllowNonCopyOnlyBackupsOnForwarder IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AllowNonCopyOnlyBackupsOnForwarder is not supported.', 16, 1) + VALUES('The value for the parameter @AllowNonCopyOnlyBackupsOnForwarder is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#AllowNonCopyOnlyBackupsOnForwarder.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2911,7 +2905,7 @@ BEGIN IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StringDelimiter is not supported.', 16, 1) + VALUES('The value for the parameter @StringDelimiter is not supported. The value has to be exactly one character. See https://ola.hallengren.com/sql-server-backup.html#StringDelimiter.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2919,13 +2913,13 @@ BEGIN 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, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 1) + VALUES('The value for the parameter @DatabaseOrder is not supported. Supported values are DATABASE_NAME_ASC, DATABASE_NAME_DESC, DATABASE_SIZE_ASC, DATABASE_SIZE_DESC, LOG_SIZE_SINCE_LAST_LOG_BACKUP_ASC and LOG_SIZE_SINCE_LAST_LOG_BACKUP_DESC. See https://ola.hallengren.com/sql-server-backup.html#DatabaseOrder.', 16, 1) END IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 2) + VALUES('The parameter @DatabaseOrder is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-backup.html#DatabaseOrder.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2933,13 +2927,13 @@ BEGIN IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) + VALUES('The value for the parameter @DatabasesInParallel is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#DatabasesInParallel.', 16, 1) END IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 2) + VALUES('The parameter @DatabasesInParallel is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-backup.html#DatabasesInParallel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2947,7 +2941,7 @@ BEGIN IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) + VALUES('The value for the parameter @LogToTable is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#LogToTable.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2955,15 +2949,7 @@ BEGIN IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Execute is not supported.', 16, 1) - END - - ---------------------------------------------------------------------------------------------------- - - IF EXISTS(SELECT * FROM @Errors) - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The documentation is available at https://ola.hallengren.com/sql-server-backup.html.', 16, 1) + VALUES('The value for the parameter @Execute is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-backup.html#Execute.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2979,7 +2965,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-backup.html#Databases.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') @@ -2991,7 +2977,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroups.', 10, 1) END ---------------------------------------------------------------------------------------------------- @@ -3001,7 +2987,7 @@ BEGIN IF UPPER(@@SERVERNAME) <> UPPER(@ServerName) AND @IsHadrEnabled = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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) + VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @IsClustered = 0 THEN 'https://learn.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN @IsClustered = 1 THEN 'https://learn.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5033,7 +5019,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 16:00:55 //-- + --// Version: 2026-08-08 22:31:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5331,13 +5317,13 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1) + VALUES('ANSI_NULLS has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1) + VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-integrity-check.html.', 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') @@ -5361,19 +5347,19 @@ BEGIN 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, [State]) - VALUES('The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1) + VALUES('The table Queue is missing. It is required when @DatabasesInParallel = ''Y''. 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, [State]) - VALUES('The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) + VALUES('The table QueueDatabase is missing. It is required when @DatabasesInParallel = ''Y''. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) END IF @@TRANCOUNT <> 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The transaction count is not 0.', 16, 1) + VALUES('The stored procedure cannot be executed inside a transaction. The transaction count (@@TRANCOUNT) has to be 0. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5497,7 +5483,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DATALENGTH(DatabaseName) = 0)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Databases is not supported.', 16, 1) + VALUES('The value for the parameter @Databases is not supported. The value could not be parsed into a list of databases. See https://ola.hallengren.com/sql-server-integrity-check.html#Databases.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5589,22 +5575,28 @@ 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 @IsHadrEnabled = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @AvailabilityGroups is not supported. The value could not be parsed into a list of availability groups. See https://ola.hallengren.com/sql-server-integrity-check.html#AvailabilityGroups.', 16, 1) + END + + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroups is not supported.', 16, 1) + VALUES('The parameter @AvailabilityGroups can only be used when availability groups are enabled on the instance. See https://ola.hallengren.com/sql-server-integrity-check.html#AvailabilityGroups.', 16, 1) END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2) + VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5743,31 +5735,31 @@ BEGIN IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 1) + VALUES('The value for the parameter @CheckCommands is not supported. Supported values are CHECKDB, CHECKFILEGROUP, CHECKALLOC, CHECKTABLE and CHECKCATALOG. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) END IF EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 2) + VALUES('The value for the parameter @CheckCommands is not supported. The same check command has been specified more than once. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) END IF NOT EXISTS (SELECT * FROM @SelectedCheckCommands) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 3) + VALUES('The value for the parameter @CheckCommands is not supported. The value cannot be NULL or empty. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) 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]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 4) + VALUES('The value for the parameter @CheckCommands is not supported. CHECKDB cannot be combined with CHECKFILEGROUP, CHECKALLOC, CHECKTABLE or CHECKCATALOG. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) 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]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 5) + VALUES('The value for the parameter @CheckCommands is not supported. CHECKFILEGROUP cannot be combined with CHECKALLOC or CHECKTABLE. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5775,7 +5767,7 @@ BEGIN IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @PhysicalOnly is not supported.', 16, 1) + VALUES('The value for the parameter @PhysicalOnly is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#PhysicalOnly.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5783,13 +5775,13 @@ BEGIN IF @DataPurity NOT IN ('Y','N') OR @DataPurity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataPurity is not supported.', 16, 1) + VALUES('The value for the parameter @DataPurity is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#DataPurity.', 16, 1) END IF @PhysicalOnly = 'Y' AND @DataPurity = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameters @PhysicalOnly and @DataPurity cannot be used together.', 16, 2) + VALUES('The parameters @PhysicalOnly and @DataPurity cannot be used together. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5797,7 +5789,7 @@ BEGIN IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NoIndex is not supported.', 16, 1) + VALUES('The value for the parameter @NoIndex is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#NoIndex.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5805,13 +5797,13 @@ BEGIN IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExtendedLogicalChecks is not supported.', 16, 1) + VALUES('The value for the parameter @ExtendedLogicalChecks is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#ExtendedLogicalChecks.', 16, 1) END IF @PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameters @PhysicalOnly and @ExtendedLogicalChecks cannot be used together.', 16, 2) + VALUES('The parameters @PhysicalOnly and @ExtendedLogicalChecks cannot be used together. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5819,7 +5811,7 @@ BEGIN IF @NoInformationalMessages NOT IN ('Y','N') OR @NoInformationalMessages IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NoInformationalMessages is not supported.', 16, 1) + VALUES('The value for the parameter @NoInformationalMessages is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#NoInformationalMessages.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5827,7 +5819,7 @@ BEGIN IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @TabLock is not supported.', 16, 1) + VALUES('The value for the parameter @TabLock is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#TabLock.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5835,19 +5827,19 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileGroups is not supported.', 16, 1) + VALUES('The value for the parameter @FileGroups is not supported. The value contains one or more items that could not be parsed. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 16, 1) END IF @FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileGroups is not supported.', 16, 2) + VALUES('The value for the parameter @FileGroups is not supported. The value could not be parsed into a list of filegroups. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 16, 1) END IF @FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileGroups is not supported.', 16, 3) + VALUES('The parameter @FileGroups can only be used together with @CheckCommands = ''CHECKFILEGROUP''. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5855,19 +5847,19 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Objects is not supported.', 16, 1) + VALUES('The value for the parameter @Objects is not supported. The value contains one or more items that could not be parsed. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 16, 1) END IF (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Objects is not supported.', 16, 2) + VALUES('The value for the parameter @Objects is not supported. The value could not be parsed into a list of objects. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 16, 1) END IF (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Objects is not supported.', 16, 3) + VALUES('The parameter @Objects can only be used together with @CheckCommands = ''CHECKTABLE''. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5875,7 +5867,7 @@ BEGIN IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxDOP is not supported.', 16, 1) + VALUES('The value for the parameter @MaxDOP is not supported. The value has to be between 0 and 64. See https://ola.hallengren.com/sql-server-integrity-check.html#MaxDOP.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5883,7 +5875,7 @@ BEGIN IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupReplicas is not supported.', 16, 1) + VALUES('The value for the parameter @AvailabilityGroupReplicas is not supported. Supported values are ALL, PRIMARY, SECONDARY and PREFERRED_BACKUP_REPLICA. See https://ola.hallengren.com/sql-server-integrity-check.html#AvailabilityGroupReplicas.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5891,7 +5883,7 @@ BEGIN IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Updateability is not supported.', 16, 1) + VALUES('The value for the parameter @Updateability is not supported. Supported values are ALL, READ_ONLY and READ_WRITE. See https://ola.hallengren.com/sql-server-integrity-check.html#Updateability.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5899,21 +5891,15 @@ BEGIN IF @TimeLimit < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @TimeLimit is not supported.', 16, 1) + VALUES('The value for the parameter @TimeLimit is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-integrity-check.html#TimeLimit.', 16, 1) END ---------------------------------------------------------------------------------------------------- - IF @LockTimeout < 0 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported.', 16, 1) - END - - IF @LockTimeout > 86400 + IF @LockTimeout < 0 OR @LockTimeout > 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported.', 16, 2) + VALUES('The value for the parameter @LockTimeout is not supported. The value has to be between 0 and 86400. See https://ola.hallengren.com/sql-server-integrity-check.html#LockTimeout.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5921,7 +5907,7 @@ BEGIN IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) + VALUES('The value for the parameter @LockMessageSeverity is not supported. Supported values are 10 and 16. See https://ola.hallengren.com/sql-server-integrity-check.html#LockMessageSeverity.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5929,7 +5915,7 @@ BEGIN IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StringDelimiter is not supported.', 16, 1) + VALUES('The value for the parameter @StringDelimiter is not supported. The value has to be exactly one character. See https://ola.hallengren.com/sql-server-integrity-check.html#StringDelimiter.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5937,31 +5923,31 @@ BEGIN 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') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 1) + VALUES('The value for the parameter @DatabaseOrder is not supported. Supported values are 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 and REPLICA_LAST_GOOD_CHECK_DESC. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) END IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 14.03029 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported. DATABASEPROPERTYEX(''DatabaseName'', ''LastGoodCheckDbTime'') is not available in this version of SQL Server.', 16, 2) + VALUES('The value for the parameter @DatabaseOrder is not supported. DATABASEPROPERTYEX(''DatabaseName'', ''LastGoodCheckDbTime'') is not available in this version of SQL Server. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) END IF @DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @LogToTable = ''Y''.', 16, 3) + VALUES('The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @LogToTable = ''Y''. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) 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]) - VALUES('The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @CheckCommands = ''CHECKDB''.', 16, 4) + VALUES('The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @CheckCommands = ''CHECKDB''. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) END IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported. This parameter is not supported in Azure SQL Database.', 16, 5) + VALUES('The parameter @DatabaseOrder is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5969,13 +5955,13 @@ BEGIN IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) + VALUES('The value for the parameter @DatabasesInParallel is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabasesInParallel.', 16, 1) END IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported. This parameter is not supported in Azure SQL Database.', 16, 2) + VALUES('The parameter @DatabasesInParallel is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabasesInParallel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5983,7 +5969,7 @@ BEGIN IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) + VALUES('The value for the parameter @LogToTable is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#LogToTable.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -5991,15 +5977,7 @@ BEGIN IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Execute is not supported.', 16, 1) - END - - ---------------------------------------------------------------------------------------------------- - - IF EXISTS(SELECT * FROM @Errors) - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) + VALUES('The value for the parameter @Execute is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#Execute.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -6015,7 +5993,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#Databases.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -6027,7 +6005,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @FileGroups parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @FileGroups parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -6039,7 +6017,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @Objects parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @Objects parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') @@ -6051,7 +6029,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#AvailabilityGroups.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -6064,7 +6042,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -6077,7 +6055,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 10, 1) END ---------------------------------------------------------------------------------------------------- @@ -6087,7 +6065,7 @@ BEGIN IF UPPER(@@SERVERNAME) <> UPPER(@ServerName) AND @IsHadrEnabled = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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) + VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @IsClustered = 0 THEN 'https://learn.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN @IsClustered = 1 THEN 'https://learn.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7081,7 +7059,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 16:00:55 //-- + --// Version: 2026-08-08 22:31:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7542,13 +7520,13 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1) + VALUES('ANSI_NULLS has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1) + VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 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') @@ -7572,19 +7550,19 @@ BEGIN 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, [State]) - VALUES('The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1) + VALUES('The table Queue is missing. It is required when @DatabasesInParallel = ''Y''. 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, [State]) - VALUES('The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) + VALUES('The table QueueDatabase is missing. It is required when @DatabasesInParallel = ''Y''. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) END IF @@TRANCOUNT <> 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The transaction count is not 0.', 16, 1) + VALUES('The stored procedure cannot be executed inside a transaction. The transaction count (@@TRANCOUNT) has to be 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7707,7 +7685,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DATALENGTH(DatabaseName) = 0)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Databases is not supported.', 16, 1) + VALUES('The value for the parameter @Databases is not supported. The value could not be parsed into a list of databases. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Databases.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7799,22 +7777,28 @@ 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 @IsHadrEnabled = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '')) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @AvailabilityGroups is not supported. The value could not be parsed into a list of availability groups. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#AvailabilityGroups.', 16, 1) + END + + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroups is not supported.', 16, 1) + VALUES('The parameter @AvailabilityGroups can only be used when availability groups are enabled on the instance. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#AvailabilityGroups.', 16, 1) END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2) + VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7952,13 +7936,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLow is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationLow is not supported. Supported values are INDEX_REBUILD_ONLINE, INDEX_REBUILD_OFFLINE and INDEX_REORGANIZE. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLow.', 16, 1) END IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLow is not supported.', 16, 2) + VALUES('The value for the parameter @FragmentationLow is not supported. The same action has been specified more than once. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLow.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7966,13 +7950,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationMedium is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationMedium is not supported. Supported values are INDEX_REBUILD_ONLINE, INDEX_REBUILD_OFFLINE and INDEX_REORGANIZE. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationMedium.', 16, 1) END IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationMedium is not supported.', 16, 2) + VALUES('The value for the parameter @FragmentationMedium is not supported. The same action has been specified more than once. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationMedium.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7980,13 +7964,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'High' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationHigh is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationHigh is not supported. Supported values are INDEX_REBUILD_ONLINE, INDEX_REBUILD_OFFLINE and INDEX_REORGANIZE. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationHigh.', 16, 1) END IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationHigh is not supported.', 16, 2) + VALUES('The value for the parameter @FragmentationHigh is not supported. The same action has been specified more than once. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationHigh.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -7994,7 +7978,7 @@ BEGIN IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel1 is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationLevel1 is not supported. The value has to be greater than 0 and less than 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLevel1.', 16, 1) END @@ -8003,7 +7987,7 @@ BEGIN IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel2 is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationLevel2 is not supported. The value has to be greater than 0 and less than 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLevel2.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8011,7 +7995,7 @@ BEGIN IF @FragmentationLevel2 <= @FragmentationLevel1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel2 has to be greater than the value for @FragmentationLevel1.', 16, 1) + VALUES('The value for the parameter @FragmentationLevel2 has to be greater than the value for @FragmentationLevel1. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLevel2.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8019,7 +8003,7 @@ BEGIN IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinNumberOfPages is not supported.', 16, 1) + VALUES('The value for the parameter @MinNumberOfPages is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MinNumberOfPages.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8027,7 +8011,7 @@ BEGIN IF @MaxNumberOfPages < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxNumberOfPages is not supported.', 16, 1) + VALUES('The value for the parameter @MaxNumberOfPages is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MaxNumberOfPages.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8035,7 +8019,7 @@ BEGIN IF @MinNumberOfPages > @MaxNumberOfPages BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxNumberOfPages has to be greater than or equal to the value for @MinNumberOfPages.', 16, 1) + VALUES('The value for the parameter @MaxNumberOfPages has to be greater than or equal to the value for @MinNumberOfPages. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MaxNumberOfPages.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8043,7 +8027,7 @@ BEGIN IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @SortInTempdb is not supported.', 16, 1) + VALUES('The value for the parameter @SortInTempdb is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#SortInTempdb.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8051,7 +8035,7 @@ BEGIN IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxDOP is not supported.', 16, 1) + VALUES('The value for the parameter @MaxDOP is not supported. The value has to be between 0 and 64. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MaxDOP.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8059,7 +8043,7 @@ BEGIN IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FillFactor is not supported.', 16, 1) + VALUES('The value for the parameter @FillFactor is not supported. The value has to be between 1 and 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FillFactor.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8067,7 +8051,7 @@ BEGIN IF @PadIndex NOT IN('Y','N') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @PadIndex is not supported.', 16, 1) + VALUES('The value for the parameter @PadIndex is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#PadIndex.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8075,7 +8059,7 @@ BEGIN IF @DataCompression NOT IN('NONE', 'PAGE', 'ROW') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataCompression is not supported.', 16, 1) + VALUES('The value for the parameter @DataCompression is not supported. Supported values are NONE, PAGE and ROW. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DataCompression.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8083,13 +8067,13 @@ BEGIN IF @WaitAtLowPriorityMaxDuration < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1) + VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#WaitAtLowPriorityMaxDuration.', 16, 1) END IF @WaitAtLowPriorityAbortAfterWait = 'SELF' AND @WaitAtLowPriorityMaxDuration = 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 2) + VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported. The value has to be greater than 0 when @WaitAtLowPriorityAbortAfterWait = ''SELF''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#WaitAtLowPriorityMaxDuration.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8097,7 +8081,7 @@ BEGIN IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16, 1) + VALUES('The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported. Supported values are NONE, SELF and BLOCKERS. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#WaitAtLowPriorityAbortAfterWait.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8105,7 +8089,7 @@ BEGIN 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]) - VALUES('The parameters @WaitAtLowPriorityMaxDuration and @WaitAtLowPriorityAbortAfterWait can only be used together.', 16, 1) + VALUES('The parameters @WaitAtLowPriorityMaxDuration and @WaitAtLowPriorityAbortAfterWait can only be used together. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8113,13 +8097,13 @@ BEGIN IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Resumable is not supported.', 16, 1) + VALUES('The value for the parameter @Resumable is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Resumable.', 16, 1) END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 2) + VALUES('You can only specify one of the parameters @Resumable and @SortInTempdb. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8127,7 +8111,7 @@ BEGIN IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LOBCompaction is not supported.', 16, 1) + VALUES('The value for the parameter @LOBCompaction is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#LOBCompaction.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8135,7 +8119,7 @@ BEGIN IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @UpdateStatistics is not supported.', 16, 1) + VALUES('The value for the parameter @UpdateStatistics is not supported. Supported values are ALL, COLUMNS and INDEX. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#UpdateStatistics.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8143,7 +8127,7 @@ BEGIN IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @OnlyModifiedStatistics is not supported.', 16, 1) + VALUES('The value for the parameter @OnlyModifiedStatistics is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#OnlyModifiedStatistics.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8151,7 +8135,7 @@ BEGIN IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsModificationLevel is not supported.', 16, 1) + VALUES('The value for the parameter @StatisticsModificationLevel is not supported. The value has to be greater than 0 and less than or equal to 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsModificationLevel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8159,7 +8143,7 @@ BEGIN IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.', 16, 1) + VALUES('You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8167,7 +8151,7 @@ BEGIN IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsSample is not supported.', 16, 1) + VALUES('The value for the parameter @StatisticsSample is not supported. The value has to be between 1 and 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsSample.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8175,25 +8159,25 @@ BEGIN IF @StatisticsPersistSample NOT IN('Y','N') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsPersistSample is not supported.', 16, 1) + VALUES('The value for the parameter @StatisticsPersistSample is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsPersistSample.', 16, 1) END IF @StatisticsPersistSample IS NOT NULL AND @StatisticsSample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @StatisticsPersistSample can only be used together with @StatisticsSample.', 16, 2) + VALUES('The parameter @StatisticsPersistSample can only be used together with @StatisticsSample. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsPersistSample.', 16, 1) END IF @StatisticsPersistSample IS NOT NULL AND @StatisticsResample = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3) + VALUES('The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.03006 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsPersistSample is not supported.', 16, 4) + VALUES('The value for the parameter @StatisticsPersistSample is not supported. PERSIST_SAMPLE_PERCENT is not supported in this version of SQL Server. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsPersistSample.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8201,13 +8185,13 @@ BEGIN IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsResample is not supported.', 16, 1) + VALUES('The value for the parameter @StatisticsResample is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsResample.', 16, 1) END IF @StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsResample is not supported.', 16, 2) + VALUES('Setting @StatisticsResample to ''Y'' cannot be combined with @StatisticsSample. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsResample.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8215,7 +8199,7 @@ BEGIN IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @PartitionLevel is not supported.', 16, 1) + VALUES('The value for the parameter @PartitionLevel is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#PartitionLevel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8223,7 +8207,7 @@ BEGIN IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MSShippedObjects is not supported.', 16, 1) + VALUES('The value for the parameter @MSShippedObjects is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MSShippedObjects.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8231,13 +8215,13 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Indexes is not supported.', 16, 1) + VALUES('The value for the parameter @Indexes is not supported. The value contains one or more items that could not be parsed. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Indexes.', 16, 1) END IF @Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Indexes is not supported.', 16, 2) + VALUES('The value for the parameter @Indexes is not supported. The value could not be parsed into a list of indexes. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Indexes.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8245,35 +8229,23 @@ BEGIN IF @TimeLimit < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @TimeLimit is not supported.', 16, 1) + VALUES('The value for the parameter @TimeLimit is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#TimeLimit.', 16, 1) END ---------------------------------------------------------------------------------------------------- - IF @Delay < 0 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Delay is not supported.', 16, 1) - END - - IF @Delay >= 86400 + IF @Delay < 0 OR @Delay >= 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Delay is not supported.', 16, 2) + VALUES('The value for the parameter @Delay is not supported. The value has to be greater than or equal to 0 and less than 86400. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Delay.', 16, 1) END ---------------------------------------------------------------------------------------------------- - IF @LockTimeout < 0 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported.', 16, 1) - END - - IF @LockTimeout > 86400 + IF @LockTimeout < 0 OR @LockTimeout > 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported.', 16, 2) + VALUES('The value for the parameter @LockTimeout is not supported. The value has to be between 0 and 86400. See https://ola.hallengren.com/sql-server-integrity-check.html#LockTimeout.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8281,7 +8253,7 @@ BEGIN IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) + VALUES('The value for the parameter @LockMessageSeverity is not supported. Supported values are 10 and 16. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#LockMessageSeverity.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8289,7 +8261,7 @@ BEGIN IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StringDelimiter is not supported.', 16, 1) + VALUES('The value for the parameter @StringDelimiter is not supported. The value has to be exactly one character. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StringDelimiter.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8297,13 +8269,13 @@ BEGIN IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 1) + VALUES('The value for the parameter @DatabaseOrder is not supported. Supported values are DATABASE_NAME_ASC, DATABASE_NAME_DESC, DATABASE_SIZE_ASC and DATABASE_SIZE_DESC. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DatabaseOrder.', 16, 1) END IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 2) + VALUES('The parameter @DatabaseOrder is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DatabaseOrder.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8311,13 +8283,13 @@ BEGIN IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) + VALUES('The value for the parameter @DatabasesInParallel is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DatabasesInParallel.', 16, 1) END IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 2) + VALUES('The parameter @DatabasesInParallel is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DatabasesInParallel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8325,7 +8297,7 @@ BEGIN IF LEN(@ExecuteAsUser) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExecuteAsUser is not supported.', 16, 1) + VALUES('The value for the parameter @ExecuteAsUser is not supported. The maximum length is 128 characters. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#ExecuteAsUser.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8333,7 +8305,7 @@ BEGIN IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) + VALUES('The value for the parameter @LogToTable is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#LogToTable.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8341,15 +8313,7 @@ BEGIN IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Execute is not supported.', 16, 1) - END - - ---------------------------------------------------------------------------------------------------- - - IF EXISTS(SELECT * FROM @Errors) - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) + VALUES('The value for the parameter @Execute is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Execute.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -8365,7 +8329,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Databases.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -8377,7 +8341,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @Indexes parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @Indexes parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Indexes.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') @@ -8389,7 +8353,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#AvailabilityGroups.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -8402,7 +8366,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Indexes.', 10, 1) END ---------------------------------------------------------------------------------------------------- diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 08e08b05..56b608ff 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-08 16:00:55 +Version: 2026-08-08 22:31:52 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 16:00:55 //-- + --// Version: 2026-08-08 22:31:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -153,25 +153,25 @@ BEGIN IF @DatabaseContext IS NULL OR NOT EXISTS (SELECT * FROM sys.databases WHERE name = @DatabaseContext) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseContext is not supported.', 16, 1) + VALUES('The value for the parameter @DatabaseContext is not supported. Specify the name of an existing database.', 16, 1) END IF @Command IS NULL OR @Command = '' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Command is not supported.', 16, 1) + VALUES('The value for the parameter @Command is not supported. The value cannot be NULL or empty.', 16, 1) END IF @CommandType IS NULL OR @CommandType = '' OR LEN(@CommandType) > 60 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CommandType is not supported.', 16, 1) + VALUES('The value for the parameter @CommandType is not supported. The value cannot be NULL or empty, and the maximum length is 60 characters.', 16, 1) END IF @Mode NOT IN(1,2) OR @Mode IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Mode is not supported.', 16, 1) + VALUES('The value for the parameter @Mode is not supported. Supported values are 1 and 2.', 16, 1) END IF (@EncryptionKey IS NULL AND @EncryptionKeyPlaceholder IS NOT NULL) OR (@EncryptionKey IS NOT NULL AND @EncryptionKeyPlaceholder IS NULL) @@ -183,25 +183,25 @@ BEGIN IF @LockMessageSeverity NOT IN(10,16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) + VALUES('The value for the parameter @LockMessageSeverity is not supported. Supported values are 10 and 16.', 16, 1) END IF LEN(@ExecuteAsUser) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExecuteAsUser is not supported.', 16, 1) + VALUES('The value for the parameter @ExecuteAsUser is not supported. The maximum length is 128 characters.', 16, 1) END IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) + VALUES('The value for the parameter @LogToTable is not supported. Supported values are ''Y'' and ''N''.', 16, 1) END IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Execute is not supported.', 16, 1) + VALUES('The value for the parameter @Execute is not supported. Supported values are ''Y'' and ''N''.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 16:00:55 //-- + --// Version: 2026-08-08 22:31:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -692,13 +692,13 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1) + VALUES('ANSI_NULLS has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1) + VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-integrity-check.html.', 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') @@ -722,19 +722,19 @@ BEGIN 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, [State]) - VALUES('The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1) + VALUES('The table Queue is missing. It is required when @DatabasesInParallel = ''Y''. 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, [State]) - VALUES('The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) + VALUES('The table QueueDatabase is missing. It is required when @DatabasesInParallel = ''Y''. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) END IF @@TRANCOUNT <> 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The transaction count is not 0.', 16, 1) + VALUES('The stored procedure cannot be executed inside a transaction. The transaction count (@@TRANCOUNT) has to be 0. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -858,7 +858,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DATALENGTH(DatabaseName) = 0)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Databases is not supported.', 16, 1) + VALUES('The value for the parameter @Databases is not supported. The value could not be parsed into a list of databases. See https://ola.hallengren.com/sql-server-integrity-check.html#Databases.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -950,22 +950,28 @@ 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 @IsHadrEnabled = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroups is not supported.', 16, 1) + VALUES('The value for the parameter @AvailabilityGroups is not supported. The value could not be parsed into a list of availability groups. See https://ola.hallengren.com/sql-server-integrity-check.html#AvailabilityGroups.', 16, 1) + END + + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameter @AvailabilityGroups can only be used when availability groups are enabled on the instance. See https://ola.hallengren.com/sql-server-integrity-check.html#AvailabilityGroups.', 16, 1) END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2) + VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1104,31 +1110,31 @@ BEGIN IF EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand NOT IN('CHECKDB','CHECKFILEGROUP','CHECKALLOC','CHECKTABLE','CHECKCATALOG')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 1) + VALUES('The value for the parameter @CheckCommands is not supported. Supported values are CHECKDB, CHECKFILEGROUP, CHECKALLOC, CHECKTABLE and CHECKCATALOG. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) END IF EXISTS (SELECT * FROM @SelectedCheckCommands GROUP BY CheckCommand HAVING COUNT(*) > 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 2) + VALUES('The value for the parameter @CheckCommands is not supported. The same check command has been specified more than once. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) END IF NOT EXISTS (SELECT * FROM @SelectedCheckCommands) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 3) + VALUES('The value for the parameter @CheckCommands is not supported. The value cannot be NULL or empty. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) 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]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 4) + VALUES('The value for the parameter @CheckCommands is not supported. CHECKDB cannot be combined with CHECKFILEGROUP, CHECKALLOC, CHECKTABLE or CHECKCATALOG. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) 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]) - VALUES('The value for the parameter @CheckCommands is not supported.', 16, 5) + VALUES('The value for the parameter @CheckCommands is not supported. CHECKFILEGROUP cannot be combined with CHECKALLOC or CHECKTABLE. See https://ola.hallengren.com/sql-server-integrity-check.html#CheckCommands.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1136,7 +1142,7 @@ BEGIN IF @PhysicalOnly NOT IN ('Y','N') OR @PhysicalOnly IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @PhysicalOnly is not supported.', 16, 1) + VALUES('The value for the parameter @PhysicalOnly is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#PhysicalOnly.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1144,13 +1150,13 @@ BEGIN IF @DataPurity NOT IN ('Y','N') OR @DataPurity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataPurity is not supported.', 16, 1) + VALUES('The value for the parameter @DataPurity is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#DataPurity.', 16, 1) END IF @PhysicalOnly = 'Y' AND @DataPurity = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameters @PhysicalOnly and @DataPurity cannot be used together.', 16, 2) + VALUES('The parameters @PhysicalOnly and @DataPurity cannot be used together. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1158,7 +1164,7 @@ BEGIN IF @NoIndex NOT IN ('Y','N') OR @NoIndex IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NoIndex is not supported.', 16, 1) + VALUES('The value for the parameter @NoIndex is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#NoIndex.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1166,13 +1172,13 @@ BEGIN IF @ExtendedLogicalChecks NOT IN ('Y','N') OR @ExtendedLogicalChecks IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExtendedLogicalChecks is not supported.', 16, 1) + VALUES('The value for the parameter @ExtendedLogicalChecks is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#ExtendedLogicalChecks.', 16, 1) END IF @PhysicalOnly = 'Y' AND @ExtendedLogicalChecks = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameters @PhysicalOnly and @ExtendedLogicalChecks cannot be used together.', 16, 2) + VALUES('The parameters @PhysicalOnly and @ExtendedLogicalChecks cannot be used together. See https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1180,7 +1186,7 @@ BEGIN IF @NoInformationalMessages NOT IN ('Y','N') OR @NoInformationalMessages IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NoInformationalMessages is not supported.', 16, 1) + VALUES('The value for the parameter @NoInformationalMessages is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#NoInformationalMessages.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1188,7 +1194,7 @@ BEGIN IF @TabLock NOT IN ('Y','N') OR @TabLock IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @TabLock is not supported.', 16, 1) + VALUES('The value for the parameter @TabLock is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#TabLock.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1196,19 +1202,19 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedFileGroups WHERE DatabaseName IS NULL OR FileGroupName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileGroups is not supported.', 16, 1) + VALUES('The value for the parameter @FileGroups is not supported. The value contains one or more items that could not be parsed. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 16, 1) END IF @FileGroups IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedFileGroups) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileGroups is not supported.', 16, 2) + VALUES('The value for the parameter @FileGroups is not supported. The value could not be parsed into a list of filegroups. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 16, 1) END IF @FileGroups IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKFILEGROUP') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FileGroups is not supported.', 16, 3) + VALUES('The parameter @FileGroups can only be used together with @CheckCommands = ''CHECKFILEGROUP''. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1216,19 +1222,19 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedObjects WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Objects is not supported.', 16, 1) + VALUES('The value for the parameter @Objects is not supported. The value contains one or more items that could not be parsed. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 16, 1) END IF (@Objects IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedObjects)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Objects is not supported.', 16, 2) + VALUES('The value for the parameter @Objects is not supported. The value could not be parsed into a list of objects. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 16, 1) END IF (@Objects IS NOT NULL AND NOT EXISTS (SELECT * FROM @SelectedCheckCommands WHERE CheckCommand = 'CHECKTABLE')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Objects is not supported.', 16, 3) + VALUES('The parameter @Objects can only be used together with @CheckCommands = ''CHECKTABLE''. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1236,7 +1242,7 @@ BEGIN IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxDOP is not supported.', 16, 1) + VALUES('The value for the parameter @MaxDOP is not supported. The value has to be between 0 and 64. See https://ola.hallengren.com/sql-server-integrity-check.html#MaxDOP.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1244,7 +1250,7 @@ BEGIN IF @AvailabilityGroupReplicas NOT IN('ALL','PRIMARY','SECONDARY','PREFERRED_BACKUP_REPLICA') OR @AvailabilityGroupReplicas IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroupReplicas is not supported.', 16, 1) + VALUES('The value for the parameter @AvailabilityGroupReplicas is not supported. Supported values are ALL, PRIMARY, SECONDARY and PREFERRED_BACKUP_REPLICA. See https://ola.hallengren.com/sql-server-integrity-check.html#AvailabilityGroupReplicas.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1252,7 +1258,7 @@ BEGIN IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Updateability is not supported.', 16, 1) + VALUES('The value for the parameter @Updateability is not supported. Supported values are ALL, READ_ONLY and READ_WRITE. See https://ola.hallengren.com/sql-server-integrity-check.html#Updateability.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1260,21 +1266,15 @@ BEGIN IF @TimeLimit < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @TimeLimit is not supported.', 16, 1) + VALUES('The value for the parameter @TimeLimit is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-integrity-check.html#TimeLimit.', 16, 1) END ---------------------------------------------------------------------------------------------------- - IF @LockTimeout < 0 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported.', 16, 1) - END - - IF @LockTimeout > 86400 + IF @LockTimeout < 0 OR @LockTimeout > 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported.', 16, 2) + VALUES('The value for the parameter @LockTimeout is not supported. The value has to be between 0 and 86400. See https://ola.hallengren.com/sql-server-integrity-check.html#LockTimeout.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1282,7 +1282,7 @@ BEGIN IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) + VALUES('The value for the parameter @LockMessageSeverity is not supported. Supported values are 10 and 16. See https://ola.hallengren.com/sql-server-integrity-check.html#LockMessageSeverity.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1290,7 +1290,7 @@ BEGIN IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StringDelimiter is not supported.', 16, 1) + VALUES('The value for the parameter @StringDelimiter is not supported. The value has to be exactly one character. See https://ola.hallengren.com/sql-server-integrity-check.html#StringDelimiter.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1298,31 +1298,31 @@ BEGIN 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') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 1) + VALUES('The value for the parameter @DatabaseOrder is not supported. Supported values are 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 and REPLICA_LAST_GOOD_CHECK_DESC. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) END IF @DatabaseOrder IN('DATABASE_LAST_GOOD_CHECK_ASC','DATABASE_LAST_GOOD_CHECK_DESC') AND NOT (@Version >= 14.03029 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported. DATABASEPROPERTYEX(''DatabaseName'', ''LastGoodCheckDbTime'') is not available in this version of SQL Server.', 16, 2) + VALUES('The value for the parameter @DatabaseOrder is not supported. DATABASEPROPERTYEX(''DatabaseName'', ''LastGoodCheckDbTime'') is not available in this version of SQL Server. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) END IF @DatabaseOrder IN('REPLICA_LAST_GOOD_CHECK_ASC','REPLICA_LAST_GOOD_CHECK_DESC') AND @LogToTable = 'N' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @LogToTable = ''Y''.', 16, 3) + VALUES('The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @LogToTable = ''Y''. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) 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]) - VALUES('The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @CheckCommands = ''CHECKDB''.', 16, 4) + VALUES('The value for the parameter @DatabaseOrder is not supported. You need to provide the parameter @CheckCommands = ''CHECKDB''. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) END IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported. This parameter is not supported in Azure SQL Database.', 16, 5) + VALUES('The parameter @DatabaseOrder is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabaseOrder.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1330,13 +1330,13 @@ BEGIN IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) + VALUES('The value for the parameter @DatabasesInParallel is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabasesInParallel.', 16, 1) END IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported. This parameter is not supported in Azure SQL Database.', 16, 2) + VALUES('The parameter @DatabasesInParallel is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-integrity-check.html#DatabasesInParallel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1344,7 +1344,7 @@ BEGIN IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) + VALUES('The value for the parameter @LogToTable is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#LogToTable.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1352,15 +1352,7 @@ BEGIN IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Execute is not supported.', 16, 1) - END - - ---------------------------------------------------------------------------------------------------- - - IF EXISTS(SELECT * FROM @Errors) - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The documentation is available at https://ola.hallengren.com/sql-server-integrity-check.html.', 16, 1) + VALUES('The value for the parameter @Execute is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-integrity-check.html#Execute.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1376,7 +1368,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#Databases.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1388,7 +1380,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @FileGroups parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @FileGroups parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1400,7 +1392,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @Objects parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @Objects parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') @@ -1412,7 +1404,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#AvailabilityGroups.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1425,7 +1417,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases have been selected in the @FileGroups parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#FileGroups.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -1438,7 +1430,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases have been selected in the @Objects parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-integrity-check.html#Objects.', 10, 1) END ---------------------------------------------------------------------------------------------------- @@ -1448,7 +1440,7 @@ BEGIN IF UPPER(@@SERVERNAME) <> UPPER(@ServerName) AND @IsHadrEnabled = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @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 @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) + VALUES('The @@SERVERNAME does not match SERVERPROPERTY(''ServerName''). See ' + CASE WHEN @IsClustered = 0 THEN 'https://learn.microsoft.com/en-us/sql/database-engine/install-windows/rename-a-computer-that-hosts-a-stand-alone-instance-of-sql-server' WHEN @IsClustered = 1 THEN 'https://learn.microsoft.com/en-us/sql/sql-server/failover-clusters/install/rename-a-sql-server-failover-cluster-instance' END + '.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2442,7 +2434,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 16:00:55 //-- + --// Version: 2026-08-08 22:31:52 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2903,13 +2895,13 @@ BEGIN IF NOT (SELECT uses_ansi_nulls FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('ANSI_NULLS has to be set to ON for the stored procedure.', 16, 1) + VALUES('ANSI_NULLS has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END IF NOT (SELECT uses_quoted_identifier FROM sys.sql_modules WHERE [object_id] = @@PROCID) = 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure.', 16, 1) + VALUES('QUOTED_IDENTIFIER has to be set to ON for the stored procedure. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 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') @@ -2933,19 +2925,19 @@ BEGIN 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, [State]) - VALUES('The table Queue is missing. Download https://ola.hallengren.com/scripts/Queue.sql.', 16, 1) + VALUES('The table Queue is missing. It is required when @DatabasesInParallel = ''Y''. 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, [State]) - VALUES('The table QueueDatabase is missing. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) + VALUES('The table QueueDatabase is missing. It is required when @DatabasesInParallel = ''Y''. Download https://ola.hallengren.com/scripts/QueueDatabase.sql.', 16, 1) END IF @@TRANCOUNT <> 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The transaction count is not 0.', 16, 1) + VALUES('The stored procedure cannot be executed inside a transaction. The transaction count (@@TRANCOUNT) has to be 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3068,7 +3060,7 @@ BEGIN IF @Databases IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedDatabases) OR EXISTS(SELECT * FROM @SelectedDatabases WHERE DatabaseName IS NULL OR DATALENGTH(DatabaseName) = 0)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Databases is not supported.', 16, 1) + VALUES('The value for the parameter @Databases is not supported. The value could not be parsed into a list of databases. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Databases.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3160,22 +3152,28 @@ 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 @IsHadrEnabled = 0) + IF @AvailabilityGroups IS NOT NULL AND (NOT EXISTS(SELECT * FROM @SelectedAvailabilityGroups) OR EXISTS(SELECT * FROM @SelectedAvailabilityGroups WHERE AvailabilityGroupName IS NULL OR AvailabilityGroupName = '')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @AvailabilityGroups is not supported.', 16, 1) + VALUES('The value for the parameter @AvailabilityGroups is not supported. The value could not be parsed into a list of availability groups. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#AvailabilityGroups.', 16, 1) + END + + IF @AvailabilityGroups IS NOT NULL AND @IsHadrEnabled = 0 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameter @AvailabilityGroups can only be used when availability groups are enabled on the instance. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#AvailabilityGroups.', 16, 1) END IF (@Databases IS NULL AND @AvailabilityGroups IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups.', 16, 2) + VALUES('You need to specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END IF (@Databases IS NOT NULL AND @AvailabilityGroups IS NOT NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups.', 16, 3) + VALUES('You can only specify one of the parameters @Databases and @AvailabilityGroups. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3313,13 +3311,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLow is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationLow is not supported. Supported values are INDEX_REBUILD_ONLINE, INDEX_REBUILD_OFFLINE and INDEX_REORGANIZE. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLow.', 16, 1) END IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Low' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLow is not supported.', 16, 2) + VALUES('The value for the parameter @FragmentationLow is not supported. The same action has been specified more than once. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLow.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3327,13 +3325,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationMedium is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationMedium is not supported. Supported values are INDEX_REBUILD_ONLINE, INDEX_REBUILD_OFFLINE and INDEX_REORGANIZE. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationMedium.', 16, 1) END IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'Medium' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationMedium is not supported.', 16, 2) + VALUES('The value for the parameter @FragmentationMedium is not supported. The same action has been specified more than once. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationMedium.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3341,13 +3339,13 @@ BEGIN IF EXISTS (SELECT [Action] FROM @ActionsPreferred WHERE FragmentationGroup = 'High' AND [Action] NOT IN(SELECT * FROM @Actions)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationHigh is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationHigh is not supported. Supported values are INDEX_REBUILD_ONLINE, INDEX_REBUILD_OFFLINE and INDEX_REORGANIZE. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationHigh.', 16, 1) END IF EXISTS (SELECT * FROM @ActionsPreferred WHERE FragmentationGroup = 'High' GROUP BY [Action] HAVING COUNT(*) > 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationHigh is not supported.', 16, 2) + VALUES('The value for the parameter @FragmentationHigh is not supported. The same action has been specified more than once. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationHigh.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3355,7 +3353,7 @@ BEGIN IF @FragmentationLevel1 <= 0 OR @FragmentationLevel1 >= 100 OR @FragmentationLevel1 IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel1 is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationLevel1 is not supported. The value has to be greater than 0 and less than 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLevel1.', 16, 1) END @@ -3364,7 +3362,7 @@ BEGIN IF @FragmentationLevel2 <= 0 OR @FragmentationLevel2 >= 100 OR @FragmentationLevel2 IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel2 is not supported.', 16, 1) + VALUES('The value for the parameter @FragmentationLevel2 is not supported. The value has to be greater than 0 and less than 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLevel2.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3372,7 +3370,7 @@ BEGIN IF @FragmentationLevel2 <= @FragmentationLevel1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FragmentationLevel2 has to be greater than the value for @FragmentationLevel1.', 16, 1) + VALUES('The value for the parameter @FragmentationLevel2 has to be greater than the value for @FragmentationLevel1. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FragmentationLevel2.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3380,7 +3378,7 @@ BEGIN IF @MinNumberOfPages < 0 OR @MinNumberOfPages IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MinNumberOfPages is not supported.', 16, 1) + VALUES('The value for the parameter @MinNumberOfPages is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MinNumberOfPages.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3388,7 +3386,7 @@ BEGIN IF @MaxNumberOfPages < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxNumberOfPages is not supported.', 16, 1) + VALUES('The value for the parameter @MaxNumberOfPages is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MaxNumberOfPages.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3396,7 +3394,7 @@ BEGIN IF @MinNumberOfPages > @MaxNumberOfPages BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxNumberOfPages has to be greater than or equal to the value for @MinNumberOfPages.', 16, 1) + VALUES('The value for the parameter @MaxNumberOfPages has to be greater than or equal to the value for @MinNumberOfPages. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MaxNumberOfPages.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3404,7 +3402,7 @@ BEGIN IF @SortInTempdb NOT IN('Y','N') OR @SortInTempdb IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @SortInTempdb is not supported.', 16, 1) + VALUES('The value for the parameter @SortInTempdb is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#SortInTempdb.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3412,7 +3410,7 @@ BEGIN IF @MaxDOP < 0 OR @MaxDOP > 64 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxDOP is not supported.', 16, 1) + VALUES('The value for the parameter @MaxDOP is not supported. The value has to be between 0 and 64. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MaxDOP.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3420,7 +3418,7 @@ BEGIN IF @FillFactor <= 0 OR @FillFactor > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @FillFactor is not supported.', 16, 1) + VALUES('The value for the parameter @FillFactor is not supported. The value has to be between 1 and 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#FillFactor.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3428,7 +3426,7 @@ BEGIN IF @PadIndex NOT IN('Y','N') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @PadIndex is not supported.', 16, 1) + VALUES('The value for the parameter @PadIndex is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#PadIndex.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3436,7 +3434,7 @@ BEGIN IF @DataCompression NOT IN('NONE', 'PAGE', 'ROW') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DataCompression is not supported.', 16, 1) + VALUES('The value for the parameter @DataCompression is not supported. Supported values are NONE, PAGE and ROW. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DataCompression.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3444,13 +3442,13 @@ BEGIN IF @WaitAtLowPriorityMaxDuration < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 1) + VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#WaitAtLowPriorityMaxDuration.', 16, 1) END IF @WaitAtLowPriorityAbortAfterWait = 'SELF' AND @WaitAtLowPriorityMaxDuration = 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported.', 16, 2) + VALUES('The value for the parameter @WaitAtLowPriorityMaxDuration is not supported. The value has to be greater than 0 when @WaitAtLowPriorityAbortAfterWait = ''SELF''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#WaitAtLowPriorityMaxDuration.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3458,7 +3456,7 @@ BEGIN IF @WaitAtLowPriorityAbortAfterWait NOT IN('NONE','SELF','BLOCKERS') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported.', 16, 1) + VALUES('The value for the parameter @WaitAtLowPriorityAbortAfterWait is not supported. Supported values are NONE, SELF and BLOCKERS. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#WaitAtLowPriorityAbortAfterWait.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3466,7 +3464,7 @@ BEGIN 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]) - VALUES('The parameters @WaitAtLowPriorityMaxDuration and @WaitAtLowPriorityAbortAfterWait can only be used together.', 16, 1) + VALUES('The parameters @WaitAtLowPriorityMaxDuration and @WaitAtLowPriorityAbortAfterWait can only be used together. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3474,13 +3472,13 @@ BEGIN IF @Resumable NOT IN('Y','N') OR @Resumable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Resumable is not supported.', 16, 1) + VALUES('The value for the parameter @Resumable is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Resumable.', 16, 1) END IF @Resumable = 'Y' AND @SortInTempdb = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You can only specify one of the parameters @Resumable and @SortInTempdb.', 16, 2) + VALUES('You can only specify one of the parameters @Resumable and @SortInTempdb. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3488,7 +3486,7 @@ BEGIN IF @LOBCompaction NOT IN('Y','N') OR @LOBCompaction IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LOBCompaction is not supported.', 16, 1) + VALUES('The value for the parameter @LOBCompaction is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#LOBCompaction.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3496,7 +3494,7 @@ BEGIN IF @UpdateStatistics NOT IN('ALL','COLUMNS','INDEX') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @UpdateStatistics is not supported.', 16, 1) + VALUES('The value for the parameter @UpdateStatistics is not supported. Supported values are ALL, COLUMNS and INDEX. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#UpdateStatistics.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3504,7 +3502,7 @@ BEGIN IF @OnlyModifiedStatistics NOT IN('Y','N') OR @OnlyModifiedStatistics IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @OnlyModifiedStatistics is not supported.', 16, 1) + VALUES('The value for the parameter @OnlyModifiedStatistics is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#OnlyModifiedStatistics.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3512,7 +3510,7 @@ BEGIN IF @StatisticsModificationLevel <= 0 OR @StatisticsModificationLevel > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsModificationLevel is not supported.', 16, 1) + VALUES('The value for the parameter @StatisticsModificationLevel is not supported. The value has to be greater than 0 and less than or equal to 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsModificationLevel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3520,7 +3518,7 @@ BEGIN IF @OnlyModifiedStatistics = 'Y' AND @StatisticsModificationLevel IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel.', 16, 1) + VALUES('You can only specify one of the parameters @OnlyModifiedStatistics and @StatisticsModificationLevel. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3528,7 +3526,7 @@ BEGIN IF @StatisticsSample <= 0 OR @StatisticsSample > 100 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsSample is not supported.', 16, 1) + VALUES('The value for the parameter @StatisticsSample is not supported. The value has to be between 1 and 100. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsSample.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3536,25 +3534,25 @@ BEGIN IF @StatisticsPersistSample NOT IN('Y','N') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsPersistSample is not supported.', 16, 1) + VALUES('The value for the parameter @StatisticsPersistSample is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsPersistSample.', 16, 1) END IF @StatisticsPersistSample IS NOT NULL AND @StatisticsSample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @StatisticsPersistSample can only be used together with @StatisticsSample.', 16, 2) + VALUES('The parameter @StatisticsPersistSample can only be used together with @StatisticsSample. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsPersistSample.', 16, 1) END IF @StatisticsPersistSample IS NOT NULL AND @StatisticsResample = 'Y' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together.', 16, 3) + VALUES('The parameters @StatisticsPersistSample and @StatisticsResample cannot be used together. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) END IF @StatisticsPersistSample IS NOT NULL AND NOT (@Version >= 14.03006 OR @EngineEdition = 5 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsPersistSample is not supported.', 16, 4) + VALUES('The value for the parameter @StatisticsPersistSample is not supported. PERSIST_SAMPLE_PERCENT is not supported in this version of SQL Server. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsPersistSample.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3562,13 +3560,13 @@ BEGIN IF @StatisticsResample NOT IN('Y','N') OR @StatisticsResample IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsResample is not supported.', 16, 1) + VALUES('The value for the parameter @StatisticsResample is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsResample.', 16, 1) END IF @StatisticsResample = 'Y' AND @StatisticsSample IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StatisticsResample is not supported.', 16, 2) + VALUES('Setting @StatisticsResample to ''Y'' cannot be combined with @StatisticsSample. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StatisticsResample.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3576,7 +3574,7 @@ BEGIN IF @PartitionLevel NOT IN('Y','N') OR @PartitionLevel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @PartitionLevel is not supported.', 16, 1) + VALUES('The value for the parameter @PartitionLevel is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#PartitionLevel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3584,7 +3582,7 @@ BEGIN IF @MSShippedObjects NOT IN('Y','N') OR @MSShippedObjects IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MSShippedObjects is not supported.', 16, 1) + VALUES('The value for the parameter @MSShippedObjects is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#MSShippedObjects.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3592,13 +3590,13 @@ BEGIN IF EXISTS(SELECT * FROM @SelectedIndexes WHERE DatabaseName IS NULL OR SchemaName IS NULL OR ObjectName IS NULL OR IndexName IS NULL) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Indexes is not supported.', 16, 1) + VALUES('The value for the parameter @Indexes is not supported. The value contains one or more items that could not be parsed. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Indexes.', 16, 1) END IF @Indexes IS NOT NULL AND NOT EXISTS(SELECT * FROM @SelectedIndexes) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Indexes is not supported.', 16, 2) + VALUES('The value for the parameter @Indexes is not supported. The value could not be parsed into a list of indexes. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Indexes.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3606,35 +3604,23 @@ BEGIN IF @TimeLimit < 0 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @TimeLimit is not supported.', 16, 1) + VALUES('The value for the parameter @TimeLimit is not supported. The value has to be greater than or equal to 0. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#TimeLimit.', 16, 1) END ---------------------------------------------------------------------------------------------------- - IF @Delay < 0 + IF @Delay < 0 OR @Delay >= 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Delay is not supported.', 16, 1) - END - - IF @Delay >= 86400 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Delay is not supported.', 16, 2) + VALUES('The value for the parameter @Delay is not supported. The value has to be greater than or equal to 0 and less than 86400. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Delay.', 16, 1) END ---------------------------------------------------------------------------------------------------- - IF @LockTimeout < 0 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported.', 16, 1) - END - - IF @LockTimeout > 86400 + IF @LockTimeout < 0 OR @LockTimeout > 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported.', 16, 2) + VALUES('The value for the parameter @LockTimeout is not supported. The value has to be between 0 and 86400. See https://ola.hallengren.com/sql-server-integrity-check.html#LockTimeout.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3642,7 +3628,7 @@ BEGIN IF @LockMessageSeverity NOT IN(10, 16) OR @LockMessageSeverity IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockMessageSeverity is not supported.', 16, 1) + VALUES('The value for the parameter @LockMessageSeverity is not supported. Supported values are 10 and 16. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#LockMessageSeverity.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3650,7 +3636,7 @@ BEGIN IF @StringDelimiter IS NULL OR LEN(@StringDelimiter) <> 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @StringDelimiter is not supported.', 16, 1) + VALUES('The value for the parameter @StringDelimiter is not supported. The value has to be exactly one character. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#StringDelimiter.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3658,13 +3644,13 @@ BEGIN IF @DatabaseOrder NOT IN('DATABASE_NAME_ASC','DATABASE_NAME_DESC','DATABASE_SIZE_ASC','DATABASE_SIZE_DESC') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 1) + VALUES('The value for the parameter @DatabaseOrder is not supported. Supported values are DATABASE_NAME_ASC, DATABASE_NAME_DESC, DATABASE_SIZE_ASC and DATABASE_SIZE_DESC. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DatabaseOrder.', 16, 1) END IF @DatabaseOrder IS NOT NULL AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabaseOrder is not supported.', 16, 2) + VALUES('The parameter @DatabaseOrder is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DatabaseOrder.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3672,13 +3658,13 @@ BEGIN IF @DatabasesInParallel NOT IN('Y','N') OR @DatabasesInParallel IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 1) + VALUES('The value for the parameter @DatabasesInParallel is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DatabasesInParallel.', 16, 1) END IF @DatabasesInParallel = 'Y' AND @EngineEdition = 5 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @DatabasesInParallel is not supported.', 16, 2) + VALUES('The parameter @DatabasesInParallel is not supported in Azure SQL Database. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#DatabasesInParallel.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3686,7 +3672,7 @@ BEGIN IF LEN(@ExecuteAsUser) > 128 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @ExecuteAsUser is not supported.', 16, 1) + VALUES('The value for the parameter @ExecuteAsUser is not supported. The maximum length is 128 characters. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#ExecuteAsUser.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3694,7 +3680,7 @@ BEGIN IF @LogToTable NOT IN('Y','N') OR @LogToTable IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LogToTable is not supported.', 16, 1) + VALUES('The value for the parameter @LogToTable is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#LogToTable.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3702,15 +3688,7 @@ BEGIN IF @Execute NOT IN('Y','N') OR @Execute IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @Execute is not supported.', 16, 1) - END - - ---------------------------------------------------------------------------------------------------- - - IF EXISTS(SELECT * FROM @Errors) - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The documentation is available at https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html.', 16, 1) + VALUES('The value for the parameter @Execute is not supported. Supported values are ''Y'' and ''N''. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Execute.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -3726,7 +3704,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @Databases parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Databases.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -3738,7 +3716,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases in the @Indexes parameter do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases in the @Indexes parameter do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Indexes.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(AvailabilityGroupName) AS nvarchar(max)), ', ') @@ -3750,7 +3728,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following availability groups do not exist: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following availability groups do not exist: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#AvailabilityGroups.', 10, 1) END SELECT @ErrorMessage = STRING_AGG(CAST(QUOTENAME(DatabaseName) AS nvarchar(max)), ', ') @@ -3763,7 +3741,7 @@ BEGIN IF @ErrorMessage IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '.', 10, 1) + VALUES('The following databases have been selected in the @Indexes parameter, but not in the @Databases or @AvailabilityGroups parameters: ' + @ErrorMessage + '. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#Indexes.', 10, 1) END ---------------------------------------------------------------------------------------------------- diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index f135288e..47169c0a 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -544a4e37c1e4c58625b6e70093043e78befd1924aeabeb81f8592bcb6b26760e CommandExecute.sql +cc3afd929be7facb7a3555082029d157e9d8aad6e249eecf107d186504bf5ded CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -2cc8a864403f3e611e152f92c4cc7f0321f1732639e06409236058ba50932a86 DatabaseBackup.sql -46010b3074a0905e0a03a84d810d728122edbae9260ae2ca5308662c0d930987 DatabaseIntegrityCheck.sql -61c06a95b51c21ab2c3e64d82915dc10841f50a514d3011ea5d0461814c4678e IndexOptimize.sql -dbbfe1aee6319e9a7066817a343bc7f04786d6c668bc693889e9cfeec455b1fc MaintenanceSolution.sql -e1920c34889256f24af2304ab5e471c47b0c5da10e1cb98be6fa3a3df5301e29 MaintenanceSolutionAzureSQLDatabase.sql +bcd3e02aa7cd8a23a4449959241ebbc895ddb46edf5f95abf018f50e730d82c4 DatabaseBackup.sql +1634e52d022d5f71bde038ed99ee068bc710c7d38ef654e36058ee653b6cfefc DatabaseIntegrityCheck.sql +1f1780947e99d354de8b9925f5708745370d403b9b81a870ee460720a1d8164b IndexOptimize.sql +da8350388828bc519386039206026d635fc042b36f14e6cc462bdb131b73f9f4 MaintenanceSolution.sql +6d032916be9ee1e9a2a5e58728cb3cbfe59d6695ce11738f937e31e6d042b0fe MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 9c1d363a641c46ff5cb325fc8e3e078c45c3c08c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 8 Aug 2026 22:48:31 +0200 Subject: [PATCH 157/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 4 ++-- DatabaseIntegrityCheck.sql | 10 +++++----- IndexOptimize.sql | 4 ++-- MaintenanceSolution.sql | 14 +++++++------- MaintenanceSolutionAzureSQLDatabase.sql | 10 +++++----- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 28 insertions(+), 28 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 1d65e9d5..1cb4bd35 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-08 22:31:52 //-- + --// Version: 2026-08-08 22:47:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 57a629cb..32ec4d26 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:31:52 //-- + --// Version: 2026-08-08 22:47:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1557,7 +1557,7 @@ BEGIN VALUES('The parameter @MaxTransferSize is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @MaxTransferSize > 4194304 AND @Directory IS NOT NULL AND @BackupSoftware IS NULL + IF @MaxTransferSize > 4194304 AND @URL IS NULL AND @BackupSoftware IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The value for the parameter @MaxTransferSize is not supported. The maximum value for SQL Server native backups to disk is 4194304. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 61446be7..277b0999 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:31:52 //-- + --// Version: 2026-08-08 22:47:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -917,10 +917,10 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @LockTimeout < 0 OR @LockTimeout > 86400 - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported. The value has to be between 0 and 86400. See https://ola.hallengren.com/sql-server-integrity-check.html#LockTimeout.', 16, 1) + IF @LockTimeout < 0 OR @LockTimeout > 86400 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @LockTimeout is not supported. The value has to be between 0 and 86400. See https://ola.hallengren.com/sql-server-integrity-check.html#LockTimeout.', 16, 1) END ---------------------------------------------------------------------------------------------------- diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 672532e4..2ee45568 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:31:52 //-- + --// Version: 2026-08-08 22:47:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1242,7 +1242,7 @@ BEGIN IF @LockTimeout < 0 OR @LockTimeout > 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported. The value has to be between 0 and 86400. See https://ola.hallengren.com/sql-server-integrity-check.html#LockTimeout.', 16, 1) + VALUES('The value for the parameter @LockTimeout is not supported. The value has to be between 0 and 86400. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#LockTimeout.', 16, 1) END ---------------------------------------------------------------------------------------------------- diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 884a6c8f..e36487b7 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: 2026-08-08 22:31:52 +Version: 2026-08-08 22:47:49 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:31:52 //-- + --// Version: 2026-08-08 22:47:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:31:52 //-- + --// Version: 2026-08-08 22:47:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1956,7 +1956,7 @@ BEGIN VALUES('The parameter @MaxTransferSize is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @MaxTransferSize > 4194304 AND @Directory IS NOT NULL AND @BackupSoftware IS NULL + IF @MaxTransferSize > 4194304 AND @URL IS NULL AND @BackupSoftware IS NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The value for the parameter @MaxTransferSize is not supported. The maximum value for SQL Server native backups to disk is 4194304. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) @@ -5019,7 +5019,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:31:52 //-- + --// Version: 2026-08-08 22:47:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7059,7 +7059,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:31:52 //-- + --// Version: 2026-08-08 22:47:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -8245,7 +8245,7 @@ BEGIN IF @LockTimeout < 0 OR @LockTimeout > 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported. The value has to be between 0 and 86400. See https://ola.hallengren.com/sql-server-integrity-check.html#LockTimeout.', 16, 1) + VALUES('The value for the parameter @LockTimeout is not supported. The value has to be between 0 and 86400. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#LockTimeout.', 16, 1) END ---------------------------------------------------------------------------------------------------- diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 56b608ff..f7676c1d 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-08 22:31:52 +Version: 2026-08-08 22:47:49 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:31:52 //-- + --// Version: 2026-08-08 22:47:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:31:52 //-- + --// Version: 2026-08-08 22:47:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2434,7 +2434,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:31:52 //-- + --// Version: 2026-08-08 22:47:49 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3620,7 +3620,7 @@ BEGIN IF @LockTimeout < 0 OR @LockTimeout > 86400 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @LockTimeout is not supported. The value has to be between 0 and 86400. See https://ola.hallengren.com/sql-server-integrity-check.html#LockTimeout.', 16, 1) + VALUES('The value for the parameter @LockTimeout is not supported. The value has to be between 0 and 86400. See https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html#LockTimeout.', 16, 1) END ---------------------------------------------------------------------------------------------------- diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 47169c0a..6d1741e6 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -cc3afd929be7facb7a3555082029d157e9d8aad6e249eecf107d186504bf5ded CommandExecute.sql +a30ca38ed766ffdd79cef9e3acf3a5c34bb8996253e4c51869d7045583f22f59 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -bcd3e02aa7cd8a23a4449959241ebbc895ddb46edf5f95abf018f50e730d82c4 DatabaseBackup.sql -1634e52d022d5f71bde038ed99ee068bc710c7d38ef654e36058ee653b6cfefc DatabaseIntegrityCheck.sql -1f1780947e99d354de8b9925f5708745370d403b9b81a870ee460720a1d8164b IndexOptimize.sql -da8350388828bc519386039206026d635fc042b36f14e6cc462bdb131b73f9f4 MaintenanceSolution.sql -6d032916be9ee1e9a2a5e58728cb3cbfe59d6695ce11738f937e31e6d042b0fe MaintenanceSolutionAzureSQLDatabase.sql +5f6da0fa014c1a7ea8232dff2c26d9fefc65b92b8e2239219512c633b6f5af79 DatabaseBackup.sql +8b9961808f9b560236620cb62d61f866d19745be6dd5e95d0bff724422a11c1f DatabaseIntegrityCheck.sql +9fba01dc66458aa89c8d75dbb546b507a16aafd7c3070541ef634b03721f7d5d IndexOptimize.sql +1cde95ba99cc35bda788a778b722b25f59411decf71ba89abc22a5ae65693dae MaintenanceSolution.sql +90077a690961e6ebf022266d39e55645aab318e37e21851abcad0aa3d80a1034 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 130785dc1205d9625fe66e4525f1075107539a8c Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sat, 8 Aug 2026 23:44:32 +0200 Subject: [PATCH 158/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 6 +++--- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 14 +++++++------- MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 23 insertions(+), 23 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 1cb4bd35..6e0f5ed0 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-08 22:47:49 //-- + --// Version: 2026-08-08 23:29:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 32ec4d26..ff65d688 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:47:49 //-- + --// Version: 2026-08-08 23:29:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3022,7 +3022,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT @CurrentUserAccess = 'SINGLE_USER' AND NOT @CurrentInStandby = 1 - AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentAvailabilityGroupRole IS NULL) + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole NOT IN('PRIMARY','SECONDARY') OR @CurrentAvailabilityGroupRole IS NULL)) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) @@ -3229,7 +3229,7 @@ BEGIN 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 @ContainedAvailabilityGroupListenerConnection = 0)) - AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentAvailabilityGroupRole IS NULL) + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole NOT IN('PRIMARY','SECONDARY') OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 277b0999..58ca7bd8 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:47:49 //-- + --// Version: 2026-08-08 23:29:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 2ee45568..54b01be2 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:47:49 //-- + --// Version: 2026-08-08 23:29:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index e36487b7..b5498240 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: 2026-08-08 22:47:49 +Version: 2026-08-08 23:29:24 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:47:49 //-- + --// Version: 2026-08-08 23:29:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:47:49 //-- + --// Version: 2026-08-08 23:29:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3421,7 +3421,7 @@ BEGIN IF @CurrentDatabaseState = 'ONLINE' AND NOT @CurrentUserAccess = 'SINGLE_USER' AND NOT @CurrentInStandby = 1 - AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentAvailabilityGroupRole IS NULL) + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole NOT IN('PRIMARY','SECONDARY') OR @CurrentAvailabilityGroupRole IS NULL)) AND (@CurrentAvailabilityGroupRole = 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL) AND (@CurrentDistributedAvailabilityGroupRole = 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL) AND (@BackupType IN('DIFF','FULL') OR (@ChangeBackupType = 'Y' AND @CurrentBackupType = 'LOG' AND @CurrentRecoveryModel IN('FULL','BULK_LOGGED') AND @CurrentLogLSN IS NULL AND NOT (@CurrentDatabaseName = 'master' AND @ContainedAvailabilityGroupListenerConnection = 0))) AND (@BackupInProgress = 0 OR @BackupInProgress IS NULL) @@ -3628,7 +3628,7 @@ BEGIN 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 @ContainedAvailabilityGroupListenerConnection = 0)) - AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentAvailabilityGroupRole IS NULL) + AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND (@CurrentAvailabilityGroupRole NOT IN('PRIMARY','SECONDARY') OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentAvailabilityGroupRole <> 'PRIMARY' OR @CurrentAvailabilityGroupRole IS NULL)) AND NOT (@CurrentAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 1 AND (@CurrentIsPreferredBackupReplica <> 1 OR @CurrentIsPreferredBackupReplica IS NULL) AND @OverrideBackupPreference = 'N') AND NOT (@CurrentDistributedAvailabilityGroup IS NOT NULL AND @CurrentBackupOperationSupportedOnSecondaryReplicas = 0 AND (@CurrentDistributedAvailabilityGroupRole <> 'PRIMARY' OR @CurrentDistributedAvailabilityGroupRole IS NULL)) @@ -5019,7 +5019,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:47:49 //-- + --// Version: 2026-08-08 23:29:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7059,7 +7059,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:47:49 //-- + --// Version: 2026-08-08 23:29:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index f7676c1d..41282bbb 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-08 22:47:49 +Version: 2026-08-08 23:29:24 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:47:49 //-- + --// Version: 2026-08-08 23:29:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:47:49 //-- + --// Version: 2026-08-08 23:29:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2434,7 +2434,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 22:47:49 //-- + --// Version: 2026-08-08 23:29:24 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 6d1741e6..51740a9c 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -a30ca38ed766ffdd79cef9e3acf3a5c34bb8996253e4c51869d7045583f22f59 CommandExecute.sql +7ef31cdc5df8c168ccafac0115ffa1692d218153b3769c06bac8dbcd369cde65 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -5f6da0fa014c1a7ea8232dff2c26d9fefc65b92b8e2239219512c633b6f5af79 DatabaseBackup.sql -8b9961808f9b560236620cb62d61f866d19745be6dd5e95d0bff724422a11c1f DatabaseIntegrityCheck.sql -9fba01dc66458aa89c8d75dbb546b507a16aafd7c3070541ef634b03721f7d5d IndexOptimize.sql -1cde95ba99cc35bda788a778b722b25f59411decf71ba89abc22a5ae65693dae MaintenanceSolution.sql -90077a690961e6ebf022266d39e55645aab318e37e21851abcad0aa3d80a1034 MaintenanceSolutionAzureSQLDatabase.sql +5b29df5d588e7cfdf59101650f72edd12e47c386d387d52c49ca4ac8aa997824 DatabaseBackup.sql +b9cf781cdbd6814b25416761be531e28a133e2a4e31935c5bfb35d81527ca693 DatabaseIntegrityCheck.sql +bcce7d06bc54d09d325335f8f5f6ff33e532104d7e167510890b57b63d04fbe2 IndexOptimize.sql +0ea98580b3c3e667120be1afe8232c203401dd3747da909e99b6dc2495970d0d MaintenanceSolution.sql +3ac39d23e6d262ad8b711f51114a98e94ba7fb01bf139a9338f414ed0d933634 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From b0e1b4f0847ba49178db925cc9beeb8871ffa439 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 9 Aug 2026 00:40:55 +0200 Subject: [PATCH 159/177] Add files via upload --- CommandExecute.sql | 4 ++-- DatabaseBackup.sql | 4 ++-- DatabaseIntegrityCheck.sql | 4 ++-- IndexOptimize.sql | 4 ++-- MaintenanceSolution.sql | 18 +++++++++--------- MaintenanceSolutionAzureSQLDatabase.sql | 14 +++++++------- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 30 insertions(+), 30 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 6e0f5ed0..754ecd5b 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-08 23:29:24 //-- + --// Version: 2026-08-09 00:40:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -52,7 +52,7 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, Severity int NOT NULL, - [State] int) + [State] int NOT NULL) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index ff65d688..42f6796b 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 23:29:24 //-- + --// Version: 2026-08-09 00:40:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -207,7 +207,7 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, Severity int NOT NULL, - [State] int) + [State] int NOT NULL) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 58ca7bd8..286dffe6 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 23:29:24 //-- + --// Version: 2026-08-09 00:40:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -122,7 +122,7 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, Severity int NOT NULL, - [State] int) + [State] int NOT NULL) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 54b01be2..61eb17bb 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 23:29:24 //-- + --// Version: 2026-08-09 00:40:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -130,7 +130,7 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, Severity int NOT NULL, - [State] int) + [State] int NOT NULL) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index b5498240..109ae7c2 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: 2026-08-08 23:29:24 +Version: 2026-08-09 00:40:19 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 23:29:24 //-- + --// Version: 2026-08-09 00:40:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -147,7 +147,7 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, Severity int NOT NULL, - [State] int) + [State] int NOT NULL) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 23:29:24 //-- + --// Version: 2026-08-09 00:40:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -606,7 +606,7 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, Severity int NOT NULL, - [State] int) + [State] int NOT NULL) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int @@ -5019,7 +5019,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 23:29:24 //-- + --// Version: 2026-08-09 00:40:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5101,7 +5101,7 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, Severity int NOT NULL, - [State] int) + [State] int NOT NULL) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int @@ -7059,7 +7059,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 23:29:24 //-- + --// Version: 2026-08-09 00:40:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7133,7 +7133,7 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, Severity int NOT NULL, - [State] int) + [State] int NOT NULL) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 41282bbb..b3171bd2 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-08 23:29:24 +Version: 2026-08-09 00:40:19 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 23:29:24 //-- + --// Version: 2026-08-09 00:40:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -102,7 +102,7 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, Severity int NOT NULL, - [State] int) + [State] int NOT NULL) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 23:29:24 //-- + --// Version: 2026-08-09 00:40:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -476,7 +476,7 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, Severity int NOT NULL, - [State] int) + [State] int NOT NULL) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int @@ -2434,7 +2434,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-08 23:29:24 //-- + --// Version: 2026-08-09 00:40:19 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2508,7 +2508,7 @@ BEGIN DECLARE @Errors TABLE (ID int IDENTITY PRIMARY KEY, [Message] nvarchar(max) NOT NULL, Severity int NOT NULL, - [State] int) + [State] int NOT NULL) DECLARE @CurrentMessage nvarchar(max) DECLARE @CurrentSeverity int diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 51740a9c..d69f4841 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -7ef31cdc5df8c168ccafac0115ffa1692d218153b3769c06bac8dbcd369cde65 CommandExecute.sql +44050ae13a43fe8da503c5a152939c88ac2b65f874f8a14668acf5459b7013bd CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -5b29df5d588e7cfdf59101650f72edd12e47c386d387d52c49ca4ac8aa997824 DatabaseBackup.sql -b9cf781cdbd6814b25416761be531e28a133e2a4e31935c5bfb35d81527ca693 DatabaseIntegrityCheck.sql -bcce7d06bc54d09d325335f8f5f6ff33e532104d7e167510890b57b63d04fbe2 IndexOptimize.sql -0ea98580b3c3e667120be1afe8232c203401dd3747da909e99b6dc2495970d0d MaintenanceSolution.sql -3ac39d23e6d262ad8b711f51114a98e94ba7fb01bf139a9338f414ed0d933634 MaintenanceSolutionAzureSQLDatabase.sql +3ec576ced0959f9f7219a1b40952e752083554322f851927402f3836674e7de4 DatabaseBackup.sql +36bc922c348a83adb37e84b06b0fc594698f907ad78988ace90a2e0baf070ddb DatabaseIntegrityCheck.sql +3bfa0c05dcf20d06987aa7c981be20c0d7f12d4249f8f5c00dfbfda0471008a7 IndexOptimize.sql +3866d75dce325ae23b07540c54e74118e8a97acb8db0683358e5511ea1b8ba16 MaintenanceSolution.sql +fd2f09f47aee95a3af0ad2cbc20f1c14024cc27bac07f243b828358b8ba6be5f MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 90ff817f131c29ac49d80914fd7dca5d46760778 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 9 Aug 2026 13:24:59 +0200 Subject: [PATCH 160/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 52 ++++++++++++++----- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 10 ++-- MaintenanceSolution.sql | 68 +++++++++++++++++-------- MaintenanceSolutionAzureSQLDatabase.sql | 16 +++--- SHA256SUMS.txt | 12 ++--- 7 files changed, 105 insertions(+), 57 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 754ecd5b..a5b74ecc 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-09 00:40:19 //-- + --// Version: 2026-08-09 13:21:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 42f6796b..709adcfd 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 00:40:19 //-- + --// Version: 2026-08-09 13:21:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1527,40 +1527,52 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @MaxTransferSize < 65536 OR @MaxTransferSize > 20971520 + IF @BackupSoftware IS NULL AND @URL IS NULL AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 4194304) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 20971520. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 4194304 when performing SQL Server native backups to disk. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP' + IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND @Version >= 16 AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 20971520) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported. The maximum value with Redgate SQL Backup Pro is 1048576. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 20971520 when backing up to URL with block blobs on this version of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE' + IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND @Version < 16 AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 4194304) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @MaxTransferSize is not supported with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 4194304 when backing up to URL with block blobs on this version of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL + IF @URL IS NOT NULL AND @Credential IS NOT NULL AND @MaxTransferSize IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('MAXTRANSFERSIZE is not supported when backing up to URL with page blobs. See https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url.', 16, 1) END - IF @MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + IF @BackupSoftware = 'SQLBACKUP' AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 1048576) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @MaxTransferSize is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 1048576 when backing up using Redgate SQL Backup Pro. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + END + + IF @BackupSoftware = 'LITESPEED' AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 4194304) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 4194304 when backing up using LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + END + + IF @BackupSoftware = 'SQLSAFE' AND @MaxTransferSize IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameter @MaxTransferSize is not supported with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @MaxTransferSize > 4194304 AND @URL IS NULL AND @BackupSoftware IS NULL + IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @MaxTransferSize IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported. The maximum value for SQL Server native backups to disk is 4194304. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + VALUES('The parameter @MaxTransferSize is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2379,10 +2391,10 @@ BEGIN VALUES('Setting @Init to ''Y'' is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#Init.', 16, 1) END - IF @Init = 'Y' AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') + IF @Init = 'Y' AND @URL IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Setting @Init to ''Y'' is not supported when backing up to S3-compatible storage. See https://ola.hallengren.com/sql-server-backup.html#Init.', 16, 1) + VALUES('Setting @Init to ''Y'' is not supported with backup to URL. See https://ola.hallengren.com/sql-server-backup.html#Init.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2479,6 +2491,12 @@ BEGIN VALUES('The parameter @ExpireDate is only supported with SQL Server native backups and LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#ExpireDate.', 16, 1) END + IF @ExpireDate IS NOT NULL AND @URL IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameter @ExpireDate is not supported with backup to URL. See https://ola.hallengren.com/sql-server-backup.html#ExpireDate.', 16, 1) + END + ---------------------------------------------------------------------------------------------------- IF @RetainDays < 0 @@ -2493,6 +2511,12 @@ BEGIN VALUES('The parameter @RetainDays is only supported with SQL Server native backups and LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#RetainDays.', 16, 1) END + IF @RetainDays IS NOT NULL AND @URL IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameter @RetainDays is not supported with backup to URL. See https://ola.hallengren.com/sql-server-backup.html#RetainDays.', 16, 1) + END + ---------------------------------------------------------------------------------------------------- IF @AllowNonCopyOnlyBackupsOnForwarder NOT IN('Y','N') OR @AllowNonCopyOnlyBackupsOnForwarder IS NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 286dffe6..74a439cb 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 00:40:19 //-- + --// Version: 2026-08-09 13:21:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 61eb17bb..53b3eb04 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 00:40:19 //-- + --// Version: 2026-08-09 13:21:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2304,6 +2304,8 @@ BEGIN IF @CurrentAlterIndexCompleted = 0 AND @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) AND @CurrentOnReadOnlyFileGroup = 0 BEGIN + SET @CurrentMaxDOP = @MaxDOP + -- Does the index exist? SET @CurrentCommand = '' @@ -2460,8 +2462,6 @@ BEGIN SET @CurrentAction = 'INDEX_REBUILD_ONLINE' END - SET @CurrentMaxDOP = @MaxDOP - -- Workaround for limitation in SQL Server, http://support.microsoft.com/kb/2292737 IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentIndexType IN (1, 2) AND @CurrentAllowPageLocks = 0 BEGIN @@ -2605,14 +2605,14 @@ BEGIN END END - SET @CurrentMaxDOP = @MaxDOP - -- Should the statistics be updated? IF @CurrentUpdateStatisticsCompleted = 0 AND @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentIsLastPartition = 1 OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) BEGIN + SET @CurrentMaxDOP = @MaxDOP + -- Does the statistics exist? SET @CurrentCommand = '' diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 109ae7c2..9a92178e 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: 2026-08-09 00:40:19 +Version: 2026-08-09 13:21:51 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 00:40:19 //-- + --// Version: 2026-08-09 13:21:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 00:40:19 //-- + --// Version: 2026-08-09 13:21:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1926,40 +1926,52 @@ BEGIN ---------------------------------------------------------------------------------------------------- - IF @MaxTransferSize < 65536 OR @MaxTransferSize > 20971520 + IF @BackupSoftware IS NULL AND @URL IS NULL AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 4194304) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 20971520. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 4194304 when performing SQL Server native backups to disk. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @MaxTransferSize > 1048576 AND @BackupSoftware = 'SQLBACKUP' + IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND @Version >= 16 AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 20971520) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported. The maximum value with Redgate SQL Backup Pro is 1048576. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 20971520 when backing up to URL with block blobs on this version of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @MaxTransferSize IS NOT NULL AND @BackupSoftware = 'SQLSAFE' + IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND @Version < 16 AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 4194304) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @MaxTransferSize is not supported with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 4194304 when backing up to URL with block blobs on this version of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @MaxTransferSize IS NOT NULL AND @URL IS NOT NULL AND @Credential IS NOT NULL + IF @URL IS NOT NULL AND @Credential IS NOT NULL AND @MaxTransferSize IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('MAXTRANSFERSIZE is not supported when backing up to URL with page blobs. See https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url.', 16, 1) END - IF @MaxTransferSize IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' + IF @BackupSoftware = 'SQLBACKUP' AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 1048576) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @MaxTransferSize is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 1048576 when backing up using Redgate SQL Backup Pro. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + END + + IF @BackupSoftware = 'LITESPEED' AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 4194304) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 4194304 when backing up using LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + END + + IF @BackupSoftware = 'SQLSAFE' AND @MaxTransferSize IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameter @MaxTransferSize is not supported with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @MaxTransferSize > 4194304 AND @URL IS NULL AND @BackupSoftware IS NULL + IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @MaxTransferSize IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MaxTransferSize is not supported. The maximum value for SQL Server native backups to disk is 4194304. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + VALUES('The parameter @MaxTransferSize is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2778,10 +2790,10 @@ BEGIN VALUES('Setting @Init to ''Y'' is not supported with Data Domain Boost. See https://ola.hallengren.com/sql-server-backup.html#Init.', 16, 1) END - IF @Init = 'Y' AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') + IF @Init = 'Y' AND @URL IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Setting @Init to ''Y'' is not supported when backing up to S3-compatible storage. See https://ola.hallengren.com/sql-server-backup.html#Init.', 16, 1) + VALUES('Setting @Init to ''Y'' is not supported with backup to URL. See https://ola.hallengren.com/sql-server-backup.html#Init.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2878,6 +2890,12 @@ BEGIN VALUES('The parameter @ExpireDate is only supported with SQL Server native backups and LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#ExpireDate.', 16, 1) END + IF @ExpireDate IS NOT NULL AND @URL IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameter @ExpireDate is not supported with backup to URL. See https://ola.hallengren.com/sql-server-backup.html#ExpireDate.', 16, 1) + END + ---------------------------------------------------------------------------------------------------- IF @RetainDays < 0 @@ -2892,6 +2910,12 @@ BEGIN VALUES('The parameter @RetainDays is only supported with SQL Server native backups and LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#RetainDays.', 16, 1) END + IF @RetainDays IS NOT NULL AND @URL IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameter @RetainDays is not supported with backup to URL. See https://ola.hallengren.com/sql-server-backup.html#RetainDays.', 16, 1) + END + ---------------------------------------------------------------------------------------------------- IF @AllowNonCopyOnlyBackupsOnForwarder NOT IN('Y','N') OR @AllowNonCopyOnlyBackupsOnForwarder IS NULL @@ -5019,7 +5043,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 00:40:19 //-- + --// Version: 2026-08-09 13:21:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7059,7 +7083,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 00:40:19 //-- + --// Version: 2026-08-09 13:21:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -9307,6 +9331,8 @@ BEGIN IF @CurrentAlterIndexCompleted = 0 AND @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) AND @CurrentOnReadOnlyFileGroup = 0 BEGIN + SET @CurrentMaxDOP = @MaxDOP + -- Does the index exist? SET @CurrentCommand = '' @@ -9463,8 +9489,6 @@ BEGIN SET @CurrentAction = 'INDEX_REBUILD_ONLINE' END - SET @CurrentMaxDOP = @MaxDOP - -- Workaround for limitation in SQL Server, http://support.microsoft.com/kb/2292737 IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentIndexType IN (1, 2) AND @CurrentAllowPageLocks = 0 BEGIN @@ -9608,14 +9632,14 @@ BEGIN END END - SET @CurrentMaxDOP = @MaxDOP - -- Should the statistics be updated? IF @CurrentUpdateStatisticsCompleted = 0 AND @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentIsLastPartition = 1 OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) BEGIN + SET @CurrentMaxDOP = @MaxDOP + -- Does the statistics exist? SET @CurrentCommand = '' diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index b3171bd2..5485804a 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-09 00:40:19 +Version: 2026-08-09 13:21:51 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 00:40:19 //-- + --// Version: 2026-08-09 13:21:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 00:40:19 //-- + --// Version: 2026-08-09 13:21:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2434,7 +2434,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 00:40:19 //-- + --// Version: 2026-08-09 13:21:51 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4682,6 +4682,8 @@ BEGIN IF @CurrentAlterIndexCompleted = 0 AND @CurrentIndexID IS NOT NULL AND EXISTS(SELECT * FROM @ActionsPreferred) AND @CurrentOnReadOnlyFileGroup = 0 BEGIN + SET @CurrentMaxDOP = @MaxDOP + -- Does the index exist? SET @CurrentCommand = '' @@ -4838,8 +4840,6 @@ BEGIN SET @CurrentAction = 'INDEX_REBUILD_ONLINE' END - SET @CurrentMaxDOP = @MaxDOP - -- Workaround for limitation in SQL Server, http://support.microsoft.com/kb/2292737 IF @CurrentAction = 'INDEX_REBUILD_ONLINE' AND @CurrentIndexType IN (1, 2) AND @CurrentAllowPageLocks = 0 BEGIN @@ -4983,14 +4983,14 @@ BEGIN END END - SET @CurrentMaxDOP = @MaxDOP - -- Should the statistics be updated? IF @CurrentUpdateStatisticsCompleted = 0 AND @CurrentStatisticsID IS NOT NULL AND ((@UpdateStatistics = 'ALL' AND (@CurrentIndexType IN (1,2,7) OR @CurrentIndexID IS NULL)) OR (@UpdateStatistics = 'INDEX' AND @CurrentIndexID IS NOT NULL AND @CurrentIndexType IN (1,2,7)) OR (@UpdateStatistics = 'COLUMNS' AND @CurrentIndexID IS NULL)) AND ((@CurrentIsPartition = 0 AND (@CurrentAction NOT IN('INDEX_REBUILD_ONLINE','INDEX_REBUILD_OFFLINE') OR @CurrentAction IS NULL)) OR (@CurrentIsPartition = 1 AND (@CurrentIsLastPartition = 1 OR (@PartitionLevel = 'Y' AND @CurrentIsIncremental = 1)))) BEGIN + SET @CurrentMaxDOP = @MaxDOP + -- Does the statistics exist? SET @CurrentCommand = '' diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index d69f4841..26f8552b 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -44050ae13a43fe8da503c5a152939c88ac2b65f874f8a14668acf5459b7013bd CommandExecute.sql +33392817d47d3ff50914eda71a82f6530e662ac9f9c3326843fb1d08c251de25 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -3ec576ced0959f9f7219a1b40952e752083554322f851927402f3836674e7de4 DatabaseBackup.sql -36bc922c348a83adb37e84b06b0fc594698f907ad78988ace90a2e0baf070ddb DatabaseIntegrityCheck.sql -3bfa0c05dcf20d06987aa7c981be20c0d7f12d4249f8f5c00dfbfda0471008a7 IndexOptimize.sql -3866d75dce325ae23b07540c54e74118e8a97acb8db0683358e5511ea1b8ba16 MaintenanceSolution.sql -fd2f09f47aee95a3af0ad2cbc20f1c14024cc27bac07f243b828358b8ba6be5f MaintenanceSolutionAzureSQLDatabase.sql +a8f36db588a41422aa00f0b35f6ab1c09be247d980bd73299f79984f859db78b DatabaseBackup.sql +6875bcc79053e2052bc41c9b60d7cb22e165e7f0094326b9710b56ac20e3076f DatabaseIntegrityCheck.sql +17b8455addc696e81e41d21e25c3708777bb6b148bd5bc6e53495c92c37ca24c IndexOptimize.sql +bd393ba04944e3a56854d166c0ca4f58b7d45d8b291478f43cf0b5f6eefb4df5 MaintenanceSolution.sql +86bc3f6e835d1ecddad1cba006c6f20976a8818fae14a37598184fd14496faaa MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 5302150494cb591c0c93b3dd388447c683da7713 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 9 Aug 2026 13:35:53 +0200 Subject: [PATCH 161/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 6 +++--- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 14 +++++++------- MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 23 insertions(+), 23 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index a5b74ecc..b6ca8e52 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-09 13:21:51 //-- + --// Version: 2026-08-09 13:35:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 709adcfd..77f2f5a6 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:21:51 //-- + --// Version: 2026-08-09 13:35:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1533,13 +1533,13 @@ BEGIN VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 4194304 when performing SQL Server native backups to disk. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND @Version >= 16 AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 20971520) + IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 20971520) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 20971520 when backing up to URL with block blobs on this version of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND @Version < 16 AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 4194304) + IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND NOT (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 4194304) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 4194304 when backing up to URL with block blobs on this version of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 74a439cb..3f30a02c 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:21:51 //-- + --// Version: 2026-08-09 13:35:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 53b3eb04..fd134af6 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:21:51 //-- + --// Version: 2026-08-09 13:35:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 9a92178e..de23dda7 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: 2026-08-09 13:21:51 +Version: 2026-08-09 13:35:14 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:21:51 //-- + --// Version: 2026-08-09 13:35:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:21:51 //-- + --// Version: 2026-08-09 13:35:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1932,13 +1932,13 @@ BEGIN VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 4194304 when performing SQL Server native backups to disk. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND @Version >= 16 AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 20971520) + IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 20971520) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 20971520 when backing up to URL with block blobs on this version of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND @Version < 16 AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 4194304) + IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND NOT (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 4194304) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 4194304 when backing up to URL with block blobs on this version of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) @@ -5043,7 +5043,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:21:51 //-- + --// Version: 2026-08-09 13:35:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7083,7 +7083,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:21:51 //-- + --// Version: 2026-08-09 13:35:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 5485804a..c3ec9e51 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-09 13:21:51 +Version: 2026-08-09 13:35:14 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:21:51 //-- + --// Version: 2026-08-09 13:35:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:21:51 //-- + --// Version: 2026-08-09 13:35:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2434,7 +2434,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:21:51 //-- + --// Version: 2026-08-09 13:35:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 26f8552b..c6148e6d 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -33392817d47d3ff50914eda71a82f6530e662ac9f9c3326843fb1d08c251de25 CommandExecute.sql +fa984d665a8bf60557ac7ef7551ed649a82d0b367d18b8fc10f03588ad57be94 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -a8f36db588a41422aa00f0b35f6ab1c09be247d980bd73299f79984f859db78b DatabaseBackup.sql -6875bcc79053e2052bc41c9b60d7cb22e165e7f0094326b9710b56ac20e3076f DatabaseIntegrityCheck.sql -17b8455addc696e81e41d21e25c3708777bb6b148bd5bc6e53495c92c37ca24c IndexOptimize.sql -bd393ba04944e3a56854d166c0ca4f58b7d45d8b291478f43cf0b5f6eefb4df5 MaintenanceSolution.sql -86bc3f6e835d1ecddad1cba006c6f20976a8818fae14a37598184fd14496faaa MaintenanceSolutionAzureSQLDatabase.sql +df284610136865003c4e73228b408a09c1ee26484bdcfed77c7f1f7be0e88ccd DatabaseBackup.sql +f6c5efb3c74bcc5378f1d462a91be9d3f2cad0a6d3a70c5c0584901ea24b6090 DatabaseIntegrityCheck.sql +fab91648498e2f3027297c4fedaf8a211360467114be16fde55e5e0362d81229 IndexOptimize.sql +2d7cada7bb9c27b7e96cf42e2924e43a9ab50119b65181cfe538839236fe8f14 MaintenanceSolution.sql +4a14501bfd1c243fa49ae4f2f2d80f375e2cac7511af0ea31a1c263e26ea3165 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From ab3e6eeb66c8941031804a1d62ac62a39d918c53 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 9 Aug 2026 16:59:39 +0200 Subject: [PATCH 162/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 131 ++++++++++++++++++++-- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 139 +++++++++++++++++++++--- MaintenanceSolutionAzureSQLDatabase.sql | 8 +- SHA256SUMS.txt | 12 +- 7 files changed, 255 insertions(+), 41 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index b6ca8e52..b500687d 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-09 13:35:14 //-- + --// Version: 2026-08-09 16:58:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 77f2f5a6..3871540b 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:35:14 //-- + --// Version: 2026-08-09 16:58:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -953,6 +953,30 @@ BEGIN VALUES('Backup to NUL is only supported with SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) END + IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) > 64 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @Directory is not supported. The maximum number of directories is 64. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) + END + + IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) > 32 AND @BackupSoftware = 'SQLBACKUP' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @Directory is not supported. The maximum number of directories with Redgate SQL Backup Pro is 32. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) + END + + IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) > 32 AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND @BackupSoftware IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @Directory is not supported. The maximum number of directories when performing mirrored SQL Server native backups is 32. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) + END + + IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) > 32 AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND @BackupSoftware = 'LITESPEED' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @Directory is not supported. The maximum number of directories when performing mirrored backups with LiteSpeed for SQL Server is 32. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 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 IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) @@ -961,10 +985,16 @@ BEGIN VALUES('The value for the parameter @MirrorDirectory is not supported. Specify a local path (e.g. D:\Backup), a UNC path (e.g. \\Server\Share), or a path starting with / on Linux, without leading or trailing spaces. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END - IF @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1 + IF @BackupSoftware = 'SQLBACKUP' AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MirrorDirectory is not supported. Redgate SQL Backup Pro supports only one mirror directory. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) + END + + IF @BackupSoftware = 'SQLSAFE' AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorDirectory is not supported. Redgate SQL Backup Pro and Idera SQL Safe Backup support only one mirror directory. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) + VALUES('The value for the parameter @MirrorDirectory is not supported. Idera SQL Safe Backup supports only one mirror directory. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END IF @MirrorDirectory IS NOT NULL AND @EngineEdition = 8 @@ -1121,6 +1151,24 @@ BEGIN VALUES('Striped backups across S3-compatible storage and Azure Blob Storage are not supported. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) END + IF (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) > 64 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @URL is not supported. The maximum number of URLs is 64. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) + END + + IF (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) > 32 AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @URL is not supported. The maximum number of URLs when performing mirrored backups is 32. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) + END + + IF @URL IS NOT NULL AND @Credential IS NOT NULL AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) > 1 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @URL is not supported. Backup striping to URL with page blobs is not supported. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) + END + ---------------------------------------------------------------------------------------------------- IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND NOT (DirectoryPath LIKE 'https://%/%' OR DirectoryPath LIKE 's3://%/%')) @@ -1335,10 +1383,22 @@ BEGIN VALUES('Backup compression is not supported in this edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) END - IF @Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevelNumeric IS NULL OR @CompressionLevelNumeric >= 1) + IF @Compress = 'N' AND @BackupSoftware = 'LITESPEED' AND (@CompressionLevelNumeric IS NULL OR @CompressionLevelNumeric >= 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('Setting @Compress to ''N'' with LiteSpeed for SQL Server requires @CompressionLevelNumeric = 0. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) + END + + IF @Compress = 'N' AND @BackupSoftware = 'SQLBACKUP' AND (@CompressionLevelNumeric IS NULL OR @CompressionLevelNumeric >= 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Setting @Compress to ''N'' with LiteSpeed for SQL Server, Redgate SQL Backup Pro or Idera SQL Safe Backup requires @CompressionLevelNumeric = 0. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) + VALUES('Setting @Compress to ''N'' with Redgate SQL Backup Pro requires @CompressionLevelNumeric = 0. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) + END + + IF @Compress = 'N' AND @BackupSoftware = 'SQLSAFE' AND (@CompressionLevelNumeric IS NULL OR @CompressionLevelNumeric >= 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('Setting @Compress to ''N'' with Idera SQL Safe Backup requires @CompressionLevelNumeric = 0. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) END IF @Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevelNumeric = 0 @@ -1607,10 +1667,16 @@ BEGIN VALUES('Backup striping to URL with page blobs is not supported. See https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url.', 16, 1) END - IF @NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) + IF @NumberOfFiles > 1 AND @BackupSoftware = 'SQLBACKUP' AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported. Mirrored backups with multiple files are not supported with Redgate SQL Backup Pro and Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) + VALUES('The value for the parameter @NumberOfFiles is not supported. Mirrored backups with multiple files are not supported with Redgate SQL Backup Pro. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) + END + + IF @NumberOfFiles > 1 AND @BackupSoftware = 'SQLSAFE' AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @NumberOfFiles is not supported. Mirrored backups with multiple files are not supported with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST' @@ -1631,10 +1697,22 @@ BEGIN VALUES('The value for the parameter @NumberOfFiles is not supported. The number of files has to be evenly divisible by the number of URLs. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END - IF @NumberOfFiles > 32 AND @URL LIKE 's3%' AND @MirrorURL LIKE 's3%' + IF @BackupSoftware IS NULL AND @NumberOfFiles > 32 AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored SQL Server native backups to disk is 32. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) + END + + IF @NumberOfFiles > 32 AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored backups to URL is 32. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) + END + + IF @BackupSoftware = 'LITESPEED' AND @NumberOfFiles > 32 AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored backups to S3 storage is 32. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) + VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored backups with LiteSpeed for SQL Server is 32. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -1883,10 +1961,22 @@ BEGIN VALUES('The parameter @EncryptionKey can only be used together with @Encrypt = ''Y''. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) END - IF @EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE') + IF @EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware = 'LITESPEED' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('You need to specify @EncryptionKey when performing encrypted backups with LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) + END + + IF @EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware = 'SQLBACKUP' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('You need to specify @EncryptionKey when performing encrypted backups with Redgate SQL Backup Pro. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) + END + + IF @EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware = 'SQLSAFE' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You need to specify @EncryptionKey when performing encrypted backups with LiteSpeed for SQL Server, Redgate SQL Backup Pro or Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) + VALUES('You need to specify @EncryptionKey when performing encrypted backups with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) END IF @EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' @@ -2025,6 +2115,18 @@ BEGIN VALUES('The parameter @MirrorURL can only be used together with @URL. See https://ola.hallengren.com/sql-server-backup.html#MirrorURL.', 16, 1) END + IF @MirrorURL IS NOT NULL AND @Credential IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MirrorURL is not supported. Mirrored backup to URL with page blobs is not supported. See https://ola.hallengren.com/sql-server-backup.html#MirrorURL.', 16, 1) + END + + IF @MirrorURL IS NOT NULL AND @BackupSoftware IS NULL AND @EngineEdition NOT IN (3, 8) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MirrorURL is not supported. Mirrored backup to URL is not supported in this edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MirrorURL.', 16, 1) + END + ---------------------------------------------------------------------------------------------------- IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL @@ -3098,7 +3200,12 @@ BEGIN 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, + MaxNumberOfFiles = CASE WHEN @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) THEN 1 + WHEN @BackupSoftware = 'LITESPEED' AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) THEN 32 + WHEN @BackupSoftware IN('SQLBACKUP','DATA_DOMAIN_BOOST') THEN 32 + WHEN @BackupSoftware IS NULL AND (EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) OR EXISTS(SELECT * FROM @URLs WHERE Mirror = 1)) 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 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 3f30a02c..6b39fe4c 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:35:14 //-- + --// Version: 2026-08-09 16:58:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index fd134af6..4580fca6 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:35:14 //-- + --// Version: 2026-08-09 16:58:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index de23dda7..ee268b6f 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: 2026-08-09 13:35:14 +Version: 2026-08-09 16:58:36 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:35:14 //-- + --// Version: 2026-08-09 16:58:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:35:14 //-- + --// Version: 2026-08-09 16:58:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1352,6 +1352,30 @@ BEGIN VALUES('Backup to NUL is only supported with SQL Server native backups. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) END + IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) > 64 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @Directory is not supported. The maximum number of directories is 64. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) + END + + IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) > 32 AND @BackupSoftware = 'SQLBACKUP' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @Directory is not supported. The maximum number of directories with Redgate SQL Backup Pro is 32. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) + END + + IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) > 32 AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND @BackupSoftware IS NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @Directory is not supported. The maximum number of directories when performing mirrored SQL Server native backups is 32. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 16, 1) + END + + IF (SELECT COUNT(*) FROM @Directories WHERE Mirror = 0) > 32 AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) AND @BackupSoftware = 'LITESPEED' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @Directory is not supported. The maximum number of directories when performing mirrored backups with LiteSpeed for SQL Server is 32. See https://ola.hallengren.com/sql-server-backup.html#Directory.', 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 IS NULL OR LEFT(DirectoryPath,1) = ' ' OR RIGHT(DirectoryPath,1) = ' ')) @@ -1360,10 +1384,16 @@ BEGIN VALUES('The value for the parameter @MirrorDirectory is not supported. Specify a local path (e.g. D:\Backup), a UNC path (e.g. \\Server\Share), or a path starting with / on Linux, without leading or trailing spaces. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END - IF @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1 + IF @BackupSoftware = 'SQLBACKUP' AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MirrorDirectory is not supported. Redgate SQL Backup Pro supports only one mirror directory. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) + END + + IF @BackupSoftware = 'SQLSAFE' AND (SELECT COUNT(*) FROM @Directories WHERE Mirror = 1) > 1 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorDirectory is not supported. Redgate SQL Backup Pro and Idera SQL Safe Backup support only one mirror directory. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) + VALUES('The value for the parameter @MirrorDirectory is not supported. Idera SQL Safe Backup supports only one mirror directory. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END IF @MirrorDirectory IS NOT NULL AND @EngineEdition = 8 @@ -1520,6 +1550,24 @@ BEGIN VALUES('Striped backups across S3-compatible storage and Azure Blob Storage are not supported. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) END + IF (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) > 64 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @URL is not supported. The maximum number of URLs is 64. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) + END + + IF (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) > 32 AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @URL is not supported. The maximum number of URLs when performing mirrored backups is 32. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) + END + + IF @URL IS NOT NULL AND @Credential IS NOT NULL AND (SELECT COUNT(*) FROM @URLs WHERE Mirror = 0) > 1 + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @URL is not supported. Backup striping to URL with page blobs is not supported. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) + END + ---------------------------------------------------------------------------------------------------- IF EXISTS(SELECT * FROM @URLs WHERE Mirror = 1 AND NOT (DirectoryPath LIKE 'https://%/%' OR DirectoryPath LIKE 's3://%/%')) @@ -1734,10 +1782,22 @@ BEGIN VALUES('Backup compression is not supported in this edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) END - IF @Compress = 'N' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND (@CompressionLevelNumeric IS NULL OR @CompressionLevelNumeric >= 1) + IF @Compress = 'N' AND @BackupSoftware = 'LITESPEED' AND (@CompressionLevelNumeric IS NULL OR @CompressionLevelNumeric >= 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('Setting @Compress to ''N'' with LiteSpeed for SQL Server requires @CompressionLevelNumeric = 0. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) + END + + IF @Compress = 'N' AND @BackupSoftware = 'SQLBACKUP' AND (@CompressionLevelNumeric IS NULL OR @CompressionLevelNumeric >= 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('Setting @Compress to ''N'' with LiteSpeed for SQL Server, Redgate SQL Backup Pro or Idera SQL Safe Backup requires @CompressionLevelNumeric = 0. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) + VALUES('Setting @Compress to ''N'' with Redgate SQL Backup Pro requires @CompressionLevelNumeric = 0. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) + END + + IF @Compress = 'N' AND @BackupSoftware = 'SQLSAFE' AND (@CompressionLevelNumeric IS NULL OR @CompressionLevelNumeric >= 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('Setting @Compress to ''N'' with Idera SQL Safe Backup requires @CompressionLevelNumeric = 0. See https://ola.hallengren.com/sql-server-backup.html#Compress.', 16, 1) END IF @Compress = 'Y' AND @BackupSoftware IN ('LITESPEED','SQLBACKUP','SQLSAFE') AND @CompressionLevelNumeric = 0 @@ -2006,10 +2066,16 @@ BEGIN VALUES('Backup striping to URL with page blobs is not supported. See https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/sql-server-backup-to-url.', 16, 1) END - IF @NumberOfFiles > 1 AND @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) + IF @NumberOfFiles > 1 AND @BackupSoftware = 'SQLBACKUP' AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported. Mirrored backups with multiple files are not supported with Redgate SQL Backup Pro and Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) + VALUES('The value for the parameter @NumberOfFiles is not supported. Mirrored backups with multiple files are not supported with Redgate SQL Backup Pro. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) + END + + IF @NumberOfFiles > 1 AND @BackupSoftware = 'SQLSAFE' AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @NumberOfFiles is not supported. Mirrored backups with multiple files are not supported with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END IF @NumberOfFiles > 32 AND @BackupSoftware = 'DATA_DOMAIN_BOOST' @@ -2030,10 +2096,22 @@ BEGIN VALUES('The value for the parameter @NumberOfFiles is not supported. The number of files has to be evenly divisible by the number of URLs. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END - IF @NumberOfFiles > 32 AND @URL LIKE 's3%' AND @MirrorURL LIKE 's3%' + IF @BackupSoftware IS NULL AND @NumberOfFiles > 32 AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored SQL Server native backups to disk is 32. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) + END + + IF @NumberOfFiles > 32 AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 1) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored backups to URL is 32. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) + END + + IF @BackupSoftware = 'LITESPEED' AND @NumberOfFiles > 32 AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored backups to S3 storage is 32. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) + VALUES('The value for the parameter @NumberOfFiles is not supported. The maximum number of files when performing mirrored backups with LiteSpeed for SQL Server is 32. See https://ola.hallengren.com/sql-server-backup.html#NumberOfFiles.', 16, 1) END ---------------------------------------------------------------------------------------------------- @@ -2282,10 +2360,22 @@ BEGIN VALUES('The parameter @EncryptionKey can only be used together with @Encrypt = ''Y''. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) END - IF @EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware IN('LITESPEED','SQLBACKUP','SQLSAFE') + IF @EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware = 'LITESPEED' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('You need to specify @EncryptionKey when performing encrypted backups with LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) + END + + IF @EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware = 'SQLBACKUP' + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('You need to specify @EncryptionKey when performing encrypted backups with Redgate SQL Backup Pro. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) + END + + IF @EncryptionKey IS NULL AND @Encrypt = 'Y' AND @BackupSoftware = 'SQLSAFE' BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('You need to specify @EncryptionKey when performing encrypted backups with LiteSpeed for SQL Server, Redgate SQL Backup Pro or Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) + VALUES('You need to specify @EncryptionKey when performing encrypted backups with Idera SQL Safe Backup. See https://ola.hallengren.com/sql-server-backup.html#EncryptionKey.', 16, 1) END IF @EncryptionKey IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' @@ -2424,6 +2514,18 @@ BEGIN VALUES('The parameter @MirrorURL can only be used together with @URL. See https://ola.hallengren.com/sql-server-backup.html#MirrorURL.', 16, 1) END + IF @MirrorURL IS NOT NULL AND @Credential IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MirrorURL is not supported. Mirrored backup to URL with page blobs is not supported. See https://ola.hallengren.com/sql-server-backup.html#MirrorURL.', 16, 1) + END + + IF @MirrorURL IS NOT NULL AND @BackupSoftware IS NULL AND @EngineEdition NOT IN (3, 8) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MirrorURL is not supported. Mirrored backup to URL is not supported in this edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MirrorURL.', 16, 1) + END + ---------------------------------------------------------------------------------------------------- IF @Updateability NOT IN('READ_ONLY','READ_WRITE','ALL') OR @Updateability IS NULL @@ -3497,7 +3599,12 @@ BEGIN 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, + MaxNumberOfFiles = CASE WHEN @BackupSoftware IN('SQLBACKUP','SQLSAFE') AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) THEN 1 + WHEN @BackupSoftware = 'LITESPEED' AND EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) THEN 32 + WHEN @BackupSoftware IN('SQLBACKUP','DATA_DOMAIN_BOOST') THEN 32 + WHEN @BackupSoftware IS NULL AND (EXISTS(SELECT * FROM @Directories WHERE Mirror = 1) OR EXISTS(SELECT * FROM @URLs WHERE Mirror = 1)) 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 @@ -5043,7 +5150,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:35:14 //-- + --// Version: 2026-08-09 16:58:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7083,7 +7190,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:35:14 //-- + --// Version: 2026-08-09 16:58:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index c3ec9e51..f24a5336 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-09 13:35:14 +Version: 2026-08-09 16:58:36 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:35:14 //-- + --// Version: 2026-08-09 16:58:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:35:14 //-- + --// Version: 2026-08-09 16:58:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2434,7 +2434,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 13:35:14 //-- + --// Version: 2026-08-09 16:58:36 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index c6148e6d..7ee88d87 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -fa984d665a8bf60557ac7ef7551ed649a82d0b367d18b8fc10f03588ad57be94 CommandExecute.sql +e292739a3615b0f913bc1d4dbe70b43b9c59a607b19ae629dad1fb540e89266a CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -df284610136865003c4e73228b408a09c1ee26484bdcfed77c7f1f7be0e88ccd DatabaseBackup.sql -f6c5efb3c74bcc5378f1d462a91be9d3f2cad0a6d3a70c5c0584901ea24b6090 DatabaseIntegrityCheck.sql -fab91648498e2f3027297c4fedaf8a211360467114be16fde55e5e0362d81229 IndexOptimize.sql -2d7cada7bb9c27b7e96cf42e2924e43a9ab50119b65181cfe538839236fe8f14 MaintenanceSolution.sql -4a14501bfd1c243fa49ae4f2f2d80f375e2cac7511af0ea31a1c263e26ea3165 MaintenanceSolutionAzureSQLDatabase.sql +71824343c1792139b1778ca718c0a0f4fc14a987044b6b76e12621883f202342 DatabaseBackup.sql +dbe5c5b5aa2d1523a01f0454dfcccac8c4d00dcbb95bac06439895f4bdb07206 DatabaseIntegrityCheck.sql +64bbbdd51cc74721c7e60055526beb0ee56d92362f8bb2d1904092cb01ba9ee7 IndexOptimize.sql +4dd683f880263b864b37b149f9abe1eede03778e48c47a7dbd2c5a7a7abdb111 MaintenanceSolution.sql +0dedcd5175a02805e6ada97fb6d3be4d1632459757a4bdc2d75882747034afa8 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From d56da6905d19558f779c608e541bbcbbf39f3d19 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 10 Aug 2026 19:54:29 +0200 Subject: [PATCH 163/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 24 +++++++------------ DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 32 ++++++++++--------------- MaintenanceSolutionAzureSQLDatabase.sql | 8 +++---- SHA256SUMS.txt | 12 +++++----- 7 files changed, 35 insertions(+), 47 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index b500687d..4856ebbd 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-09 16:58:36 //-- + --// Version: 2026-08-10 19:53:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 3871540b..06cae4ed 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 16:58:36 //-- + --// Version: 2026-08-10 19:53:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1593,18 +1593,24 @@ BEGIN VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 4194304 when performing SQL Server native backups to disk. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 20971520) + IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 20971520) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 20971520 when backing up to URL with block blobs on this version of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND NOT (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 4194304) + IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND NOT (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 4194304) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 4194304 when backing up to URL with block blobs on this version of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END + IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND (@MaxTransferSize < 5242880 OR @MaxTransferSize > 20971520) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 5242880 and 20971520 when backing up to S3-compatible storage. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + END + IF @URL IS NOT NULL AND @Credential IS NOT NULL AND @MaxTransferSize IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -2593,12 +2599,6 @@ BEGIN VALUES('The parameter @ExpireDate is only supported with SQL Server native backups and LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#ExpireDate.', 16, 1) END - IF @ExpireDate IS NOT NULL AND @URL IS NOT NULL - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @ExpireDate is not supported with backup to URL. See https://ola.hallengren.com/sql-server-backup.html#ExpireDate.', 16, 1) - END - ---------------------------------------------------------------------------------------------------- IF @RetainDays < 0 @@ -2613,12 +2613,6 @@ BEGIN VALUES('The parameter @RetainDays is only supported with SQL Server native backups and LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#RetainDays.', 16, 1) END - IF @RetainDays IS NOT NULL AND @URL IS NOT NULL - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @RetainDays is not supported with backup to URL. See https://ola.hallengren.com/sql-server-backup.html#RetainDays.', 16, 1) - END - ---------------------------------------------------------------------------------------------------- IF @AllowNonCopyOnlyBackupsOnForwarder NOT IN('Y','N') OR @AllowNonCopyOnlyBackupsOnForwarder IS NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 6b39fe4c..ddca9500 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 16:58:36 //-- + --// Version: 2026-08-10 19:53:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 4580fca6..3720f95e 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 16:58:36 //-- + --// Version: 2026-08-10 19:53:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index ee268b6f..c0070798 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: 2026-08-09 16:58:36 +Version: 2026-08-10 19:53:25 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 16:58:36 //-- + --// Version: 2026-08-10 19:53:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 16:58:36 //-- + --// Version: 2026-08-10 19:53:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1992,18 +1992,24 @@ BEGIN VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 4194304 when performing SQL Server native backups to disk. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 20971520) + IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 20971520) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 20971520 when backing up to URL with block blobs on this version of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END - IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND NOT (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 4194304) + IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND NOT EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND NOT (@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND (@MaxTransferSize < 65536 OR @MaxTransferSize > 4194304) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 65536 and 4194304 when backing up to URL with block blobs on this version of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) END + IF @BackupSoftware IS NULL AND @URL IS NOT NULL AND @Credential IS NULL AND EXISTS(SELECT * FROM @URLs WHERE Mirror = 0 AND DirectoryPath LIKE 's3://%/%') AND (@MaxTransferSize < 5242880 OR @MaxTransferSize > 20971520) + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The value for the parameter @MaxTransferSize is not supported. The value has to be between 5242880 and 20971520 when backing up to S3-compatible storage. See https://ola.hallengren.com/sql-server-backup.html#MaxTransferSize.', 16, 1) + END + IF @URL IS NOT NULL AND @Credential IS NOT NULL AND @MaxTransferSize IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) @@ -2992,12 +2998,6 @@ BEGIN VALUES('The parameter @ExpireDate is only supported with SQL Server native backups and LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#ExpireDate.', 16, 1) END - IF @ExpireDate IS NOT NULL AND @URL IS NOT NULL - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @ExpireDate is not supported with backup to URL. See https://ola.hallengren.com/sql-server-backup.html#ExpireDate.', 16, 1) - END - ---------------------------------------------------------------------------------------------------- IF @RetainDays < 0 @@ -3012,12 +3012,6 @@ BEGIN VALUES('The parameter @RetainDays is only supported with SQL Server native backups and LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#RetainDays.', 16, 1) END - IF @RetainDays IS NOT NULL AND @URL IS NOT NULL - BEGIN - INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The parameter @RetainDays is not supported with backup to URL. See https://ola.hallengren.com/sql-server-backup.html#RetainDays.', 16, 1) - END - ---------------------------------------------------------------------------------------------------- IF @AllowNonCopyOnlyBackupsOnForwarder NOT IN('Y','N') OR @AllowNonCopyOnlyBackupsOnForwarder IS NULL @@ -5150,7 +5144,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 16:58:36 //-- + --// Version: 2026-08-10 19:53:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7190,7 +7184,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 16:58:36 //-- + --// Version: 2026-08-10 19:53:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index f24a5336..ebd52391 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-09 16:58:36 +Version: 2026-08-10 19:53:25 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 16:58:36 //-- + --// Version: 2026-08-10 19:53:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 16:58:36 //-- + --// Version: 2026-08-10 19:53:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2434,7 +2434,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-09 16:58:36 //-- + --// Version: 2026-08-10 19:53:25 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 7ee88d87..4b9e5cdc 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -e292739a3615b0f913bc1d4dbe70b43b9c59a607b19ae629dad1fb540e89266a CommandExecute.sql +535d23c8dd835214c6b00ed2b21617bebdb9baa3a3156df0066e65b600f81336 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -71824343c1792139b1778ca718c0a0f4fc14a987044b6b76e12621883f202342 DatabaseBackup.sql -dbe5c5b5aa2d1523a01f0454dfcccac8c4d00dcbb95bac06439895f4bdb07206 DatabaseIntegrityCheck.sql -64bbbdd51cc74721c7e60055526beb0ee56d92362f8bb2d1904092cb01ba9ee7 IndexOptimize.sql -4dd683f880263b864b37b149f9abe1eede03778e48c47a7dbd2c5a7a7abdb111 MaintenanceSolution.sql -0dedcd5175a02805e6ada97fb6d3be4d1632459757a4bdc2d75882747034afa8 MaintenanceSolutionAzureSQLDatabase.sql +6f26f231eb7241176d28d0a2c3fafe86cc0f6a621a468a594af3b78f067ed7eb DatabaseBackup.sql +f49dacb8917178ae96535bb147058070e159d3c7437433e56c5f3c0bac60b5cf DatabaseIntegrityCheck.sql +6ff9a9bcbd48b46f30e1ca21cae757beb0701f4dcd0d7814f415aa8ba05c2d63 IndexOptimize.sql +3c26e861f68edd02bd7474a780c6b718a5a88691d3c9ccf48052859767ae7ca2 MaintenanceSolution.sql +20304977b63ebff05ecf2ce9f01a2d0c177625b13ce3a356c56b3387d4a57bb7 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From d4e0ed9c5f65594768605ad645332add6e593845 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 12 Aug 2026 20:44:29 +0200 Subject: [PATCH 164/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 9 ++++++- DatabaseIntegrityCheck.sql | 9 ++++++- IndexOptimize.sql | 11 +++++++-- MaintenanceSolution.sql | 33 ++++++++++++++++++++----- MaintenanceSolutionAzureSQLDatabase.sql | 24 ++++++++++++++---- SHA256SUMS.txt | 12 ++++----- 7 files changed, 78 insertions(+), 22 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 4856ebbd..bc55e1db 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-10 19:53:25 //-- + --// Version: 2026-08-12 20:43:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 06cae4ed..24e2a5cf 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-10 19:53:25 //-- + --// Version: 2026-08-12 20:43:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -126,6 +126,7 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupID uniqueidentifier DECLARE @ContainedAvailabilityGroupListenerConnection bit + DECLARE @IsSysadmin bit = IS_SRVROLEMEMBER('sysadmin') DECLARE @DirectorySeparator nvarchar(max) DECLARE @Updated bit @@ -449,6 +450,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @EngineEdition <> 5 + BEGIN + SET @StartMessage = 'Is sysadmin: ' + CASE WHEN @IsSysadmin = 1 THEN 'Yes' WHEN @IsSysadmin = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index ddca9500..f96dda8b 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-10 19:53:25 //-- + --// Version: 2026-08-12 20:43:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -73,6 +73,7 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupID uniqueidentifier DECLARE @ContainedAvailabilityGroupListenerConnection bit + DECLARE @IsSysadmin bit = IS_SRVROLEMEMBER('sysadmin') DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -291,6 +292,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @EngineEdition <> 5 + BEGIN + SET @StartMessage = 'Is sysadmin: ' + CASE WHEN @IsSysadmin = 1 THEN 'Yes' WHEN @IsSysadmin = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 3720f95e..659fe450 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-10 19:53:25 //-- + --// Version: 2026-08-12 20:43:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -93,6 +93,7 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupID uniqueidentifier DECLARE @ContainedAvailabilityGroupListenerConnection bit + DECLARE @IsSysadmin bit = IS_SRVROLEMEMBER('sysadmin') DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -239,7 +240,7 @@ BEGIN Selected bit DEFAULT 0, AlterIndexCompleted bit DEFAULT 0, UpdateStatisticsCompleted bit DEFAULT 0, - Completed AS CASE WHEN AlterIndexCompleted = 1 AND UpdateStatisticsCompleted = 1 THEN 1 ELSE 0 END, + Completed AS CAST(CASE WHEN AlterIndexCompleted = 1 AND UpdateStatisticsCompleted = 1 THEN 1 ELSE 0 END AS bit) PERSISTED, PRIMARY KEY (Selected, Completed, [Order], ID), INDEX IX_ObjectID_IndexID_PartitionNumber NONCLUSTERED (ObjectID, IndexID, PartitionNumber), INDEX IX_ObjectID_StatisticsID_PartitionNumber NONCLUSTERED (ObjectID, StatisticsID, PartitionNumber)) @@ -470,6 +471,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @EngineEdition <> 5 + BEGIN + SET @StartMessage = 'Is sysadmin: ' + CASE WHEN @IsSysadmin = 1 THEN 'Yes' WHEN @IsSysadmin = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index c0070798..a3f71d68 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: 2026-08-10 19:53:25 +Version: 2026-08-12 20:43:14 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-10 19:53:25 //-- + --// Version: 2026-08-12 20:43:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-10 19:53:25 //-- + --// Version: 2026-08-12 20:43:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -525,6 +525,7 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupID uniqueidentifier DECLARE @ContainedAvailabilityGroupListenerConnection bit + DECLARE @IsSysadmin bit = IS_SRVROLEMEMBER('sysadmin') DECLARE @DirectorySeparator nvarchar(max) DECLARE @Updated bit @@ -848,6 +849,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @EngineEdition <> 5 + BEGIN + SET @StartMessage = 'Is sysadmin: ' + CASE WHEN @IsSysadmin = 1 THEN 'Yes' WHEN @IsSysadmin = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -5144,7 +5151,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-10 19:53:25 //-- + --// Version: 2026-08-12 20:43:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -5177,6 +5184,7 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupID uniqueidentifier DECLARE @ContainedAvailabilityGroupListenerConnection bit + DECLARE @IsSysadmin bit = IS_SRVROLEMEMBER('sysadmin') DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -5395,6 +5403,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @EngineEdition <> 5 + BEGIN + SET @StartMessage = 'Is sysadmin: ' + CASE WHEN @IsSysadmin = 1 THEN 'Yes' WHEN @IsSysadmin = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -7184,7 +7198,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-10 19:53:25 //-- + --// Version: 2026-08-12 20:43:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7221,6 +7235,7 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupID uniqueidentifier DECLARE @ContainedAvailabilityGroupListenerConnection bit + DECLARE @IsSysadmin bit = IS_SRVROLEMEMBER('sysadmin') DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -7367,7 +7382,7 @@ BEGIN Selected bit DEFAULT 0, AlterIndexCompleted bit DEFAULT 0, UpdateStatisticsCompleted bit DEFAULT 0, - Completed AS CASE WHEN AlterIndexCompleted = 1 AND UpdateStatisticsCompleted = 1 THEN 1 ELSE 0 END, + Completed AS CAST(CASE WHEN AlterIndexCompleted = 1 AND UpdateStatisticsCompleted = 1 THEN 1 ELSE 0 END AS bit) PERSISTED, PRIMARY KEY (Selected, Completed, [Order], ID), INDEX IX_ObjectID_IndexID_PartitionNumber NONCLUSTERED (ObjectID, IndexID, PartitionNumber), INDEX IX_ObjectID_StatisticsID_PartitionNumber NONCLUSTERED (ObjectID, StatisticsID, PartitionNumber)) @@ -7598,6 +7613,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @EngineEdition <> 5 + BEGIN + SET @StartMessage = 'Is sysadmin: ' + CASE WHEN @IsSysadmin = 1 THEN 'Yes' WHEN @IsSysadmin = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index ebd52391..c48cb654 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-10 19:53:25 +Version: 2026-08-12 20:43:14 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-10 19:53:25 //-- + --// Version: 2026-08-12 20:43:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-10 19:53:25 //-- + --// Version: 2026-08-12 20:43:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -427,6 +427,7 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupID uniqueidentifier DECLARE @ContainedAvailabilityGroupListenerConnection bit + DECLARE @IsSysadmin bit = IS_SRVROLEMEMBER('sysadmin') DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -645,6 +646,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @EngineEdition <> 5 + BEGIN + SET @StartMessage = 'Is sysadmin: ' + CASE WHEN @IsSysadmin = 1 THEN 'Yes' WHEN @IsSysadmin = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -2434,7 +2441,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-10 19:53:25 //-- + --// Version: 2026-08-12 20:43:14 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2471,6 +2478,7 @@ BEGIN DECLARE @HostPlatform nvarchar(max) DECLARE @ContainedAvailabilityGroupID uniqueidentifier DECLARE @ContainedAvailabilityGroupListenerConnection bit + DECLARE @IsSysadmin bit = IS_SRVROLEMEMBER('sysadmin') DECLARE @QueueID int DECLARE @QueueStartTime datetime2 @@ -2617,7 +2625,7 @@ BEGIN Selected bit DEFAULT 0, AlterIndexCompleted bit DEFAULT 0, UpdateStatisticsCompleted bit DEFAULT 0, - Completed AS CASE WHEN AlterIndexCompleted = 1 AND UpdateStatisticsCompleted = 1 THEN 1 ELSE 0 END, + Completed AS CAST(CASE WHEN AlterIndexCompleted = 1 AND UpdateStatisticsCompleted = 1 THEN 1 ELSE 0 END AS bit) PERSISTED, PRIMARY KEY (Selected, Completed, [Order], ID), INDEX IX_ObjectID_IndexID_PartitionNumber NONCLUSTERED (ObjectID, IndexID, PartitionNumber), INDEX IX_ObjectID_StatisticsID_PartitionNumber NONCLUSTERED (ObjectID, StatisticsID, PartitionNumber)) @@ -2848,6 +2856,12 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END + IF @EngineEdition <> 5 + BEGIN + SET @StartMessage = 'Is sysadmin: ' + CASE WHEN @IsSysadmin = 1 THEN 'Yes' WHEN @IsSysadmin = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT + END + SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 4b9e5cdc..22c3aba2 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -535d23c8dd835214c6b00ed2b21617bebdb9baa3a3156df0066e65b600f81336 CommandExecute.sql +cfaa103607bceb790391f03029b27df1cc6f58e099a105bba70f048d7e40ceb4 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -6f26f231eb7241176d28d0a2c3fafe86cc0f6a621a468a594af3b78f067ed7eb DatabaseBackup.sql -f49dacb8917178ae96535bb147058070e159d3c7437433e56c5f3c0bac60b5cf DatabaseIntegrityCheck.sql -6ff9a9bcbd48b46f30e1ca21cae757beb0701f4dcd0d7814f415aa8ba05c2d63 IndexOptimize.sql -3c26e861f68edd02bd7474a780c6b718a5a88691d3c9ccf48052859767ae7ca2 MaintenanceSolution.sql -20304977b63ebff05ecf2ce9f01a2d0c177625b13ce3a356c56b3387d4a57bb7 MaintenanceSolutionAzureSQLDatabase.sql +dbcbea9621b911b195912eda8fa517d4ed18a8a5013a473f0352e87e0672a636 DatabaseBackup.sql +cfe2f407355ca08113160f7d7132a49bb6f2baa7ed43eb7bd9acb4100a812779 DatabaseIntegrityCheck.sql +0eb13e9f3a39879221126f5f738ece2e6170f5c681e0417caadd893a27c706c1 IndexOptimize.sql +86e27982b79096b8e8b4d30d6d9803c072ca159cd6abcfa6bdda088932fbe344 MaintenanceSolution.sql +ceaaa7ed3fea05ba3c8abc8fb4d6a558c1a38080adb7c087e03035b25f0a19fa MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From be2b1ff58fb48800761d739885d13d404ede698a Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 12 Aug 2026 20:49:20 +0200 Subject: [PATCH 165/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 9 +++------ DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 17 +++++++---------- MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 23 insertions(+), 29 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index bc55e1db..1b639ef8 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-12 20:43:14 //-- + --// Version: 2026-08-12 20:48:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 24e2a5cf..7e3e456b 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:43:14 //-- + --// Version: 2026-08-12 20:48:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -450,11 +450,8 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF @EngineEdition <> 5 - BEGIN - SET @StartMessage = 'Is sysadmin: ' + CASE WHEN @IsSysadmin = 1 THEN 'Yes' WHEN @IsSysadmin = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END + SET @StartMessage = 'Is sysadmin: ' + CASE WHEN @IsSysadmin = 1 THEN 'Yes' WHEN @IsSysadmin = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index f96dda8b..dda0483f 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:43:14 //-- + --// Version: 2026-08-12 20:48:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 659fe450..0617e514 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:43:14 //-- + --// Version: 2026-08-12 20:48:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index a3f71d68..59327fce 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: 2026-08-12 20:43:14 +Version: 2026-08-12 20:48:42 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:43:14 //-- + --// Version: 2026-08-12 20:48:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:43:14 //-- + --// Version: 2026-08-12 20:48:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -849,11 +849,8 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF @EngineEdition <> 5 - BEGIN - SET @StartMessage = 'Is sysadmin: ' + CASE WHEN @IsSysadmin = 1 THEN 'Yes' WHEN @IsSysadmin = 0 THEN 'No' ELSE 'N/A' END - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END + SET @StartMessage = 'Is sysadmin: ' + CASE WHEN @IsSysadmin = 1 THEN 'Yes' WHEN @IsSysadmin = 0 THEN 'No' ELSE 'N/A' END + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT SET @StartMessage = 'Database: ' + QUOTENAME(DB_NAME()) RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT @@ -5151,7 +5148,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:43:14 //-- + --// Version: 2026-08-12 20:48:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7198,7 +7195,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:43:14 //-- + --// Version: 2026-08-12 20:48:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index c48cb654..50796e9e 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-12 20:43:14 +Version: 2026-08-12 20:48:42 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:43:14 //-- + --// Version: 2026-08-12 20:48:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:43:14 //-- + --// Version: 2026-08-12 20:48:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2441,7 +2441,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:43:14 //-- + --// Version: 2026-08-12 20:48:42 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 22c3aba2..0e054f1b 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -cfaa103607bceb790391f03029b27df1cc6f58e099a105bba70f048d7e40ceb4 CommandExecute.sql +64257c72cbb193860bf3c611cdd48bf0de765740aafda056760057a075810303 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -dbcbea9621b911b195912eda8fa517d4ed18a8a5013a473f0352e87e0672a636 DatabaseBackup.sql -cfe2f407355ca08113160f7d7132a49bb6f2baa7ed43eb7bd9acb4100a812779 DatabaseIntegrityCheck.sql -0eb13e9f3a39879221126f5f738ece2e6170f5c681e0417caadd893a27c706c1 IndexOptimize.sql -86e27982b79096b8e8b4d30d6d9803c072ca159cd6abcfa6bdda088932fbe344 MaintenanceSolution.sql -ceaaa7ed3fea05ba3c8abc8fb4d6a558c1a38080adb7c087e03035b25f0a19fa MaintenanceSolutionAzureSQLDatabase.sql +4256ea0a080303e50b88931c920247ab34b00555d527094b1ef95421af29f4fe DatabaseBackup.sql +dfd64bd0d680e7cc059d22f4e333ecffba11858c757a3484bdf52e410a559031 DatabaseIntegrityCheck.sql +5d1484f43c563af526bac077d562df27c32004a27179bb826334fd708c52aefa IndexOptimize.sql +3cfe1c0b790e43abea9495fdc2edbae612d553da1cd271954563b62d19cad4da MaintenanceSolution.sql +fcc01c8b317c0c40bc1095088c967259080f6865bee4ab941edfba97d7d5a6e4 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 3e7dea804646cbcdd4f0ba5b3b07c87345e6566a Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 12 Aug 2026 21:00:06 +0200 Subject: [PATCH 166/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 9 +++------ DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 17 +++++++---------- MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 23 insertions(+), 29 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 1b639ef8..76c2e30e 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-12 20:48:42 //-- + --// Version: 2026-08-12 20:57:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 7e3e456b..359bd670 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:48:42 //-- + --// Version: 2026-08-12 20:57:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -319,11 +319,8 @@ BEGIN SET @Version = 16.01000 END - IF @EngineEdition <> 5 - BEGIN - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info - END + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) BEGIN diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index dda0483f..10fc45cb 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:48:42 //-- + --// Version: 2026-08-12 20:57:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 0617e514..a0410f93 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:48:42 //-- + --// Version: 2026-08-12 20:57:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 59327fce..512b9dc4 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: 2026-08-12 20:48:42 +Version: 2026-08-12 20:57:17 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:48:42 //-- + --// Version: 2026-08-12 20:57:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:48:42 //-- + --// Version: 2026-08-12 20:57:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -718,11 +718,8 @@ BEGIN SET @Version = 16.01000 END - IF @EngineEdition <> 5 - BEGIN - SELECT @HostPlatform = host_platform - FROM sys.dm_os_host_info - END + SELECT @HostPlatform = host_platform + FROM sys.dm_os_host_info IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) BEGIN @@ -5148,7 +5145,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:48:42 //-- + --// Version: 2026-08-12 20:57:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7195,7 +7192,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:48:42 //-- + --// Version: 2026-08-12 20:57:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 50796e9e..37a8ba12 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-12 20:48:42 +Version: 2026-08-12 20:57:17 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:48:42 //-- + --// Version: 2026-08-12 20:57:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:48:42 //-- + --// Version: 2026-08-12 20:57:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2441,7 +2441,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:48:42 //-- + --// Version: 2026-08-12 20:57:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 0e054f1b..a03d3145 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -64257c72cbb193860bf3c611cdd48bf0de765740aafda056760057a075810303 CommandExecute.sql +7b4c3e1dd76bd7bd260dea7e2839b7c8acd28030106a1fb588102e8f3a6e0a09 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -4256ea0a080303e50b88931c920247ab34b00555d527094b1ef95421af29f4fe DatabaseBackup.sql -dfd64bd0d680e7cc059d22f4e333ecffba11858c757a3484bdf52e410a559031 DatabaseIntegrityCheck.sql -5d1484f43c563af526bac077d562df27c32004a27179bb826334fd708c52aefa IndexOptimize.sql -3cfe1c0b790e43abea9495fdc2edbae612d553da1cd271954563b62d19cad4da MaintenanceSolution.sql -fcc01c8b317c0c40bc1095088c967259080f6865bee4ab941edfba97d7d5a6e4 MaintenanceSolutionAzureSQLDatabase.sql +7fd61c180e90d2f92a9e6e83f45b60921182b9b4ad7054f2b9cb96ffcef777c7 DatabaseBackup.sql +63533fdc9c4cfe8660b912e23312b9e2bda7fa24f401adbfc36dda59d869540e DatabaseIntegrityCheck.sql +2d83bf82093d03b94fbee47b89b23694aef2cd55fceeede50d172a0ac9f2599d IndexOptimize.sql +f94d49c6d6112bbdc9bbe82d94a340398db0af772047545cbcc2a7207fc0c4b9 MaintenanceSolution.sql +be1e9ae0752549ad9563144126cba58833c4dea748b1098bcdf3dc218f470f29 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 58f5d39cc1adb11ce52c30f0c6fd0dd5a22a652e Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Wed, 12 Aug 2026 22:03:15 +0200 Subject: [PATCH 167/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 9 +++------ DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 17 +++++++---------- MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 23 insertions(+), 29 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 76c2e30e..efa3905b 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-12 20:57:17 //-- + --// Version: 2026-08-12 22:02:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 359bd670..50ce13ad 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:57:17 //-- + --// Version: 2026-08-12 22:02:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -435,11 +435,8 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF @EngineEdition <> 5 - BEGIN - SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END + SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) BEGIN diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 10fc45cb..d8263959 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:57:17 //-- + --// Version: 2026-08-12 22:02:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index a0410f93..7fc5f425 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:57:17 //-- + --// Version: 2026-08-12 22:02:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 512b9dc4..39c85ed2 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: 2026-08-12 20:57:17 +Version: 2026-08-12 22:02:18 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:57:17 //-- + --// Version: 2026-08-12 22:02:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:57:17 //-- + --// Version: 2026-08-12 22:02:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -834,11 +834,8 @@ BEGIN RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT END - IF @EngineEdition <> 5 - BEGIN - SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') - RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT - END + SET @StartMessage = 'Platform: ' + ISNULL(@HostPlatform, 'N/A') + RAISERROR('%s',10,1,@StartMessage) WITH NOWAIT IF @Version >= 16 AND @EngineEdition NOT IN(5, 8) BEGIN @@ -5145,7 +5142,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:57:17 //-- + --// Version: 2026-08-12 22:02:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7192,7 +7189,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:57:17 //-- + --// Version: 2026-08-12 22:02:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 37a8ba12..3f558d20 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-12 20:57:17 +Version: 2026-08-12 22:02:18 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:57:17 //-- + --// Version: 2026-08-12 22:02:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:57:17 //-- + --// Version: 2026-08-12 22:02:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2441,7 +2441,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 20:57:17 //-- + --// Version: 2026-08-12 22:02:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index a03d3145..36df13d6 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -7b4c3e1dd76bd7bd260dea7e2839b7c8acd28030106a1fb588102e8f3a6e0a09 CommandExecute.sql +938b3267b5cb3e37bae4a494cf46b8097a7eb7404842c77d1e06358e6ace992c CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -7fd61c180e90d2f92a9e6e83f45b60921182b9b4ad7054f2b9cb96ffcef777c7 DatabaseBackup.sql -63533fdc9c4cfe8660b912e23312b9e2bda7fa24f401adbfc36dda59d869540e DatabaseIntegrityCheck.sql -2d83bf82093d03b94fbee47b89b23694aef2cd55fceeede50d172a0ac9f2599d IndexOptimize.sql -f94d49c6d6112bbdc9bbe82d94a340398db0af772047545cbcc2a7207fc0c4b9 MaintenanceSolution.sql -be1e9ae0752549ad9563144126cba58833c4dea748b1098bcdf3dc218f470f29 MaintenanceSolutionAzureSQLDatabase.sql +102d5f072df10e193606d1f5252481472bc66ea1087dac838cb28d09e4e6e779 DatabaseBackup.sql +b52d37a50d82627673fc785dfef195514be9d77ba3e5591a29002a9413ef48d0 DatabaseIntegrityCheck.sql +5503533f789764672100842ddbf67522586d0b43ac009388a98a8320bceb8692 IndexOptimize.sql +ea0d42d2328c8d72237aae01c74a02e05442cc64ca5ce953c5e6a0e6fcf0456b MaintenanceSolution.sql +b9598654946e9274410b4489d59b90198f7775d4a4d6e33ec4f46490396bd674 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 9d1c2c8fc81ade27e30d766e95e999983fb35d1a Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 16 Aug 2026 22:01:36 +0200 Subject: [PATCH 168/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 12 ++++++++++-- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 20 ++++++++++++++------ MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 37 insertions(+), 21 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index efa3905b..374ff1e2 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-12 22:02:18 //-- + --// Version: 2026-08-16 22:00:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 50ce13ad..4e87727f 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 22:02:18 //-- + --// Version: 2026-08-16 22:00:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4066,7 +4066,15 @@ BEGIN END -- Perform a backup - IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE DirectoryPath <> 'NUL' AND DirectoryPath NOT IN(SELECT DirectoryPath FROM @Directories) AND (CreateOutput <> 0 OR CreateOutput IS NULL)) + IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @CurrentDatabaseName LIKE '%"%' + BEGIN + SET @ErrorMessage = 'The name of the database ' + QUOTENAME(@CurrentDatabaseName) + ' is not supported. Double quotes (") are not supported with Data Domain Boost.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + SET @ReturnCode = @Error + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + ELSE 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 diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index d8263959..71ca63d7 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 22:02:18 //-- + --// Version: 2026-08-16 22:00:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 7fc5f425..857d6dfb 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 22:02:18 //-- + --// Version: 2026-08-16 22:00:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 39c85ed2..c6bb8361 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: 2026-08-12 22:02:18 +Version: 2026-08-16 22:00:30 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 22:02:18 //-- + --// Version: 2026-08-16 22:00:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 22:02:18 //-- + --// Version: 2026-08-16 22:00:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -4465,7 +4465,15 @@ BEGIN END -- Perform a backup - IF NOT EXISTS (SELECT * FROM @CurrentDirectories WHERE DirectoryPath <> 'NUL' AND DirectoryPath NOT IN(SELECT DirectoryPath FROM @Directories) AND (CreateOutput <> 0 OR CreateOutput IS NULL)) + IF @BackupSoftware = 'DATA_DOMAIN_BOOST' AND @CurrentDatabaseName LIKE '%"%' + BEGIN + SET @ErrorMessage = 'The name of the database ' + QUOTENAME(@CurrentDatabaseName) + ' is not supported. Double quotes (") are not supported with Data Domain Boost.' + RAISERROR('%s',16,1,@ErrorMessage) WITH NOWAIT + SET @Error = @@ERROR + SET @ReturnCode = @Error + RAISERROR(@EmptyLine,10,1) WITH NOWAIT + END + ELSE 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 @@ -5142,7 +5150,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 22:02:18 //-- + --// Version: 2026-08-16 22:00:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7189,7 +7197,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 22:02:18 //-- + --// Version: 2026-08-16 22:00:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 3f558d20..243317c4 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-12 22:02:18 +Version: 2026-08-16 22:00:30 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 22:02:18 //-- + --// Version: 2026-08-16 22:00:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 22:02:18 //-- + --// Version: 2026-08-16 22:00:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2441,7 +2441,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-12 22:02:18 //-- + --// Version: 2026-08-16 22:00:30 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 36df13d6..c6a3ddcb 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -938b3267b5cb3e37bae4a494cf46b8097a7eb7404842c77d1e06358e6ace992c CommandExecute.sql +9c8c21aa167ffbd1fa688a0fd6dc4d83a3fc85c663f45ecb8f2342305cd7f0d0 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -102d5f072df10e193606d1f5252481472bc66ea1087dac838cb28d09e4e6e779 DatabaseBackup.sql -b52d37a50d82627673fc785dfef195514be9d77ba3e5591a29002a9413ef48d0 DatabaseIntegrityCheck.sql -5503533f789764672100842ddbf67522586d0b43ac009388a98a8320bceb8692 IndexOptimize.sql -ea0d42d2328c8d72237aae01c74a02e05442cc64ca5ce953c5e6a0e6fcf0456b MaintenanceSolution.sql -b9598654946e9274410b4489d59b90198f7775d4a4d6e33ec4f46490396bd674 MaintenanceSolutionAzureSQLDatabase.sql +b6dc274ab93c4fb29f28aa230e2b0a9fbf2a44069bf734e7bf976a21e5493290 DatabaseBackup.sql +0f3a51bc022c028dde63db8d95f0c66837faece3b3d669147363d11585981016 DatabaseIntegrityCheck.sql +22f34313b16d33c50def162f269e805ff9e1d42cbd0c62b77dc8c5ead842e199 IndexOptimize.sql +87d19062655520ed3e283518dc90ecc2918ae62143293f22f64aaa1820df344c MaintenanceSolution.sql +59ce249f832d9485a429b14e5d238f180e06a5c35beada7b91e65cb3b83fea91 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 40c8bd680ba403fd6e8c816c9190e44f8b93abd5 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 16 Aug 2026 23:10:45 +0200 Subject: [PATCH 169/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 6 +++--- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 14 +++++++------- MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 23 insertions(+), 23 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 374ff1e2..2df0c1ed 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-16 22:00:30 //-- + --// Version: 2026-08-16 23:09:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 4e87727f..1016afda 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 22:00:30 //-- + --// Version: 2026-08-16 23:09:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2431,7 +2431,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(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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(REPLACE(@FileName,'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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]) VALUES('The parameter @FileName contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) @@ -2439,7 +2439,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(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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(REPLACE(@AvailabilityGroupFileName,'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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]) VALUES('The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 71ca63d7..0ed08c2e 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 22:00:30 //-- + --// Version: 2026-08-16 23:09:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 857d6dfb..678619aa 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 22:00:30 //-- + --// Version: 2026-08-16 23:09:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index c6bb8361..5c927242 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: 2026-08-16 22:00:30 +Version: 2026-08-16 23:09:18 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 22:00:30 //-- + --// Version: 2026-08-16 23:09:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 22:00:30 //-- + --// Version: 2026-08-16 23:09:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2830,7 +2830,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(REPLACE(REPLACE(REPLACE(@FileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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(REPLACE(@FileName,'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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]) VALUES('The parameter @FileName contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) @@ -2838,7 +2838,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(REPLACE(REPLACE(REPLACE(@AvailabilityGroupFileName,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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(REPLACE(@AvailabilityGroupFileName,'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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]) VALUES('The parameter @AvailabilityGroupFileName contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#AvailabilityGroupFileName.', 16, 1) @@ -5150,7 +5150,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 22:00:30 //-- + --// Version: 2026-08-16 23:09:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7197,7 +7197,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 22:00:30 //-- + --// Version: 2026-08-16 23:09:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 243317c4..06522b21 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-16 22:00:30 +Version: 2026-08-16 23:09:18 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 22:00:30 //-- + --// Version: 2026-08-16 23:09:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 22:00:30 //-- + --// Version: 2026-08-16 23:09:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2441,7 +2441,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 22:00:30 //-- + --// Version: 2026-08-16 23:09:18 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index c6a3ddcb..69f5f3bd 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -9c8c21aa167ffbd1fa688a0fd6dc4d83a3fc85c663f45ecb8f2342305cd7f0d0 CommandExecute.sql +e8aa2929579cffadb46f7ec2bc15ab75d5b98fa0451eab6c62828f5633efcd28 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -b6dc274ab93c4fb29f28aa230e2b0a9fbf2a44069bf734e7bf976a21e5493290 DatabaseBackup.sql -0f3a51bc022c028dde63db8d95f0c66837faece3b3d669147363d11585981016 DatabaseIntegrityCheck.sql -22f34313b16d33c50def162f269e805ff9e1d42cbd0c62b77dc8c5ead842e199 IndexOptimize.sql -87d19062655520ed3e283518dc90ecc2918ae62143293f22f64aaa1820df344c MaintenanceSolution.sql -59ce249f832d9485a429b14e5d238f180e06a5c35beada7b91e65cb3b83fea91 MaintenanceSolutionAzureSQLDatabase.sql +37a0154d2957684ab5a079d777e150297f650f562a6b9008c23d75bf90571a11 DatabaseBackup.sql +35a0ee74612ef6c2e965729796c5d246d1fb02db0c86e3bb9016b894da2db25e DatabaseIntegrityCheck.sql +b6f17cc35f439a433b2e41b0f367f446dec83b8150565cdda2cd4eae88ffbbc3 IndexOptimize.sql +7c7900bda25e4d2a03cf5630d79b778f987b07249b20c923fd0dfc3b0289c405 MaintenanceSolution.sql +46f5a846c57c1f78af1373fc0d9347e60727167a9f7a1be21770364fb7130ac6 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 8da092fdf871634a023b8954dfa13c2ac5bf63b8 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Mon, 17 Aug 2026 22:23:10 +0200 Subject: [PATCH 170/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 14 ++++++++++---- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 22 ++++++++++++++-------- MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 37 insertions(+), 25 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 2df0c1ed..ef654cbd 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-16 23:09:18 //-- + --// Version: 2026-08-17 22:22:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 1016afda..265185ee 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 23:09:18 //-- + --// Version: 2026-08-17 22:22:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1136,7 +1136,7 @@ BEGIN VALUES('The number of URLs for the parameters @URL and @MirrorURL has to be the same. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END - IF EXISTS(SELECT * FROM @URLs WHERE DirectoryPath LIKE 's3://%/%') AND NOT ((@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND @EngineEdition IN(2, 3, 8)) + IF EXISTS(SELECT * FROM @URLs WHERE DirectoryPath LIKE 's3://%/%') AND NOT (@Version >= 16 AND @EngineEdition IN(2, 3)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('Backup to S3-compatible storage is not supported in this version and edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) @@ -2415,7 +2415,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(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The parameter @DirectoryStructure contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#DirectoryStructure.', 16, 1) @@ -2431,7 +2431,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(REPLACE(REPLACE(@FileName,'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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,'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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]) VALUES('The parameter @FileName contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) @@ -2611,6 +2611,12 @@ BEGIN VALUES('The parameter @RetainDays is only supported with SQL Server native backups and LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#RetainDays.', 16, 1) END + IF @ExpireDate IS NOT NULL AND @RetainDays IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameters @ExpireDate and @RetainDays cannot be used together. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) + END + ---------------------------------------------------------------------------------------------------- IF @AllowNonCopyOnlyBackupsOnForwarder NOT IN('Y','N') OR @AllowNonCopyOnlyBackupsOnForwarder IS NULL diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 0ed08c2e..497d2d1f 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 23:09:18 //-- + --// Version: 2026-08-17 22:22:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 678619aa..8cdadfd0 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 23:09:18 //-- + --// Version: 2026-08-17 22:22:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 5c927242..1d731dbb 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: 2026-08-16 23:09:18 +Version: 2026-08-17 22:22:29 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 23:09:18 //-- + --// Version: 2026-08-17 22:22:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 23:09:18 //-- + --// Version: 2026-08-17 22:22:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1535,7 +1535,7 @@ BEGIN VALUES('The number of URLs for the parameters @URL and @MirrorURL has to be the same. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) END - IF EXISTS(SELECT * FROM @URLs WHERE DirectoryPath LIKE 's3://%/%') AND NOT ((@Version >= 16 OR (@EngineEdition = 8 AND @ProductUpdateType = 'Continuous')) AND @EngineEdition IN(2, 3, 8)) + IF EXISTS(SELECT * FROM @URLs WHERE DirectoryPath LIKE 's3://%/%') AND NOT (@Version >= 16 AND @EngineEdition IN(2, 3)) BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('Backup to S3-compatible storage is not supported in this version and edition of SQL Server. See https://ola.hallengren.com/sql-server-backup.html#URL.', 16, 1) @@ -2814,7 +2814,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(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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(REPLACE(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The parameter @DirectoryStructure contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#DirectoryStructure.', 16, 1) @@ -2830,7 +2830,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(REPLACE(REPLACE(@FileName,'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{AvailabilityGroupName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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,'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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]) VALUES('The parameter @FileName contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) @@ -3010,6 +3010,12 @@ BEGIN VALUES('The parameter @RetainDays is only supported with SQL Server native backups and LiteSpeed for SQL Server. See https://ola.hallengren.com/sql-server-backup.html#RetainDays.', 16, 1) END + IF @ExpireDate IS NOT NULL AND @RetainDays IS NOT NULL + BEGIN + INSERT INTO @Errors ([Message], Severity, [State]) + VALUES('The parameters @ExpireDate and @RetainDays cannot be used together. See https://ola.hallengren.com/sql-server-backup.html.', 16, 1) + END + ---------------------------------------------------------------------------------------------------- IF @AllowNonCopyOnlyBackupsOnForwarder NOT IN('Y','N') OR @AllowNonCopyOnlyBackupsOnForwarder IS NULL @@ -5150,7 +5156,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 23:09:18 //-- + --// Version: 2026-08-17 22:22:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7197,7 +7203,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 23:09:18 //-- + --// Version: 2026-08-17 22:22:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 06522b21..611e519b 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-16 23:09:18 +Version: 2026-08-17 22:22:29 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 23:09:18 //-- + --// Version: 2026-08-17 22:22:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 23:09:18 //-- + --// Version: 2026-08-17 22:22:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2441,7 +2441,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-16 23:09:18 //-- + --// Version: 2026-08-17 22:22:29 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 69f5f3bd..fe9b279b 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -e8aa2929579cffadb46f7ec2bc15ab75d5b98fa0451eab6c62828f5633efcd28 CommandExecute.sql +80e65a63e0dd81a8073c69b538ba222381354bd3435ba6141e6fb8eb6acbb070 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -37a0154d2957684ab5a079d777e150297f650f562a6b9008c23d75bf90571a11 DatabaseBackup.sql -35a0ee74612ef6c2e965729796c5d246d1fb02db0c86e3bb9016b894da2db25e DatabaseIntegrityCheck.sql -b6f17cc35f439a433b2e41b0f367f446dec83b8150565cdda2cd4eae88ffbbc3 IndexOptimize.sql -7c7900bda25e4d2a03cf5630d79b778f987b07249b20c923fd0dfc3b0289c405 MaintenanceSolution.sql -46f5a846c57c1f78af1373fc0d9347e60727167a9f7a1be21770364fb7130ac6 MaintenanceSolutionAzureSQLDatabase.sql +503d04e5047622c273ab2a24b7a08ae5fec7f56e105f73e16a12c25eaa082194 DatabaseBackup.sql +19e773fe4b4ee9956899e281799745269b4f610e70cb875dc71e4c72f583b3ce DatabaseIntegrityCheck.sql +06c03f53f96d0e13945fc14a3c83e55d6409e3c38ffbc113b4936f80287f327f IndexOptimize.sql +8d4b5fa1f45dfb78a6267cca11d4bc4cfb52109952b59399d6c8d171be55be83 MaintenanceSolution.sql +20ac5ac10110a137dfddeec3daa34e6b885ef18809dd84e95fdd5770a4eebb72 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 0099d2a54bc025fd06c31cd3d3e31b4a146d8c5a Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 23 Aug 2026 10:18:40 +0200 Subject: [PATCH 171/177] Update sql-server-backup.md --- docs/sql-server-backup.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/sql-server-backup.md b/docs/sql-server-backup.md index 009aa2d0..e7c5aba2 100644 --- a/docs/sql-server-backup.md +++ b/docs/sql-server-backup.md @@ -813,7 +813,6 @@ EXECUTE dbo.DatabaseBackup EXECUTE dbo.DatabaseBackup @Databases = 'USER_DATABASES', @URL = 'https://myaccount.blob.core.windows.net/mycontainer', -@Credential = 'MyCredential', @BackupType = 'FULL', @Compress = 'Y', @Verify = 'Y' From a4dacdc48eae48c91f9563a55cb19eeb061d1860 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 23 Aug 2026 11:37:16 +0200 Subject: [PATCH 172/177] Add files via upload --- docs/sql-server-backup.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/docs/sql-server-backup.md b/docs/sql-server-backup.md index e7c5aba2..ef476e59 100644 --- a/docs/sql-server-backup.md +++ b/docs/sql-server-backup.md @@ -455,6 +455,16 @@ You can use the following tokens: | CopyOnly | COPY_ONLY for copy-only backups | | Description | Backup description | | BackupSetName | Backup set name | +| Year | Year | +| Month | Month | +| Day | Day | +| Week | Week | +| Weekday | Weekday | +| Hour | Hour | +| Minute | Minute | +| Second | Second | +| Millisecond | Millisecond | +| Microsecond | Microsecond | | MajorVersion | Major version | | MinorVersion | Minor version | | DirectorySeparator | The directory separator | @@ -484,6 +494,16 @@ You can use the following tokens: | CopyOnly | COPY_ONLY for copy-only backups | | Description | Backup description | | BackupSetName | Backup set name | +| Year | Year | +| Month | Month | +| Day | Day | +| Week | Week | +| Weekday | Weekday | +| Hour | Hour | +| Minute | Minute | +| Second | Second | +| Millisecond | Millisecond | +| Microsecond | Microsecond | | MajorVersion | Major version | | MinorVersion | Minor version | | DirectorySeparator | The directory separator | From 12dd1faf1cb99fdfd29de0c31d7aa55b9740b705 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 23 Aug 2026 12:20:58 +0200 Subject: [PATCH 173/177] Add files via upload --- docs/sql-server-backup.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/docs/sql-server-backup.md b/docs/sql-server-backup.md index ef476e59..2d1679de 100644 --- a/docs/sql-server-backup.md +++ b/docs/sql-server-backup.md @@ -80,7 +80,13 @@ The Verify option in DatabaseBackup uses the SQL Server [RESTORE VERIFYONLY](htt Specify the time, in hours, after which the backup files are deleted. If no time is specified, then no backup files are deleted. -DatabaseBackup has a check to verify that transaction log backups that are newer than the most recent full or differential backup are not deleted. +By default, backup files are deleted after each database is backed up and verified. Backup files are deleted only if the backup and verification of the database were successful. + +DatabaseBackup has a check to verify that transaction log backups that are newer than the most recent full or differential backup are not deleted. This is to guarantee that you can always perform a point-in-time restore. + +DatabaseBackup uses the extended stored procedure xp_delete_file to delete backup files. xp_delete_file deletes files based on a directory, a file extension, and a modified date. Therefore if you are using date or time tokens (e.g. {Year}, {Month}, and {Day}) in the parameters @DirectoryStructure or @AvailabilityGroupDirectoryStructure, then old backup files may be in different directories, and may not be deleted. + +Cleanup is not supported when backing up to URL. ### CleanupMode @@ -335,6 +341,10 @@ By default, backup files are deleted after each database is backed up and verifi DatabaseBackup has a check to verify that transaction log backups that are newer than the most recent full or differential backup are not deleted. This is to guarantee that you can always perform a point-in-time restore. +DatabaseBackup uses the extended stored procedure xp_delete_file to delete backup files. xp_delete_file deletes files based on a directory, a file extension, and a modified date. Therefore if you are using date or time tokens (e.g. {Year}, {Month}, and {Day}) in the parameters @DirectoryStructure or @AvailabilityGroupDirectoryStructure, then old backup files may be in different directories, and may not be deleted. + +Cleanup is not supported when backing up to URL. + ### MirrorCleanupMode Specify whether old backup files in the mirror directory should be deleted before or after the backup has been performed. From 423a5b175b1f2a54926de49564d77a6a3998cd0f Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 23 Aug 2026 12:40:35 +0200 Subject: [PATCH 174/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 6 +++--- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 14 +++++++------- MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 23 insertions(+), 23 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index ef654cbd..f3dab4cb 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-17 22:22:29 //-- + --// Version: 2026-08-23 12:39:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 265185ee..47ce5a99 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-17 22:22:29 //-- + --// Version: 2026-08-23 12:39:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2415,7 +2415,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(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The parameter @DirectoryStructure contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#DirectoryStructure.', 16, 1) @@ -2431,7 +2431,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(REPLACE(@FileName,'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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(@FileName,'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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]) VALUES('The parameter @FileName contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index 497d2d1f..f394ef55 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-17 22:22:29 //-- + --// Version: 2026-08-23 12:39:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 8cdadfd0..f94c6b67 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-17 22:22:29 //-- + --// Version: 2026-08-23 12:39:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 1d731dbb..220bf96a 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: 2026-08-17 22:22:29 +Version: 2026-08-23 12:39:41 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-17 22:22:29 //-- + --// Version: 2026-08-23 12:39:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-17 22:22:29 //-- + --// Version: 2026-08-23 12:39:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2814,7 +2814,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(@DirectoryStructure,'{DirectorySeparator}',''),'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{Hour}',''),'{Minute}',''),'{Second}',''),'{Millisecond}',''),'{Microsecond}',''),'{MajorVersion}',''),'{MinorVersion}','') AS DirectoryStructure) Temp WHERE DirectoryStructure LIKE '%{%' OR DirectoryStructure LIKE '%}%') BEGIN INSERT INTO @Errors ([Message], Severity, [State]) VALUES('The parameter @DirectoryStructure contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#DirectoryStructure.', 16, 1) @@ -2830,7 +2830,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(REPLACE(@FileName,'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{ClusterName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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(@FileName,'{ServerName}',''),'{InstanceName}',''),'{ServiceName}',''),'{DatabaseName}',''),'{BackupType}',''),'{Partial}',''),'{CopyOnly}',''),'{Description}',''),'{BackupSetName}',''),'{Year}',''),'{Month}',''),'{Day}',''),'{Week}',''),'{Weekday}',''),'{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]) VALUES('The parameter @FileName contains one or more tokens that are not supported. See https://ola.hallengren.com/sql-server-backup.html#FileName.', 16, 1) @@ -5156,7 +5156,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-17 22:22:29 //-- + --// Version: 2026-08-23 12:39:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7203,7 +7203,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-17 22:22:29 //-- + --// Version: 2026-08-23 12:39:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 611e519b..7889fb1a 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-17 22:22:29 +Version: 2026-08-23 12:39:41 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-17 22:22:29 //-- + --// Version: 2026-08-23 12:39:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-17 22:22:29 //-- + --// Version: 2026-08-23 12:39:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2441,7 +2441,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-17 22:22:29 //-- + --// Version: 2026-08-23 12:39:41 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index fe9b279b..51b29522 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -80e65a63e0dd81a8073c69b538ba222381354bd3435ba6141e6fb8eb6acbb070 CommandExecute.sql +9e9f725972f82497a13570259fd333e5d70732134a9aaa0509d9c726bcc0c8a2 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -503d04e5047622c273ab2a24b7a08ae5fec7f56e105f73e16a12c25eaa082194 DatabaseBackup.sql -19e773fe4b4ee9956899e281799745269b4f610e70cb875dc71e4c72f583b3ce DatabaseIntegrityCheck.sql -06c03f53f96d0e13945fc14a3c83e55d6409e3c38ffbc113b4936f80287f327f IndexOptimize.sql -8d4b5fa1f45dfb78a6267cca11d4bc4cfb52109952b59399d6c8d171be55be83 MaintenanceSolution.sql -20ac5ac10110a137dfddeec3daa34e6b885ef18809dd84e95fdd5770a4eebb72 MaintenanceSolutionAzureSQLDatabase.sql +8e3bc4ffa4515a809638a883535633e5aadce72de100c03ae800e149c931d46f DatabaseBackup.sql +aa32ffee55c30ab2a5e8266ab8c2ba34c207ce2e0d6b48b7c0b14348dd7efefe DatabaseIntegrityCheck.sql +1db2fd5f28c5d3da2bd04a402b9ac61287a9a4352de3886c2d61ff3c69a41466 IndexOptimize.sql +cca8c5162e9a819af6f9e9e1d966cdb8e7f8dfb136a5ae0481ee7df9405b1e3b MaintenanceSolution.sql +ac2fc1a8723b818cf72eb2fe7df50e70b8ffef1b143658a451fa2a4685d9edfe MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From b45825113653b753341f8bc2939fa29fde6d8db3 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 23 Aug 2026 14:18:43 +0200 Subject: [PATCH 175/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 8 +++----- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 16 +++++++--------- MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 23 insertions(+), 27 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index f3dab4cb..079b8009 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-23 12:39:41 //-- + --// Version: 2026-08-23 14:14:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 47ce5a99..f139f5d6 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 12:39:41 //-- + --// Version: 2026-08-23 14:14:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3405,7 +3405,6 @@ BEGIN 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 @InstanceName IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}','') IF @@SERVICENAME IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}','') IF @Description IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}','') @@ -3557,7 +3556,7 @@ BEGIN -- Directory structure - replace tokens with real values SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}',@DirectorySeparator) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}',CASE WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) > 0 THEN LEFT(@ServerName,CHARINDEX('.',@ServerName) - 1) ELSE @MachineName END) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}',CASE WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) > 0 THEN LEFT(@ServerName,CHARINDEX('.',@ServerName) - 1) WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) = 0 THEN @ServerName ELSE @MachineName END) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}',ISNULL(@InstanceName,'')) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}',ISNULL(@@SERVICENAME,'')) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}',ISNULL(@Cluster,'')) @@ -3615,7 +3614,6 @@ BEGIN 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 @InstanceName IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}','') IF @@SERVICENAME IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}','') IF @Description IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}','') @@ -3722,7 +3720,7 @@ BEGIN END -- File name - replace tokens with real values - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServerName}',CASE WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) > 0 THEN LEFT(@ServerName,CHARINDEX('.',@ServerName) - 1) ELSE @MachineName END) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServerName}',CASE WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) > 0 THEN LEFT(@ServerName,CHARINDEX('.',@ServerName) - 1) WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) = 0 THEN @ServerName ELSE @MachineName END) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}',ISNULL(@InstanceName,'')) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}',ISNULL(@@SERVICENAME,'')) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}',ISNULL(@Cluster,'')) diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index f394ef55..b7311eb3 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 12:39:41 //-- + --// Version: 2026-08-23 14:14:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index f94c6b67..09b2c9e8 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 12:39:41 //-- + --// Version: 2026-08-23 14:14:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 220bf96a..64634e9f 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: 2026-08-23 12:39:41 +Version: 2026-08-23 14:14:17 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 12:39:41 //-- + --// Version: 2026-08-23 14:14:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 12:39:41 //-- + --// Version: 2026-08-23 14:14:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -3804,7 +3804,6 @@ BEGIN 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 @InstanceName IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}','') IF @@SERVICENAME IS NULL SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}','') IF @Description IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{Description}','') @@ -3956,7 +3955,7 @@ BEGIN -- Directory structure - replace tokens with real values SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{DirectorySeparator}',@DirectorySeparator) - SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}',CASE WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) > 0 THEN LEFT(@ServerName,CHARINDEX('.',@ServerName) - 1) ELSE @MachineName END) + SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServerName}',CASE WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) > 0 THEN LEFT(@ServerName,CHARINDEX('.',@ServerName) - 1) WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) = 0 THEN @ServerName ELSE @MachineName END) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{InstanceName}',ISNULL(@InstanceName,'')) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ServiceName}',ISNULL(@@SERVICENAME,'')) SET @CurrentDirectoryStructure = REPLACE(@CurrentDirectoryStructure,'{ClusterName}',ISNULL(@Cluster,'')) @@ -4014,7 +4013,6 @@ BEGIN 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 @InstanceName IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}','') IF @@SERVICENAME IS NULL SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}','') IF @Description IS NULL OR LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@Description,'\',''),'/',''),':',''),'*',''),'?',''),'"',''),'<',''),'>',''),'|',''))) = '' SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{Description}','') @@ -4121,7 +4119,7 @@ BEGIN END -- File name - replace tokens with real values - SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServerName}',CASE WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) > 0 THEN LEFT(@ServerName,CHARINDEX('.',@ServerName) - 1) ELSE @MachineName END) + SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServerName}',CASE WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) > 0 THEN LEFT(@ServerName,CHARINDEX('.',@ServerName) - 1) WHEN @EngineEdition = 8 AND CHARINDEX('.',@ServerName) = 0 THEN @ServerName ELSE @MachineName END) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{InstanceName}',ISNULL(@InstanceName,'')) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ServiceName}',ISNULL(@@SERVICENAME,'')) SET @CurrentDatabaseFileName = REPLACE(@CurrentDatabaseFileName,'{ClusterName}',ISNULL(@Cluster,'')) @@ -5156,7 +5154,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 12:39:41 //-- + --// Version: 2026-08-23 14:14:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7203,7 +7201,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 12:39:41 //-- + --// Version: 2026-08-23 14:14:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 7889fb1a..cc50731f 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-23 12:39:41 +Version: 2026-08-23 14:14:17 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 12:39:41 //-- + --// Version: 2026-08-23 14:14:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 12:39:41 //-- + --// Version: 2026-08-23 14:14:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2441,7 +2441,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 12:39:41 //-- + --// Version: 2026-08-23 14:14:17 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 51b29522..254bed82 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -9e9f725972f82497a13570259fd333e5d70732134a9aaa0509d9c726bcc0c8a2 CommandExecute.sql +fc4979e7b4906dd379185cc1a8ee98a4bb16aa016af252076d35df215b5ecc46 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -8e3bc4ffa4515a809638a883535633e5aadce72de100c03ae800e149c931d46f DatabaseBackup.sql -aa32ffee55c30ab2a5e8266ab8c2ba34c207ce2e0d6b48b7c0b14348dd7efefe DatabaseIntegrityCheck.sql -1db2fd5f28c5d3da2bd04a402b9ac61287a9a4352de3886c2d61ff3c69a41466 IndexOptimize.sql -cca8c5162e9a819af6f9e9e1d966cdb8e7f8dfb136a5ae0481ee7df9405b1e3b MaintenanceSolution.sql -ac2fc1a8723b818cf72eb2fe7df50e70b8ffef1b143658a451fa2a4685d9edfe MaintenanceSolutionAzureSQLDatabase.sql +6a4ef27d5f68a358113617fbb3e61e0fce21a61770f47a6e980b745f2e1400ce DatabaseBackup.sql +2e45eee0110e541a4c02cd6f95e179b66611ddda469be91a19333d8b89071119 DatabaseIntegrityCheck.sql +1949a30b8dff3825a1f062f2da49de4c4e8a3d84e612d1f6c800c46db6bf4534 IndexOptimize.sql +5af0311874383e2a449929f7b653bddcbddca7fefc9f865fd2f7e8ae59523a1b MaintenanceSolution.sql +599001e46ee664de76cd28b9f3f63e896e25f8aa910ec5b59ebb9b10754d14d9 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From 7938895f3d29c5d373788752af31ad97b4064ec7 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 23 Aug 2026 14:34:51 +0200 Subject: [PATCH 176/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 4 ++-- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 ++++++------ MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 079b8009..153d3f96 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-23 14:14:17 //-- + --// Version: 2026-08-23 14:34:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index f139f5d6..6ec9fbea 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:14:17 //-- + --// Version: 2026-08-23 14:34:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1331,7 +1331,7 @@ BEGIN IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to URL. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) END IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index b7311eb3..c0f75919 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:14:17 //-- + --// Version: 2026-08-23 14:34:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 09b2c9e8..3a747d56 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:14:17 //-- + --// Version: 2026-08-23 14:34:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 64634e9f..53fd2f08 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: 2026-08-23 14:14:17 +Version: 2026-08-23 14:34:11 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:14:17 //-- + --// Version: 2026-08-23 14:34:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:14:17 //-- + --// Version: 2026-08-23 14:34:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1730,7 +1730,7 @@ BEGIN IF @CleanupTime IS NOT NULL AND @URL IS NOT NULL BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported on Azure Blob Storage. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) + VALUES('The value for the parameter @CleanupTime is not supported. Cleanup is not supported when backing up to URL. See https://ola.hallengren.com/sql-server-backup.html#CleanupTime.', 16, 1) END IF @CleanupTime IS NOT NULL AND EXISTS(SELECT * FROM @Directories WHERE DirectoryPath = 'NUL') @@ -5154,7 +5154,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:14:17 //-- + --// Version: 2026-08-23 14:34:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7201,7 +7201,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:14:17 //-- + --// Version: 2026-08-23 14:34:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index cc50731f..7922f7d0 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-23 14:14:17 +Version: 2026-08-23 14:34:11 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:14:17 //-- + --// Version: 2026-08-23 14:34:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:14:17 //-- + --// Version: 2026-08-23 14:34:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2441,7 +2441,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:14:17 //-- + --// Version: 2026-08-23 14:34:11 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index 254bed82..bd375617 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -fc4979e7b4906dd379185cc1a8ee98a4bb16aa016af252076d35df215b5ecc46 CommandExecute.sql +aa13dfbf83ddeebd24453b798e355fcb7a65021a8da873f779aa031c6c043934 CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -6a4ef27d5f68a358113617fbb3e61e0fce21a61770f47a6e980b745f2e1400ce DatabaseBackup.sql -2e45eee0110e541a4c02cd6f95e179b66611ddda469be91a19333d8b89071119 DatabaseIntegrityCheck.sql -1949a30b8dff3825a1f062f2da49de4c4e8a3d84e612d1f6c800c46db6bf4534 IndexOptimize.sql -5af0311874383e2a449929f7b653bddcbddca7fefc9f865fd2f7e8ae59523a1b MaintenanceSolution.sql -599001e46ee664de76cd28b9f3f63e896e25f8aa910ec5b59ebb9b10754d14d9 MaintenanceSolutionAzureSQLDatabase.sql +7d4f58507a4aba6057ef198b987a07e61b897bbc213c35b1522f698b65d32852 DatabaseBackup.sql +9f1e252d8dbd261e5f463563146971bbea5687911907c6e31f03d534fcaabd16 DatabaseIntegrityCheck.sql +ed2871611d6d6da6fac423e75d9548ce54e797aa1e4aec1e9d71bc5071fea08d IndexOptimize.sql +d313e1cc118b85fb7f89773a79846c3c157935469f57bc133cf1c46f6d240886 MaintenanceSolution.sql +0bff1d47881f380911e3a2269e8f5418ce0145baa9be503563eb1f8603ed45a5 MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql From c83055a139a5a49bdf847629ee9bb7efdbdc92d5 Mon Sep 17 00:00:00 2001 From: Ola Hallengren Date: Sun, 23 Aug 2026 14:47:25 +0200 Subject: [PATCH 177/177] Add files via upload --- CommandExecute.sql | 2 +- DatabaseBackup.sql | 4 ++-- DatabaseIntegrityCheck.sql | 2 +- IndexOptimize.sql | 2 +- MaintenanceSolution.sql | 12 ++++++------ MaintenanceSolutionAzureSQLDatabase.sql | 8 ++++---- SHA256SUMS.txt | 12 ++++++------ 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/CommandExecute.sql b/CommandExecute.sql index 153d3f96..494eb3b6 100644 --- a/CommandExecute.sql +++ b/CommandExecute.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: 2026-08-23 14:34:11 //-- + --// Version: 2026-08-23 14:46:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/DatabaseBackup.sql b/DatabaseBackup.sql index 6ec9fbea..dc6fafef 100644 --- a/DatabaseBackup.sql +++ b/DatabaseBackup.sql @@ -94,7 +94,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:34:11 //-- + --// Version: 2026-08-23 14:46:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -998,7 +998,7 @@ BEGIN IF @MirrorDirectory IS NOT NULL AND @EngineEdition = 8 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorDirectory is not supported. Mirrored backup is not supported on Azure SQL Managed Instance. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) + VALUES('The parameter @MirrorDirectory is not supported on Azure SQL Managed Instance. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END IF @MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' diff --git a/DatabaseIntegrityCheck.sql b/DatabaseIntegrityCheck.sql index c0f75919..5a084a93 100644 --- a/DatabaseIntegrityCheck.sql +++ b/DatabaseIntegrityCheck.sql @@ -40,7 +40,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:34:11 //-- + --// Version: 2026-08-23 14:46:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/IndexOptimize.sql b/IndexOptimize.sql index 3a747d56..f21c945b 100644 --- a/IndexOptimize.sql +++ b/IndexOptimize.sql @@ -56,7 +56,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:34:11 //-- + --// Version: 2026-08-23 14:46:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolution.sql b/MaintenanceSolution.sql index 53fd2f08..a03abe0f 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: 2026-08-23 14:34:11 +Version: 2026-08-23 14:46:45 You can contact me by e-mail at ola@hallengren.com. @@ -133,7 +133,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:34:11 //-- + --// Version: 2026-08-23 14:46:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -493,7 +493,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:34:11 //-- + --// Version: 2026-08-23 14:46:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -1397,7 +1397,7 @@ BEGIN IF @MirrorDirectory IS NOT NULL AND @EngineEdition = 8 BEGIN INSERT INTO @Errors ([Message], Severity, [State]) - VALUES('The value for the parameter @MirrorDirectory is not supported. Mirrored backup is not supported on Azure SQL Managed Instance. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) + VALUES('The parameter @MirrorDirectory is not supported on Azure SQL Managed Instance. See https://ola.hallengren.com/sql-server-backup.html#MirrorDirectory.', 16, 1) END IF @MirrorDirectory IS NOT NULL AND @BackupSoftware = 'DATA_DOMAIN_BOOST' @@ -5154,7 +5154,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:34:11 //-- + --// Version: 2026-08-23 14:46:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -7201,7 +7201,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:34:11 //-- + --// Version: 2026-08-23 14:46:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/MaintenanceSolutionAzureSQLDatabase.sql b/MaintenanceSolutionAzureSQLDatabase.sql index 7922f7d0..2477f0b6 100644 --- a/MaintenanceSolutionAzureSQLDatabase.sql +++ b/MaintenanceSolutionAzureSQLDatabase.sql @@ -9,7 +9,7 @@ License: https://ola.hallengren.com/license.html GitHub: https://github.com/olahallengren/sql-server-maintenance-solution -Version: 2026-08-23 14:34:11 +Version: 2026-08-23 14:46:45 You can contact me by e-mail at ola@hallengren.com. @@ -88,7 +88,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:34:11 //-- + --// Version: 2026-08-23 14:46:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -394,7 +394,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:34:11 //-- + --// Version: 2026-08-23 14:46:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON @@ -2441,7 +2441,7 @@ BEGIN --// Source: https://ola.hallengren.com //-- --// License: https://ola.hallengren.com/license.html //-- --// GitHub: https://github.com/olahallengren/sql-server-maintenance-solution //-- - --// Version: 2026-08-23 14:34:11 //-- + --// Version: 2026-08-23 14:46:45 //-- ---------------------------------------------------------------------------------------------------- SET NOCOUNT ON diff --git a/SHA256SUMS.txt b/SHA256SUMS.txt index bd375617..28c96e64 100644 --- a/SHA256SUMS.txt +++ b/SHA256SUMS.txt @@ -1,9 +1,9 @@ -aa13dfbf83ddeebd24453b798e355fcb7a65021a8da873f779aa031c6c043934 CommandExecute.sql +89c96d0a900c8d8d172b021d8d34b0f7c8a2c8e694891b8a201b7229533237bc CommandExecute.sql 7a508fa7ed562ec5ee09d4f587f7f2a87f7a4eb3c57450602ee99cdeb4e18b31 CommandLog.sql -7d4f58507a4aba6057ef198b987a07e61b897bbc213c35b1522f698b65d32852 DatabaseBackup.sql -9f1e252d8dbd261e5f463563146971bbea5687911907c6e31f03d534fcaabd16 DatabaseIntegrityCheck.sql -ed2871611d6d6da6fac423e75d9548ce54e797aa1e4aec1e9d71bc5071fea08d IndexOptimize.sql -d313e1cc118b85fb7f89773a79846c3c157935469f57bc133cf1c46f6d240886 MaintenanceSolution.sql -0bff1d47881f380911e3a2269e8f5418ce0145baa9be503563eb1f8603ed45a5 MaintenanceSolutionAzureSQLDatabase.sql +f3acadfd302b9af135b5d6b09d732eb68509c2eab08adf26377e1a7d162cdde6 DatabaseBackup.sql +f96df950a9b6dd9e63c18224641e8f8486802119090d0f582e4dfaa643874ea3 DatabaseIntegrityCheck.sql +cbef7d1c82d8e84b08a05df8aec5d5502ddef7cd091e3fc4836076ddad67bbeb IndexOptimize.sql +e9ef6b051bfbadddb1b105054e07e424b0267337b248012e25256c3f0a00a2f3 MaintenanceSolution.sql +8ce92c06224c0ed7fce4e67598d5f93179f423645d9e61e72685a65fdb49162b MaintenanceSolutionAzureSQLDatabase.sql c30c3b986cc53efe75420e073af5ae9f0830c8f5b0dd1989649e249533588308 Queue.sql 8e61a33a6b6755ceae483968d8dedea87da3f82534dc37fba4786e9fbe9c1ec9 QueueDatabase.sql