Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SQLDBAWithABeard/8ed2e37b122342c93e17c9f7115e6db2 to your computer and use it in GitHub Desktop.
Save SQLDBAWithABeard/8ed2e37b122342c93e17c9f7115e6db2 to your computer and use it in GitHub Desktop.
SQL Parsing with Powershell
## Load assembly
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Management.SqlParser") | Out-Null
$ParseOptions = New-Object Microsoft.SqlServer.Management.SqlParser.Parser.ParseOptions
$ParseOptions.BatchSeparator = 'GO'
## No Errors
$Sql = "Select * from sys.sysdatabases"
$Script = [Microsoft.SqlServer.Management.SqlParser.Parser.Parser]::Parse($SQL, $ParseOptions)
$Script.Errors
## Errors
$Sql = "Select Name from sys.sysdatabases Where Name IN ('DBName)"
$Script = [Microsoft.SqlServer.Management.SqlParser.Parser.Parser]::Parse($SQL, $ParseOptions)
$Script.Errors
@SQLDBAWithABeard
Copy link
Author

SQLDBAWithABeard commented Jul 25, 2018

Describe "Testing SQL" {
Context "Running parser" {
## Load assembly
$Parserdll = 'C:\Program Files\WindowsPowerShell\Modules\dbatools\0.9.188\bin\smo\Microsoft.SqlServer.Management.SqlParser.dll'
[System.Reflection.Assembly]::LoadFile($Parserdll) | Out-Null
$TraceDll = 'C:\Program Files\WindowsPowerShell\Modules\dbatools\0.9.188\bin\smo\Microsoft.SqlServer.Diagnostics.Strace.dll'
[System.Reflection.Assembly]::LoadFile($TraceDll) | Out-Null
$ParseOptions = New-Object Microsoft.SqlServer.Management.SqlParser.Parser.ParseOptions
$ParseOptions.BatchSeparator = 'GO'
$files = Get-ChildItem -Path $Env:Directory -Include *.sql -Recurse ## This variable is set as a TFS Build Process Variable
$files.ForEach{
It "$($Psitem.FullName) Should Parse SQL correctly" {
$filename = $Psitem.FullName
$sql = Get-Content -LiteralPath "$fileName"
$Script = [Microsoft.SqlServer.Management.SqlParser.Parser.Parser]::Parse($SQL, $ParseOptions)
$Script.Errors.Count | Should -Be 0
}
}
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment