2017-07-05 115 views
4

我有一個腳本,用於執行SQL文件並在控制檯(現在)中輸出結果。問題是我需要區分NULL值和Result表中返回的空字符串。執行SQL查詢時在結果表中顯示NULL值

這就是查詢在Management Studio中返回:

enter image description here

你可以看到它包含字符串,空字符串和NULL值。

這是該查詢PowerShell的IDE返回:

enter image description here

有NULL和空之間沒有什麼區別。

另外最後幾列被剪切,只打印前10個。

我該如何解決這個問題?

這裏是我的代碼:

$ConnectionString = "Data Source=...;Initial Catalog=...;User Id=..;Password=.." 
$FolderToSQLFiles = "C:\SQLFilesTestFolder"; 

#function that executes sql queries and return result tables 
function GetSQLresults { 
    Param(
     [Parameter(Mandatory=$True, ValueFromPipelineByPropertyName=$True, Position=0)] $SQLqueryText, # sql query text returned from file 
    ) 

    $objConnection = New-Object System.Data.SqlClient.SqlConnection; 
    $objConnection.ConnectionString = $ConnectionString 

    $objConnection.Open(); 

    $ObjCmd = New-Object System.Data.SqlClient.SqlCommand; 
    $ObjCmd.CommandText = $SQLqueryText; 
    $ObjCmd.Connection = $objConnection; 
    $ObjCmd.CommandTimeout = 0; 

    $objAdapter = New-Object System.Data.SqlClient.SqlDataAdapter; 
    $objAdapter.SelectCommand = $ObjCmd; 
    $objDataSet = New-Object System.Data.DataSet; 

    $objAdapter.Fill($objDataSet); 

    $ResultSets = @(); #adding all result tables to array 

    for ($i=0; $i -lt $objDataSet.Tables.Count; $i++) { 
     $tmpResultTable = $objDataSet.Tables[$i] | Format-Table | Out-String; 
     $ResultSets += $tmpResultTable; 
    } 

    return $ResultSets 

    $query = $null; 

    $objDataSet = $null; 

    $objConnection.Close(); 
    $objConnection = $null; 
} 

Get-ChildItem $FolderToSQLFiles -Filter *.sql | Foreach-Object { 
    $tmpSQLfilePath = $_.FullName #getting the sql file full path 
    $tmpSQLfileContent = (Get-Content $tmpSQLfilePath) -join "`n" #getting the content of the sql 

    GetSQLresults -SQLqueryText $tmpSQLfileContent #passing the sql query to the executing funciton 
} 

回答

0

PowerShell中自動將空值轉換爲輸出空字符串。您需要檢查字段中值的類型並相應地調整輸出/值。

像這樣的東西應該工作:

GetSQLresults ... | 
    Select-Object -Property *,@{n='Col006',e={ 
     if ($_.Col006 -is [DBNull]) {'NULL'} else {$_.Col006} 
    }} -Exclude Col006 
+0

的問題是,我也不知道列名的每張桌子。我執行了很多查詢,它們都有不同的結果表。另外,一個查詢可以有多個結果表。 :/ – Nyagolova

+0

然後,您需要枚舉表,枚舉列,併爲列中的每個值替換類型爲'[DBNull]'的值。我不會爲此提供交鑰匙解決方案。 –

1

我會SELECT條款內。因此添加另一個計算列(Col006_Description):

SELECT ..., CASE WHEN Col006 IS NULL THEN '(null)' WHEN Col006 = '' THEN '(empty)' ELSE '' END AS Col006_Description, ... 
+0

這將是一個簡單的方法,但我不能修改SQL文件。 :/另外如果我可以的話 - 他們中的很多人都會編輯它們。 – Nyagolova