自动在不同的文件组中创建索引,编辑发布配置文件脚本

我需要一种方法来自动将聚集索引移动到一个文件组:ClusteredFilegroup,并在创建DDL时将所有非聚集索引移动到不同的文件组NonClusteredFilegroup。我们有SQL发布配置文件,它在每周部署下面创建类似的脚本。我如何利用PowerShell进行此操作?

我想让PowerShell添加单词 ON [ClusteredFilegroup]每次创建表后

ON [NonClusteredFilegroup]用于每个非聚集索引。

PowerShell应该能够读取原始脚本(testscript.sql),并对其运行文本编辑。

原始脚本:

GO
CREATE TABLE [dbo].[Dim_Product] (
    [DimProductId]        INT            IDENTITY (1, 1) NOT NULL,
    [ProductName]         VARCHAR(64)    NOT NULL,
    [ProductDescription]  VARCHAR(64)    NOT NULL,
    [BeginDate]           DATETIME       NOT NULL,
    [EndDate]             DATETIME       NOT NULL,
    CONSTRAINT [PK_DimProductId] PRIMARY KEY CLUSTERED ([DimProductId] ASC)
);

GO
CREATE NONCLUSTERED INDEX [NCX_Product_ProductName]
    ON [dbo].[Dim_Product]([ProductName] ASC);

GO
CREATE NONCLUSTERED INDEX [NCX_Product_BeginDate]
    ON [dbo].[Dim_Product]([BeginDate] ASC);   


GO
CREATE TABLE [dbo].[Dim_Customer] (
    [DimCustomertId]        INT           IDENTITY (1, 1) NOT NULL,
    [CustomerName]         VARCHAR(64)    NOT NULL,
    [CustomerDescription]  VARCHAR(64)    NOT NULL,
    [BeginDate]           DATETIME        NOT NULL,
    [EndDate]             DATETIME        NOT NULL,
    CONSTRAINT [PK_DimCustomerId] PRIMARY KEY CLUSTERED ([DimCustomerId] ASC)
);

GO
CREATE NONCLUSTERED INDEX [NCX_Customer_CustomerName]
    ON [dbo].[Dim_Customer]([CustomerName] ASC);

GO
CREATE NONCLUSTERED INDEX [NCX_Customer_BeginDate]
    ON [dbo].[Dim_Customer]([BeginDate] ASC);

目标:

CREATE TABLE [dbo].[Dim_Product] (
     [DimProductId]        INT           IDENTITY (1, 1) NOT NULL,
     [ProductName]         VARCHAR(64)   NOT NULL,
     [ProductDescription]  VARCHAR(64)   NOT NULL,
     [BeginDate]           DATETIME      NOT NULL,
     [EndDate]             DATETIME      NOT NULL,
     CONSTRAINT [PK_DimProductId] PRIMARY KEY CLUSTERED ([DimProductId] ASC)
    ) ON [ClusteredFilegroup];

    GO
CREATE NONCLUSTERED INDEX [NCX_Product_ProductName]
     ON [dbo].[Dim_Product]([ProductName] ASC) ON [NonClusteredFilegroup];

我正在尝试研究这些脚本:

Add text to every line in text file using PowerShell

Search a text file for specific word if found copy the entire line to new file in powershell

https://dba.stackexchange.com/questions/229380/automatically-have-nonclustered-indexes-in-a-different-filegroup/229382#229382


解决方案

这应该会起作用:

$sql = Get-Content .org.sql -Raw
$sql = $sql -replace '(?smi)(CREATE TABLE (.*?)));','$1 ) ON [ClusteredFilegroup];'
$sql = $sql -replace '(?smi)(CREATE NONCLUSTERED INDEX (.*?)));','$1) ON [NonClusteredFilegroup];'
$sql | Set-Content -Path .
ew.sql

(?smi)告诉REPLACE语句匹配多行(M),并包括新行和Ignore Case(I)。 (.*?)包括任何内容,包括换行符(因此(?smi)),但不包括贪婪(?)。

相关文章