PowerShell执行2个SQL查询并将结果加在一起

时间:2018-09-25 18:51:01

标签: sql sql-server powershell

我需要使用Windows身份验证来查询SQL Server数据库中的表。查询需要提取2个值并将结果相加。我有第一部分。我遇到问题的部分是执行查询并将结果加在一起。任何帮助,将不胜感激。

到目前为止我所拥有的:

    $date = Get-Date
    $d = $date.day
    $m = $date.month
    $y = $date.year

    $ServerName = "SERVERNAME"
    $DatabaseName = "DATABASENAME"

    $Table = "STATSDATA" + $m + "_" + $d + "_" + $y

    $Query1 = "SELECT TOP 1 VAL FROM" + $Table + 
              "WHERE POLLID=16267 ORDER BY TTIME DESC"

    $Query2 = "SELECT TOP 1 VAL FROM" + $Table + 
              "WHERE POLLID=16272 ORDER BY TTIME DESC"

    #Timeout parameters
    $QueryTimeout = 120
    $ConnectionTimeout = 30

    #Action of connecting to the Database and executing the query and 
    returning results if there were any.
    $conn = New-Object System.Data.SqlClient.SQLConnection
    $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerName,$DatabaseName,$ConnectionTimeout

    $conn.ConnectionString = $ConnectionString
    $conn.Open()

对此尚不确定:

    $cmd1 = New-Object system.Data.SqlClient.SqlCommand($Query1, $conn)
    $cmd2 = New-Object system.Data.SqlClient.SqlCommand($Query2, $conn)
    $cmd1.CommandTimeout = $QueryTimeout
    $cmd2.CommandTimeout = $QueryTimeout
    $ds1 = New-Object system.Data.DataSet
    $ds2 = New-Object system.Data.DataSet
    $da1 = New-Object system.Data.SqlClient.SqlDataAdapter($cmd1)
    $da2 = New-Object system.Data.SqlClient.SqlDataAdapter($cmd2)

    [void]$da1.fill($ds1)
    [void]$da2.fill($ds2)
    $conn.Close()

    $ds.Tables

3 个答案:

答案 0 :(得分:2)

严格地说,使用现有代码对问题的回答是:

$ds1.Tables[0].Rows[0].Val + $ds2.Tables[0].Rows[0].Val

成员可能是TableRow,而不是TablesRows。我现在不记得了。我的语法可能并不完全正确,但是实际上这是您必须要做的。您需要引用数据集中的第一个表,然后是表中的第一个行,然后是该行中的第一个列(或Val列)。我想您可以只使用列的名称。


但是,由于每次查询只获取一行中的一列,因此您也可以两次使用SqlCommand.ExecuteScalar()函数:

$cmd1=New-Object system.Data.SqlClient.SqlCommand($Query1,$conn)
$cmd2=New-Object system.Data.SqlClient.SqlCommand($Query2,$conn)
$cmd1.CommandTimeout=$QueryTimeout
$cmd2.CommandTimeout=$QueryTimeout
$val1 = $cmd1.ExecuteScalar()
$val2 = $cmd2.ExecuteScalar()
$val1 + $val2

我个人将使用另一个查询,只需运行一次即可获得两个结果:

$Date = Get-Date

$Query = @'
SELECT SUM(VAL) Val
FROM (
    SELECT VAL,
        ROW_NUMBER() OVER (PARTITION BY POLLID ORDER BY TTIME DESC) RN
    FROM STATSDATA{0:m_d_yyyy}
    WHERE POLLID IN (16267,16272)
) T
WHERE RN = 1
'@ -f $Date

答案 1 :(得分:1)

此查询应执行以下操作:

SELECT SUM(VAL) AS sum_val FROM (
    SELECT TOP 1 VAL FROM <insert table name here> WHERE POLLID=16267 ORDER BY TTIME DESC
    UNION ALL
    SELECT TOP 1 VAL FROM <insert table name here> WHERE POLLID=16272 ORDER BY TTIME DESC
) AS X

答案 2 :(得分:0)

仅执行一个查询,而不是执行两个查询。假设您有两个查询:

@Conditionnals

您可以使用以下语法:

TraceAutoConfiguration

仅运行 $Query1 = "SELECT TOP 1 VAL FROM" + $Table + "WHERE POLLID=16267 ORDER BY TTIME DESC" $Query2 = "SELECT TOP 1 VAL FROM" + $Table + "WHERE POLLID=16272 ORDER BY TTIME DESC"