如何在CASE语句中使用REGEXP_LIKE?

时间:2013-10-21 23:04:38

标签: sql regex oracle11g case

我想在我的CASE语句中使用REGEXP_LIKE

2个问题

  1. 如何让REGEXP_LIKE在此CASE语句中工作? 我收到以下错误消息 ORA-00904: "TRUE": invalid identifier

  2. Re regex,为什么select '12345678' from dual查询会返回1

  3. 正则表达式规则

    0到6位,后跟0或1个小数点,后跟0到6位数。

    with expression_row as 
    (select 'zzzz'     as expression from dual union all
    select '12345678' as expression from dual union all
    select '12.33333' as expression from dual union all
    select '.222222'  as expression from dual)
    select 
    expression,
           case regexp_like( expression, '^\d{0,6}(\.{0,1}\d{0,6})$') 
          -- [0-6 digits][0-1 decimal][0-6 digits]
           when TRUE then 'Y'
           else 'N'
          end as valid_y_n
        from expression_row; 
    

    所需输出

    zzzz     N
    12345678 N
    12.33333 Y
    .222222  Y
    

    我正在使用此查询验证我的正则表达式模式。

    select 1 as valid from dual 
    where regexp_like( '12345678', '^\d{0,6}\.{0,1}\d{0,6}$');
    

2 个答案:

答案 0 :(得分:6)

1)尝试下面的代码 - 这不是正则表达式错误,而是位于它的位置。在评估表达式时,SQL以与大多数语言不同的方式工作 - 它不返回true,然后将其与其他值进行比较;你需要在预期条件或值的地方放置返回true的条件。

with expression_row as 
(select 'zzzz'     as expression from dual union all
select '12345678' as expression from dual union all
select '12.33333' as expression from dual union all
select '.222222'  as expression from dual)
select 
expression
,case 
   when regexp_like( expression, '^\d{0,6}(\.{0,1}\d{0,6})$')  -- [0-6 digits][0-1 decimal][0-6 digits]
   then 'Y'
   else 'N'
end as valid_y_n
from expression_row; 

2)1是SQL代表TRUE; 0为FALSE。这是因为SQL使用位而不是bools(尽管从逻辑角度来看它们是相同的)。

答案 1 :(得分:0)

改为使用 case when regex_instr(variable, 'regex') <> 0 then ...

with expression_row as 
(select 'zzzz'     as expression from dual union all
select '12345678' as expression from dual union all
select '12.33333' as expression from dual union all
select '.222222'  as expression from dual)
select 
expression,
       case when regexp_instr(expression, '^\d{0,6}(\.{0,1}\d{0,6})$') <> 0 
          then 'Y' 
          else 'N'  
      end as valid_y_n
    from expression_row;