Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 43 additions & 34 deletions functions/Format-SqlIndex.ps1
Original file line number Diff line number Diff line change
@@ -1,45 +1,54 @@
function Format-SqlIndex {
[CmdletBinding()]Param(
[object]$Index
,[object]$options
[CmdletBinding()]Param(
[Alias('Index')]
[object]$Indexes
, [object]$options
)
$_NL = "`r`n"
$_TB = "".PadRight(4)

$s = $Index.table_schema
$t = $Index.table_name
$i = $Index.index_name

$CLUSTERED_OR_NOT = switch($Index.type){
1 {"clustered "}
5 {"clustered columnstore "}
6 {"columnstore "}
}
foreach ($Index in $Indexes) {
$s = $Index.table_schema
$t = $Index.table_name
$i = $Index.index_name

$is_columnstore = $Index.type -in (5,6)
$UNIQUE_OR_NOT = ""
$keyCols = ""
$inclCols = ""
$includeBlock = ""

if($Index.is_unique){
$UNIQUE_OR_NOT = "unique "
}
$CLUSTERED_OR_NOT = switch ($Index.type) {
1 {"clustered "}
2 {"nonclustered "}
5 {"clustered columnstore "}
6 {"columnstore "}
}
$is_columnstore = $Index.type -in (5, 6)

$keyCols = ($Index.KeyColumns | Sort-Object -Property key_ordinal).KeyColumnName -join "$_NL$_TB$_TB,"
$inclCols = ($Index.InclColumns).column_name -join "$_NL$_TB$_TB,"
$hasInclCols = (($Index.InclColumns | Measure-Object).Count -gt 0)
if ($Index.is_unique) {
$UNIQUE_OR_NOT = "unique "
}

if($hasInclCols){
$includeBlock = " $_NL$($_TB)include ( $inclCols ) "
}

$createIndexCommand = ""
$createIndexCommand += "create $UNIQUE_OR_NOT$($CLUSTERED_OR_NOT)index $i $_NL on $s.$t "
if(-not $is_columnstore){
$createIndexCommand += "( $keyCols )"
$createIndexCommand += "$includeBlock"
}
if($Index.has_filter){$createIndexCommand += "$($_NL)where $($Index.filter_definition)"}
$createIndexCommand += ";$($_NL)go$_NL"

[PSCustomObject]@{
CreateIndexCommand = $createIndexCommand
$keyCols = ($Index.KeyColumns | Sort-Object -Property key_ordinal).KeyColumnName -join "$_NL$_TB$_TB,"
$inclCols = ($Index.InclColumns).column_name -join "$_NL$_TB$_TB,"
$hasInclCols = (($Index.InclColumns | Measure-Object).Count -gt 0)

if ($hasInclCols) {
$includeBlock = " $_NL$($_TB)include ( $inclCols ) "
}

$createIndexCommand = ""
$createIndexCommand += "create $UNIQUE_OR_NOT$($CLUSTERED_OR_NOT)index $i $_NL on $s.$t "
if (-not $is_columnstore) {
$createIndexCommand += "( $keyCols )"
$createIndexCommand += "$includeBlock"
}
if ($Index.has_filter) {$createIndexCommand += "$($_NL)where $($Index.filter_definition)"}
$createIndexCommand += ";$($_NL)go$_NL"

[PSCustomObject]@{
CreateIndexCommand = $createIndexCommand
inclCols =$inclCols
}
}
}