索引优化脚本中的过滤模式

Mar*_*Joe 3 sql-server ola-hallengren index-maintenance

是否可以使用 Ola 的脚本进行索引优化并过滤掉特定的模式?

Tom*_*m V 7

是的,如果您查看文档,您会发现可以使用该@indexes参数来指定要对哪些索引进行碎片整理。您可以%在对象名称中使用通配符,并且可以使用前缀-来排除索引。

使用此信息,您要使用的语法是@indexes = 'ALL_INDEXES, -databasename.excludedschema.%',或者@indexes = 'ALL_INDEXES, -%.excludedschema.%'如果您要排除所有数据库中的架构。

您可以在下面找到记录此内容的再现:

首先创建一个包含 2 个碎片表的数据库,一个在dbo架构中,一个在我称为Exclusion. 两者都应该分散到 99% 左右。

USE [master];
GO

CREATE DATABASE [196090];
GO
USE [196090];
GO

SET NOCOUNT ON;
GO

-- Create a table in dbo schema
CREATE TABLE [ProdTable] (
    [c1] INT,
    [c2] CHAR (5000) DEFAULT 'production');
CREATE CLUSTERED INDEX [prod_cl] ON [ProdTable] ([c1]);
GO

-- Fill with random integers to create fragmentation
INSERT INTO [ProdTable] (c1, c2) VALUES  (CRYPT_GEN_RANDOM(8000), 'filler');
GO 12800

-- Check the fragmentation of the production table
SELECT
    [avg_fragmentation_in_percent]
FROM sys.dm_db_index_physical_stats (
    DB_ID (N'196090'), OBJECT_ID (N'ProdTable'), 1, NULL, 'LIMITED');
GO

-- Create a schema to exclude from the rebuild
CREATE SCHEMA Exclusion;
GO

-- Fill with random integers to create fragmentation
CREATE TABLE [Exclusion].[ProdTableExclude] (
    [c1] INT,
    [c2] CHAR (5000) DEFAULT 'production');
CREATE CLUSTERED INDEX [prod_cl] ON [Exclusion].[ProdTableExclude] ([c1]);
GO

INSERT INTO [Exclusion].[ProdTableExclude] VALUES  (CRYPT_GEN_RANDOM(8000), 'filler');
GO 12800

-- Check the fragmentation of the production table
SELECT
    [avg_fragmentation_in_percent]
FROM sys.dm_db_index_physical_stats (
    DB_ID (N'196090'), OBJECT_ID (N'Exclusion.ProdTableExclude'), 1, NULL, 'LIMITED');
GO
Run Code Online (Sandbox Code Playgroud)

然后这样运行Ola的索引维护:

EXECUTE dbo.IndexOptimize
@Databases = '196090',
@indexes = 'ALL_INDEXES, -196090.Exclusion.%' 
Run Code Online (Sandbox Code Playgroud)

你会注意到脚本将跳过模式,留下一个索引碎片。