【问题标题】:How to get integer from column without using regexp_like如何在不使用 regexp_like 的情况下从列中获取整数
【发布时间】:2021-09-17 02:13:24
【问题描述】:

我在Oracle 中有一个列X,其值类似于“a1b2c3”、“abc”、“1ab”、“123”、“156-346”

如何编写一个只返回 X 的 sql 查询,其中包含 123,456 等纯数值。

我不能使用regexp_like,因为我正在使用10g

【问题讨论】:

    标签: sql oracle oracle11g oracle10g oracle12c


    【解决方案1】:

    这里有两种选择:一种使用正则表达式,另一种使用translate 函数。

    SQL> with test as
      2    (select 'a1b2c3' col from dual union all
      3     select 'abc'        from dual union all
      4     select '1ab'        from dual union all
      5     select '123'        from dual union all
      6     select '156-346'    from dual
      7    )
      8  select col,
      9    regexp_replace(col, '[^[:digit:]]') result,
     10    --
     11    translate(col, '0'|| translate(col, '$0123456789', '$'), '0') result2
     12  from test;
    
    COL     RESULT  RESULT2
    ------- ------- -------
    a1b2c3  123     123
    abc
    1ab     1       1
    123     123     123
    156-346 156346  156346
    
    SQL>
    

    【讨论】:

    • 谢谢。但我不能使用 regexp_replace 并且我 hv 在 where 子句中使用它
    • 不客气。我添加了另一个使用 TRANSLATE 功能的选项。看看有没有帮助。
    • 其实小脚,如果column包含字符串,直接忽略即可。截至目前,如果一列包含 1 而另一列 1abc 则为真。
    • 如果列包含除整数以外的任何内容,它可以给出 null 或 0 吗?
    【解决方案2】:

    当使用translate函数删除所有数字并修剪结果时,纯数字将产生null

    select x
    from test
    where trim(translate(x, '0123456789', '          ')) is null;
    

    确保有 10 个空格作为 translate 的最后一个参数。

    如果x 列可以包含空格,则使用

    select x
    from test
    where trim(translate(replace(x,' ','*'), '0123456789', '          ')) is null;
    

    见:http://sqlfiddle.com/#!4/772dc7d/2/0

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 1970-01-01
      • 2019-08-31
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      • 2014-11-06
      • 2019-09-09
      相关资源
      最近更新 更多