在Oracle的CASE / THEN中使用LIKE?

时间:2012-02-21 10:54:10

标签: sql oracle

我有这部分代码

WHERE p.id = m.id AND (
      CASE
        WHEN (c.match_text IS NOT NULL)
        THEN (
          (lower(p.station) LIKE '%'||c.match_text||'%')
          OR
          (
            (lower(p.station) LIKE '%sealed in%')
            AND
            (lower(p.affected_units) LIKE '%'||c.match_text||'%')
          )
        )
        WHEN(u.name LIKE '%Memory%')
        THEN (
          (lower(p.affected_fuels) LIKE '%nuclear%')
          AND

我在这里得到LIKE错误(更低(p.station)LIKE'%'|| c.match_text ||'%')!!

为什么会这样?

我认为这种方法可以解决问题:

WHEN (c.match_text IS NOT NULL)
THEN (
  CASE WHEN
    (lower(p.station) LIKE '%'||c.match_text||'%')
    OR
    (
      (lower(p.station) LIKE '%sealed in%')
      AND
      (lower(p.affected_units) LIKE '%'||c.match_text||'%')
    )
    THEN true
    ELSE false
    END
)

由于

1 个答案:

答案 0 :(得分:6)

CASE()基本上是一个翻译器:它返回一组给定条件的值。您遇到的问题是您试图强制它返回BOOLEAN值。这不起作用,因为BOOLEAN不是有效的SQL数据类型。

所以我认为你必须将你的逻辑实现为嵌套的AND / OR子句。它有点粗糙但并不比你原来的陈述复杂得多。像这样:

WHERE p.id = m.id 
AND (  
        ( c.match_text IS NOT NULL
         AND ( lower(p.station) LIKE '%'||c.match_text||'%'
              OR ( lower(p.station) LIKE '%sealed in%'
                    AND   lower(p.affected_units) LIKE '%'||c.match_text||'%'
                 )           
              ) 
         )        
     OR (u.name LIKE '%Memory%'
        AND lower(p.affected_fuels) LIKE '%nuclear%'
        AND ...