我正在通过Powershell运行查询。我知道通过ssms运行查询有多个结果。为什么变量在Powershell中只有一个结果?
我使用了很多方法来执行此查询,但最终使它运行了,但无法获得查询的所有结果。
[string] $Server= "mochqdb01";
[string] $Database = "MoCApp.Models.Item+ItemDBContext";
[string] $SQLQuery= $("Select smEmail from Items where DateRequested >= dateadd(day,datediff(day,1,GETDATE()),0)");
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$Server;Database=$Database;Integrated Security=True"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SQLQuery
$SqlCmd.Connection = $SqlConnection
$dbname = $SqlCmd.ExecuteScalar()
$SqlConnection.Close()
Write-output "Database is " $dbname
输出: 数据库是 Franziew@marketyyo.com
应该有多个结果。我应该保存到数组中吗?
我实际上想将结果保存为这种格式。
发送至电子邮件-电子邮件“ js@marketyyo.com”,“ mb@marketyyo.com”;这可能吗?
答案 0 :(得分:1)
ExecuteScalar()返回第一个结果集的第一行的第一列。您需要ExecuteReader()。 EG
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$Server;Database=$Database;Integrated Security=True"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SQLQuery
$SqlCmd.Connection = $SqlConnection
$rdr = $SqlCmd.ExecuteReader()
while ($rdr.Read())
{
$smMail = $rdr[0]
write-output "email is $smMail"
}
$rdr.Close()
$SqlConnection.Close()