我有一个执行SQL文件的脚本,并在控制台中打印结果(现在).问题是我需要区分NULL值和Result表中返回的空字符串.
这是查询在Management Studio中返回的内容:
您可以看到它包含字符串,空字符串和NULL值.
这是查询在PowerShell IDE中返回的内容:
NULL和empty之间没有区别.
最后几列也被剪切,只打印了前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
}
最佳答案 我会在SELECT子句中添加另一个计算列(Col006_Description):
SELECT ..., CASE WHEN Col006 IS NULL THEN '(null)' WHEN Col006 = '' THEN '(empty)' ELSE '' END AS Col006_Description, ...