有人能告诉我为什么下面的代码只返回DataSet中的一行(对于主数据库)而不是服务器上每个数据库的一行?
$SQLConn = New-Object System.data.SqlClient.SqlConnection
$SQLConn.ConnectionString = "Data Source = $SQLServer; Initial Catalog = master;
Integrated Security = True"
$SQLConn.Open()
$query = "exec sp_msForEachDb 'use [?] SELECT TOP 1 [name] FROM sysusers'"
$SQLCmd = New-Object System.Data.Sqlclient.SqlCommand($query, $SQLConn);
$SQLAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SQLAdapter.SelectCommand = $SQLCmd
$DataSet = New-Object System.Data.Dataset
$SQLAdapter.Fill($DataSet) | out-null
ForEach ($row in $DataSet.Tables[0])
{
$Name = $row["name"]
write-host $Name
}
$SQLConn.Close()
答案 0 :(得分:0)
您的代码显示您使用$ dataset.tables的索引位置0。将其更改为$DataSet.Tables
ForEach ($row in $DataSet.Tables[0])
{
$Name = $row["name"]
write-host $Name
}
更改为...
ForEach ($row in $DataSet.Tables)
{
$Name = $row["name"]
write-host $Name
}
答案 1 :(得分:0)
您将返回在结果集中获取多个数据表,但仅显示第一个Tables [0]。试试这个:
$DataSet.Tables | foreach {$_.name}
以下是一些完整且经过测试的代码,用于组合结果集:
$SQLServer = ".\SQL1"
$query = @"
create table #output
(DB varchar(128),
name varchar(128)
)
exec sp_MSforeachdb @command1='USE [?];
insert #output SELECT TOP 1 ''?'' AS ''DB'', [name]
FROM sysusers';
select * from #output
"@
$SQLConn = New-Object System.data.SqlClient.SqlConnection
$SQLConn.ConnectionString = "Data Source = $SQLServer; Initial Catalog = master;
Integrated Security = True"
$SQLConn.Open()
$SQLCmd = New-Object System.Data.Sqlclient.SqlCommand($query, $SQLConn);
$SQLAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SQLAdapter.SelectCommand = $SQLCmd
$DataSet = New-Object System.Data.Dataset
$SQLAdapter.Fill($DataSet) | out-null
$DataSet.Tables[0]
$SQLConn.Close()
答案 2 :(得分:0)
我想我需要做这样的事情,将所有记录转换为一个数据集:
$query = "DECLARE @users TABLE ([name] varchar(100)) INSERT @db_roles
exec sp_msForEachDB 'USE [?] SELECT [name] FROM sysusers'
SELECT [name] FROM @db_roles"