我正在尝试从sql server从两个不同的查询中提取数据,并在我的Powershell ISE中显示结果。无论我尝试什么,第二个数据集都不显示,或者query2中的列被追加到query1的列中,然后显示。
$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 :(得分: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()
答案 1 :(得分:0)
您可以尝试这样的事情:
$SQLSERVER="db_server"
$Database="DB"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection ("Server=$SQLSERVER;Database=$DATABASE;Integrated Security=True")
$SqlConnection.open()
if ($SqlConnection.State -eq 1){
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SQLCmd.Connection = $SQLConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$DataSet = New-Object System.Data.DataSet
}else{
Write-Host "Unable to connect to Database"
Exit
}
$sql = @'
Select * FROM Table_1;
Select * FROM Table_2;
'@
$SqlCmd.CommandText = $sql
$SqlAdapter.SelectCommand = $SqlCmd
$count = $SqlAdapter.Fill($DataSet)
$DataSet.Tables[0] | Export-CSV $file1 -NoTypeInformation
$DataSet.Tables[1] | Export-CSV $file2 -NoTypeInformation