2017-08-03 16 views
0

私はSOで見つけた関数を使用して、SQLサーバーからデータを取り出してXMLを生成しています。PowerShellでは、DataSet.Fillで例外のトラブルシューティングを行う方法を教えてください。

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メソッドを中断させるのか?

+3

障害発生時に$ sqlCommandとは何ですか?私はまずこれをチェックします。通常、このエラーはSQLコマンドで問題になります。 –

+1

ええ、それは '$ sqlCommand'のSQLエラーです。 https://stackoverflow.com/q/39874629/478656またはhttps://stackoverflow.com/questions/24661805/incorrect-syntax-nearまたはhttps://stackoverflow.com/questions/39300057/incorrect-syntax-nearまたはhttps://stackoverflow.com/questions/40086340/error-in-sql-query-incorrect-syntax-near - 不正なクエリ、壊れたエスケープ、新しいSQLサーバなどの機能の使用 – TessellatingHeckler

+1

クエリが間違って書き込まれるしばしば。私はあなたのparam()の直後に '$ sqlCommand >> c:\ logs \ myquery.log'のような行を入れてみます。そのログファイル内のクエリ(または$ sqlCommand)を見て、それをキャッチできるかどうかを確認します。 – brendan62269

答えて

0

コメントごとに、それはSQLコマンドそのものでした。 SQLコマンドを生成するときは、すべての変数が妥当性検査とサニティチェックを通過するようにしてください。いくつかのコメントが示すように、ログのクエリはトラブルシューティングに役立ちます。

関連する問題