gpt4 book ai didi

sql-server - 使用 powershell 处理多个 SQL 结果集

转载 作者:行者123 更新时间:2023-12-03 13:57:32 25 4
gpt4 key购买 nike

我有几个查询用于识别 SQL 数据库中的问题,但我正在尝试在 powershell 脚本中创建,我可以使用它来自动执行此操作。我遇到的问题是,当我调用 SQL 脚本时,有多个结果集,而我的脚本似乎只捕获了第一个集。我想知道我需要做什么来循环查看所有结果。这是只有一些简单选择的代码

$dataSource = 'Server'
$database = "DB"
$sqlcommand = @"
Select TOP 1000 * from tblA;
Select TOP 1000 * from tblB
"@


Function Convert-Dataset
{
Param
(
[Parameter(Mandatory=$true)]
$dataset
)

Begin
{
$return=@()
For($r = 0; $r -lt $dataset.tables[0].rows.Count; $r++)
{
$table= new-object psobject
If($dataset.tables[0].columns.ColumnName.Count -le 1)
{
$colName = [String]$dataset.tables[0].columns.ColumnName
If($dataset.tables[0].rows.Count -eq 1)
{
$colValue = [string]$dataset.tables[0].rows.$colName
}
Else
{
$colValue = [string]$dataset.tables[0].rows[$r].$colName
}
$table | Add-Member -memberType noteproperty -Name $colName -Value $colValue
}
Else{
For($c = 0; $c -lt $dataset.tables[0].columns.ColumnName.Count; $c++)
{
$colName = [String]$dataset.tables[0].columns.ColumnName[$c]
$colValue = [string]$dataset.tables[0].rows[$r][$c]
$table | Add-Member -memberType noteproperty -Name $colName -Value $colValue
}
}
$return +=$table
}
}
End
{
Return $return
}
}

$connectionString = "Data Source=$dataSource; " +
"Integrated Security=True; " +
"Initial Catalog=$database"
$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()
$return=Convert-Dataset -dataset $dataset
$return | Out-GridView

最佳答案

我想到了

$connectionString = "Data Source=$dataSource; " +
"Integrated Security=True; " +
"Initial Catalog=$database"
$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()

ForEach($table in $dataset.Tables)
{
$table |Out-GridView -PassThru
}

关于sql-server - 使用 powershell 处理多个 SQL 结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45088684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com