2017-05-31 46 views
0

我試圖從兩個不同的SQL Server查詢中提取數據,並在我的Powershell ISE中顯示結果。不管我嘗試什麼,第二個數據集都不會顯示,或者query2的列被附加到query1的列中,然後顯示。Powershell如何從數據集中清除表結構

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection 
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter 
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand 
$DataSet = New-Object System.Data.DataSet 

$SqlConnection.ConnectionString = "MyConnectionString" 

Write-output `r`r "Query 1" 

$SQLQuery = "SELECT columnset 
       FROM table1;" 

$SqlConnection.Open() 
$SqlCmd.CommandText = $SQLQuery 
$SqlCmd.Connection = $SqlConnection 
$SqlAdapter.SelectCommand = $SqlCmd 
$DataSet = New-Object System.Data.DataSet 
$SqlAdapter.Fill($DataSet) 
$DataSet.Tables[0] 
$SqlConnection.Close() 

Write-output `r`r "Query 2" 

$SQLQuery2 = "SELECT columnset 
       FROM table2;" 

$SqlConnection.Open() 
$SqlCmd.CommandText = $SQLQuery 
$SqlCmd.Connection = $SqlConnection 
$SqlAdapter.SelectCommand = $SqlCmd 
$SqlAdapter.Fill($DataSet) 
$DataSet.Tables[0] 
$SqlConnection.Close() 

如何在數據集之間清除表結構,以便只返回我想要的列?

+0

爲什麼不乾脆在每個查詢之間創建一個新的'DataSet'? –

+0

@Mathias R. Jessen - 我每次嘗試聲明一個新的數據集,但是當我這樣做時,它仍然拒絕在屏幕上顯示數據集。 – Lumpy

+0

它確實顯示第二組的記錄計數只是不會返回數據 – Lumpy

回答

0

嘗試這樣的事情

$SqlConnection = New-Object System.Data.SqlClient.SqlConnectio 
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand 


$SqlConnection.ConnectionString = "MyConnectionString" 

Write-output `r`r "Query 1" 

$SQLQuery = "SELECT columnset FROM table1;" 

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter 
$DataSet = New-Object System.Data.DataSet 
$SqlConnection.Open() 
$SqlCmd.CommandText = $SQLQuery 
$SqlCmd.Connection = $SqlConnection 
$SqlAdapter.SelectCommand = $SqlCmd 
$SqlAdapter.Fill($DataSet) 
$DataSet.Tables[0] 
$SqlConnection.Close() 

Write-output `r`r "Query 2" 

$SQLQuery2 = "SELECT columnset FROM table2;" 

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter 
$DataSet = New-Object System.Data.DataSet 
$SqlConnection.Open() 
$SqlCmd.CommandText = $SQLQuery 
$SqlCmd.Connection = $SqlConnection 
$SqlAdapter.SelectCommand = $SqlCmd 
$DataSet = New-Object System.Data.DataSet 
$SqlAdapter.Fill($DataSet) 
$DataSet.Tables[0] 
$SqlConnection.Close()