sql-server - Power Shell 将 SQL 查询结果添加到数组或表中
问题描述
我有一个 Power Shell 脚本,它将连接到我的数据库并返回 10 个 ID 和相关代码的列表。运行此脚本时,它会列出 10 个 ID,然后是 10 个代码。我正在尝试将这些值放入一个数组中,以便稍后在脚本中循环浏览它们。
ps1:
clear
#################################################
## Connect to SQL Server Database
#################################################
[string]$serverName = 'Server'
[string]$databaseName = 'Database'
[string]$userName = 'Username'
[string]$password = 'Password'
$connectionString = 'Data Source={0};database={1};User ID={2};Password={3}' -f $serverName,$databaseName,$userName,$password
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection $connectionString
$sqlConnection.Open()
#################################################
## Run SQL Query
#################################################
[string]$sqlCommand = 'SELECT TOP 10 * FROM Table'
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null
#################################################
## Return SQL Query Results
#################################################
$dataSet.tables.id
$dataSet.tables.code
#################################################
## Close SQL Connection
#################################################
$sqlConnection.Close()
目前输出看起来像:
1
2
3
4
5
code1
code2
code3
code4
code5
我试图让输出看起来像:
{
("1","code1"),
("2","code2"),
...
}
或以表格格式返回数据
解决方案
尝试这个 :
$dataSet.tables | Select id, code
也看看Select-Object
推荐阅读
- sql - 如何使用正则表达式清除数据输入错误
- amazon-web-services - NestJs TypeORM 配置使用 AWS 秘密管理器
- python - Pandas 数据框计算
- angular - mat-datePicker 角度 11
- ruby-on-rails - 如何避免使用完整的 yaml 路由进行语言环境翻译?
- python - 使用会话范围 pytest 夹具更新 webdriver 以供类范围夹具使用
- python - 如何让 OpenCV 显示整个相机帧?
- android - 应用程序未构建 apk - MethodHandle.invoke 和 MethodHandle.invokeExact 仅支持从 Android O (--min-api 26) 开始
- firebase - 是否可以使用一个 POST 请求在不同位置添加新节点?
- javascript - 如果设置了 type="module",为什么 childNodes 在 connectedCallback 中返回不同的值?