不存在的SQL查询

时间:2016-04-12 00:07:56

标签: sql sql-server reporting-services

我正在制作一份SSRS报告,并希望合并一份我认为无法存在的记录,但希望有人可以证明我错了。我试图找到解决它的方法,但说实话,我并不精通SQL。查询专门用于从SCCM 2012数据库获取数据,用于不是win7企业且没有office 2013的机器记录。问题点我有一个2013因素,当SoftwareFile表没有outlook.exe的记录时特定的机器,因此它不会显示在结果集中。我想找到一种方法来显示它甚至当outlook.exe文件不存在时。

这是我当前的查询,我试图开始工作,但它仍然无法显示当我退出最后一行时出现的机器。

   SELECT Distinguished_Name0, Full_Domain_Name0, User_Name0, Netbios_Name0, OS.Caption0, IP_Addresses0, SystemType0, Model0, SYS.ResourceID,
[Office2013] = CASE 
    WHEN  [FileName] = 'outlook.exe' and left(FileVersion, 2) = '15'     THEN 'TRUE'
    WHEN Not Exists (Select * from v_GS_SoftwareFile where SF.ResourceID = Sys.ResourceID and [FileName] = 'outlook.exe') THEN 'FALSE'
    ELSE 'FALSE'
END

FROM v_R_System SYS 

INNER JOIN v_GS_OPERATING_SYSTEM OS 
ON SYS.ResourceID = OS.ResourceID 
INNER JOIN v_RA_System_IPAddresses IP
ON SYS.ResourceID = IP.ResourceID 
INNER JOIN v_GS_COMPUTER_SYSTEM CO
ON SYS.ResourceID = CO.ResourceID 
INNER JOIN  v_GS_SoftwareFile SF
ON SYS.ResourceID = SF.ResourceID

WHERE sys.Distinguished_Name0 LIKE '%DC=local'
AND sys.Distinguished_Name0 NOT LIKE '%Server%'
AND IP_Addresses0 LIKE '10.0.0.%' 
AND Model0 LIKE '%%'
AND OS.Caption0 <> 'Microsoft Windows 7 Enterprise'
AND (SF.[FileName] = 'outlook.exe' 
OR NOT EXISTS (Select * from v_GS_SoftwareFile where SF.ResourceID = SYS.ResourceID and [FileName] = 'outlook.exe'))

2 个答案:

答案 0 :(得分:0)

I think you want an outer join:

SELECT . . .
FROM v_R_System SYS INNER JOIN
     v_GS_OPERATING_SYSTEM OS 
     ON SYS.ResourceID = OS.ResourceID INNER JOIN
     v_RA_System_IPAddresses IP
     ON SYS.ResourceID = IP.ResourceID INNER JOIN
     v_GS_COMPUTER_SYSTEM CO
     ON SYS.ResourceID = CO.ResourceID LEFT JOIN
     v_GS_SoftwareFile SF
     ON SYS.ResourceID = SF.ResourceID AND
        SF.[FileName] = 'outlook.exe' 
WHERE sys.Distinguished_Name0 LIKE '%DC=local' AND
      sys.Distinguished_Name0 NOT LIKE '%Server%' AND
      IP_Addresses0 LIKE '10.0.0.%' AND
      Model0 LIKE '%%' AND
      OS.Caption0 <> 'Microsoft Windows 7 Enterprise'

答案 1 :(得分:0)

not exists查询无效的原因是因为子查询中的别名SF指的是外部查询的v_GS_SoftwareFile,而不是您的子查询。< / p>

AND (SF.[FileName] = 'outlook.exe' 
OR NOT EXISTS (Select * from v_GS_SoftwareFile where SF.ResourceID = SYS.ResourceID and [FileName] = 'outlook.exe'))
                                                     ^^ this is referring to outer v_GS_SoftwareFile

SF.ResourceID = SYS.ResourceID将始终为true(由于连接条件),因此如果表中至少有一行not exists outlook.exe,则FileName查询将始终返回false }}

您需要在子查询中为表提供另一个别名

AND (SF.[FileName] = 'outlook.exe' 
OR NOT EXISTS (Select * from v_GS_SoftwareFile SF2 where SF2.ResourceID = SYS.ResourceID and [FileName] = 'outlook.exe'))

我可能不理解你的问题。但是,如果目标是向机器显示outlook.exe是否存在,那么为什么不简单地从where子句中删除outlook.exe