我需要一种方法来自动将聚簇索引移动到一个文件组中: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
这应该做的伎俩:
$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 .\new.sql
(?smi)
告诉replace语句匹配多行(m)并包括换行符和忽略大小写(i)。 (.*?)
包括任何内容,包括换行符(因此(?smi)
),但不贪婪(?
)。