Created
November 29, 2017 13:58
-
-
Save asmorger/99a7bace3ddc33cc8b2e7611764ac339 to your computer and use it in GitHub Desktop.
Iterate over all Table definitions in a SSDT project and fix the un-named "PRIMARY KEY" declaration and move it to a named constraint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Needs-Updating([string] $content){ | |
if($content -match "PK_" -and $content -match "Id"){ | |
return $false | |
} | |
return $true | |
} | |
function Remove-PrimaryKey([string]$content){ | |
return $content -replace " PRIMARY KEY", "" | |
} | |
function Insert-PrimaryKey([string]$tableName, [string]$content){ | |
$content = $content.TrimEnd("`r`n").TrimEnd(')').TrimEnd("`r`n").TrimEnd(","); | |
#$index = $content.LastIndexOfAny(')') | |
$constraint = ",`r`n`tCONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED ([Id] ASC)`r`n)" -f $tableName | |
#$newContent = $content.Insert($index + 1, $constraint) | |
$newContent = $content + $constraint; | |
return $newContent | |
} | |
$tables = Get-ChildItem . -Filter "*.sql" | |
foreach($table in $tables){ | |
$content = (Get-Content $table) -join "`r`n" | |
$tableName = $table -replace ".sql", "" | |
if(Needs-Updating($content) -eq $true){ | |
$noPkContent = Remove-PrimaryKey $content | |
$newContent = Insert-PrimaryKey $tableName $noPkContent | |
Set-Content -Path $table -Value $newContent -Encoding UTF8 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment