Skip to content

Instantly share code, notes, and snippets.

@asmorger
Created November 29, 2017 13:58
Show Gist options
  • Save asmorger/99a7bace3ddc33cc8b2e7611764ac339 to your computer and use it in GitHub Desktop.
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
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