Powershell不会运行嵌套的SQL查询

时间:2014-10-30 14:38:35

标签: sql-server powershell nested

SQL Server 2012

我有Powershell脚本,可以运行查询和输出到EXCEL

如果我执行以下

$SQL9 = "SELECT *
FROM dbo.Computers
WHERE Date_of_Record = CAST(GETDATE() AS DATE)
AND dbo.Computers.COMPUTER_NAME LIKE '%s001'
AND dbo.Computers.IP_Address LIKE '%.100'
ORDER BY Computer_Name"

$ws = $wb.Worksheets.Item(9)
$ws.name = "GUP"

$qt = $ws.QueryTables.Add("ODBC;DSN=$DSN3;UID=$username;PWD=$password", $ws.Range("A1"), $SQL9)

if ($qt.Refresh()){
    $ws.Activate()
    $ws.Select()
    $excel.Rows.Item(1).HorizontalAlignment = $xlCenter
    $excel.Rows.Item(1).VerticalAlignment = $xlTop
    $excel.Rows.Item("1:1").Font.Name = "Calibri" 
    $excel.Rows.Item("1:1").Font.Size = 11 
    $excel.Rows.Item("1:1").Font.Bold = $true 
 }

它有效

但是如果我使用另一个SQL语句,即

$SQL9 = "SELECT Date_of_Record, Computer_Name, IP_Address, Agent_Version
FROM dbo.Computers
WHERE Computer_Name in (SELECT Computer_Name
                        FROM dbo.Computers
                        GROUP BY Computer_Name
                        HAVING COUNT(DISTINCT Agent_Version) > 1)
AND dbo.Computers.COMPUTER_NAME LIKE '%s001'
AND dbo.Computers.IP_Address LIKE '%.100'
ORDER BY Computer_Name, Date_of_Record"

它不起作用。我在SQL Management Studio中运行此查询,它按预期工作。

我甚至使用了另一个SQL语句并运行了脚本,即

$SQL9 = "SELECT Computer_Name, IP_Address, COUNT(*) AS Number_of_Days_Checked_Past_Month
FROM dbo.Computers
WHERE Date_of_Record > GETDATE() - 30
AND dbo.Computers.COMPUTER_NAME LIKE '%s001'
AND dbo.Computers.IP_Address LIKE '%.100'
Group BY Computer_Name, IP_Address
ORDER BY Number_of_Days_Checked_Past_Month DESC"

它有效。

为什么在我尝试执行

时,powershell脚本会挂起
$SQL9 = "SELECT Date_of_Record, Computer_Name, IP_Address, Agent_Version
FROM dbo.Computers
WHERE Computer_Name in (SELECT Computer_Name
                        FROM dbo.Computers
                        GROUP BY Computer_Name
                        HAVING COUNT(DISTINCT Agent_Version) > 1)
AND dbo.Computers.COMPUTER_NAME LIKE '%s001'
AND dbo.Computers.IP_Address LIKE '%.100'
ORDER BY Computer_Name, Date_of_Record"

是否因为有嵌套SELECT?如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

即使您没有告诉它,我想问题是您使用ODBC从Excel连接到SQL Server。

ODBC不支持嵌套查询。您需要使用不同的方法从Excel访问SQL Server。你可以使用OLE DB驱动程序吗?

您还可以修改查询,以便它不使用子查询(我无法查看如何操作)。您还可以在服务器上创建一个视图,以便excel的查询不会使用子查询。

see this SO answer:您可以在联接中使用子查询,并对已连接的值进行过滤。