Is there any powershell syntax that detects sql syntax errors? For e.g. stored procedures , SQL query , functions etc.
-
You are looking for an Online SQL compiler like rextester.com/l/sql_server_online_compilerVivek Kumar Singh– Vivek Kumar Singh2019-03-22 07:52:55 +00:00Commented Mar 22, 2019 at 7:52
-
Yes . need a syntax validator written in powershell that will validate syntax errors.Asi– Asi2019-03-22 08:10:57 +00:00Commented Mar 22, 2019 at 8:10
-
Which RDBMS are you using? For SQL Server solution, see earlier a question.vonPryz– vonPryz2019-03-22 09:41:05 +00:00Commented Mar 22, 2019 at 9:41
-
Microsoft sql serverAsi– Asi2019-03-22 09:53:57 +00:00Commented Mar 22, 2019 at 9: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– Ansgar Wiechers2019-03-22 10:12:21 +00:00Commented Mar 22, 2019 at 10:12
Add a comment
|
1 Answer
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 }
3 Comments
Asi
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
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?
Fourat
@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?" ?