是否有任何Powershell语法可检测sql语法错误?例如存储过程,SQL查询,函数等。
答案 0 :(得分:0)
您可以使用PRASEONLY
或NOEXEC
包装查询,下面是一个示例:
$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
参考:https://stackoverflow.com/a/3276146/3759822
更新:
如果要检查.sql
文件中的查询,请从包含脚本的目录中执行脚本
Get-ChildItem .\*.sql | Select -ExpandProperty FullName | ForEach { $query = (Get-Content -Path $_); Check-Query-Syntax $str }