【问题标题】:Using an IIF statement in a where clause在 where 子句中使用 IIF 语句
【发布时间】:2017-11-25 00:28:10
【问题描述】:

我正在尝试使用以下代码向 SQL Server 2014 中的 Where 子句添加多个条件,但出现语法错误。

我已经尝试了一个案例陈述,但根据本网站上的示例无法使其发挥作用。

Where  
iif(ss.DATAAREAID = 'USMF',
 (ss.ITEMGROUPID like 'S%' and  ss.ITEMGROUPID  not like 'SMS%'),
(ss.ITEMGROUPID like 'SW%' and  ss.ITEMGROUPID  like 'SS%')

我确信这是一个快速的解决方案,但我们将不胜感激。

【问题讨论】:

标签: sql sql-server-2014 where-clause


【解决方案1】:

不要使用条件逻辑。只需使用布尔表达式:

Where (ss.DATAAREAID = 'USMF', and ss.ITEMGROUPID like 'S%' and ss.ITEMGROUPID  not like 'SMS%') or
      (ss.DATAAREAID <> 'USMF' and ss.ITEMGROUPID like 'SW%' and ss.ITEMGROUPID  like 'SS%')

注意:iif() 是一个 SQL Server 函数,但引入它是为了向后兼容 MS Access。您应该改用 ANSI 标准的 case 表达式。

您的版本不起作用,因为 SQL Server 不将布尔表达式的结果视为有效值。你需要做这样的事情:

where (case when . . . and . . . then 1
            else 0
       end) = 1

上面没有考虑NULL 值。如果需要,可以轻松添加该条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 2011-09-19
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多