Created
July 27, 2017 08:18
-
-
Save SQLDBAWithABeard/8ed2e37b122342c93e17c9f7115e6db2 to your computer and use it in GitHub Desktop.
SQL Parsing with Powershell
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
## 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
}
}
}
}