0

有人能告诉我为什么下面的代码只从 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()
4

3 回答 3

0

我想我需要做这样的事情来将所有记录放入一个数据集中:

 $query = "DECLARE @users TABLE ([name] varchar(100)) INSERT @db_roles 
           exec sp_msForEachDB 'USE [?] SELECT [name] FROM sysusers'
           SELECT [name] FROM @db_roles"
于 2013-03-20T17:24:30.213 回答
0

您将返回结果集中的多个数据表,但仅显示第一个表 [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()
于 2013-03-20T13:06:24.203 回答
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
     }
于 2013-03-19T18:42:29.037 回答