在 PowerShell 中如何解决 DataSet.Fill 中的异常?

In PowerShell how to troubleshoot exception in DataSet.Fill?

我正在使用我在 SO 上找到的函数从 SQL 服务器检索数据并生成 XML。

function Invoke-SQL {
    param(
        [string] $sqlCommand = $(throw "Please specify a query.")
      )

    $connectionString = "Data Source=$server;Initial Catalog=$database;user id=$uid;password=$pwd"

    $connection = new-object system.data.SqlClient.SQLConnection($connectionString)
    $command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
    $connection.Open()

    $adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
    $dataset = New-Object System.Data.DataSet
    $adapter.Fill($dataSet) | Out-Null

    $connection.Close()
    $tableOutput = $dataSet.Tables

    foreach($row in $tableOutput) {
        $xml  = $row | ConvertTo-Xml -NoTypeInformation -Depth 1
        $xml.InnerXML
    }
}

它大部分时间都有效,但偶尔,来自同一数据库的完全相同的 SELECT(范围除外)和 table 会抛出以下异常:

Exception calling "Fill" with "1" argument(s): "Incorrect syntax near '>'."
At DBTest.ps1:22 char:18
+     $adapter.Fill <<<< ($dataSet) | Out-Null
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

如何调试哪些行 and/or 哪些数据会导致 Fill 方法中断?

根据评论,它是 SQL 命令本身。当您生成 SQL 命令时,请确保 每个 变量都经过验证和完整性检查。正如一些评论所建议的那样,日志记录 查询可以帮助进行故障排除。