使用CASE时如何不显示NULL行?

时间:2016-11-04 21:46:32

标签: sql case

以下是示例代码:

select i.computerguid, i.logfile_enabled, i.logfile_logExtFileFlags
,Case 
    When    
        CHARINDEX('Date'    , i.logfile_logExtFileFlags) = 0 or
        CHARINDEX('Time'    , i.logfile_logExtFileFlags) = 0 or
        CHARINDEX('ClientIP', i.logfile_logExtFileFlags) = 0                
        Then 'Need these W3SVC fields enabled by default: Date, Time, ClientIP' 
    End as 'Reason'
,Case When i.logfile_enabled = 'true' Then 'Enabled the IIS log fields (via IIS MMC console) for site: ' + i.sitename End as 'Remediation'
from aspr_iissite i inner join aspr_root r on r.computerguid = i.computerguid 
where i.logfile_enabled = 'true'

这是一个截屏,我不想在' Reason'一片空白: enter image description here

谢谢

1 个答案:

答案 0 :(得分:0)

在您的情况下,最简单的方法是使用子查询:

select *
from (select i.computerguid, i.logfile_enabled, i.logfile_logExtFileFlags,
             (Case When CHARINDEX('Date'    , i.logfile_logExtFileFlags) = 0 or
                        CHARINDEX('Time'    , i.logfile_logExtFileFlags) = 0 or
                        CHARINDEX('ClientIP', i.logfile_logExtFileFlags) = 0                
                   Then 'Need these W3SVC fields enabled by default: Date, Time, ClientIP' 
              End) as Reason,
             (Case When i.logfile_enabled = 'true'
                   Then 'Enabled the IIS log fields (via IIS MMC console) for site: ' + i.sitename
              End) as Remediation
      from aspr_iissite i inner join
           aspr_root r
           on r.computerguid = i.computerguid 
      where i.logfile_enabled = 'true'
     ) ir
where Reason is not null;

可以重复case语句中的条件,但这会使代码更难修改和维护。

两个注释:

  • 我认为使用like更容易遵循条件逻辑:i.logfile_logExtFileFlags不像'%Date%'`。这是标准的SQL。
  • 仅对字符串和日期常量使用单引号。不要将它们用于列别名。