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

时间:2017-08-03 00:13:23

标签: powershell powershell-v2.0

我使用我在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(范围除外)会抛出以下异常:

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

如何调试哪些行和/或哪些数据使Fill方法中断?

1 个答案:

答案 0 :(得分:0)

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