我需要一种方法,可以在创建DDL时自动将聚簇索引移动到一个文件组:ClusteredFilegroup,并将所有非聚簇索引移动到另一个文件组NonClusteredFilegroup。我们有sql publish配置文件,它在每周的部署下面创建类似的脚本。我如何利用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
答案 0 :(得分:3)
这应该可以解决问题:
$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),包括换行(s),并忽略大小写(i)。
(.*?)
包括换行符(因此(?smi)
),但不包括贪婪(?
)。