-1

Is there any powershell syntax that detects sql syntax errors? For e.g. stored procedures , SQL query , functions etc.

Asi
  • 1
  • 4

1 Answers1

2

You can wrap your query with PARSEONLY or NOEXEC, here's an example :

$Server = "SERVER"
$Database = "Database"
$UserId = "USERID"
$Password = "PASSWORD"
$QueryToTest= "SELECT * FROM NO_TABLE !!"

Function Check-Query-Syntax
{
    Param(
        [Parameter(Mandatory = $true)][string]$query
    )
    try
    {
        $sb = New-Object -TypeName "System.Text.StringBuilder"
        [void]$classpath.AppendLine("SET NOEXEC ON;")
        [void]$classpath.AppendLine($query)
        [void]$classpath.AppendLine("SET NOEXEC OFF;")
        $Connection = New-Object System.Data.SQLClient.SQLConnection
        $Connection.ConnectionString = "server='$Server';database='$Database';User Id='$UserId';Password='$Password';trusted_connection=true;"
        $Connection.Open()
        $Command = New-Object System.Data.SQLClient.SQLCommand
        $Command.Connection = $Connection
        $Command.CommandText = $SQLQuery
        $Reader = $Command.ExecuteNonQuery()
        $Connection.Close()
    }
    catch
    {
        Write-Host "Some error"
        throw
    }
}

Check-Query-Syntax $QueryToTest

PARSEONLY NOEXEC

Reference : https://stackoverflow.com/a/3276146/3759822

UPDATE :

If you want to check the queries inside .sql files then execute the script from the directory that contains the scripts

Get-ChildItem .\*.sql | Select -ExpandProperty FullName | ForEach { $query = (Get-Content -Path $_); Check-Query-Syntax $str }
Dylan Watson
  • 2,283
  • 2
  • 20
  • 38
Fourat
  • 2,366
  • 4
  • 38
  • 53
  • Hi appreciate your efforts. Basically m trying to check the errors not through sql servers or anything. I have the sql scripts in my folder . I need it to check each file within the folder. – Asi Mar 22 '19 at 13:49
  • Yes .. thank you for that . Is it not possible without passing the database details etc? Is there any namespace available that will work in a way to display the errors? – Asi Mar 25 '19 at 10:26
  • @aishwaryamurali you need a connection to a SQL Server database server in order to validate a query because it's done on server side. Whats do you mean by "Is there any namespace available that will work in a way to display the errors?" ? – Fourat Mar 25 '19 at 10:29