Is there any powershell syntax that detects sql syntax errors? For e.g. stored procedures , SQL query , functions etc.
Asked
Active
Viewed 1,646 times
-1
-
You are looking for an Online SQL compiler like https://rextester.com/l/sql_server_online_compiler – Vivek Kumar Singh Mar 22 '19 at 07:52
-
Yes . need a syntax validator written in powershell that will validate syntax errors. – Asi Mar 22 '19 at 08:10
-
Which RDBMS are you using? For SQL Server solution, see [earlier a question](https://stackoverflow.com/q/13316328/503046). – vonPryz Mar 22 '19 at 09:41
-
Microsoft sql server – Asi Mar 22 '19 at 09:53
-
You'd need to write an SQL parser for that (regardless of what DBMS you're using), which is clearly *way* beyond the scope of an SO question. – Ansgar Wiechers Mar 22 '19 at 10:12
1 Answers
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
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