【问题标题】:How to get substring index in OracleOracle中如何获取子字符串索引
【发布时间】:2018-05-17 07:56:32
【问题描述】:

我的数据库 (Oracle) 中有以下字段

Jayson,1990,3,july

我想在这里获取所有值。 解决办法是什么?

【问题讨论】:

标签: sql database oracle function oracle11g


【解决方案1】:
 SELECT CASE WHEN rn = 1 THEN 'Name: '
                      WHEN rn =2 THEN 'Year: '
                      WHEN rn = 3 THEN 'Day: '
                      WHEN rn = 4 THEN 'Month: ' END || result "Results"
                      FROM
 (
 WITH TEST (col) AS
 (SELECT 'Jayson,1990,3,july' FROM dual)
 SELECT REGEXP_SUBSTR(col, '[^,]+', 1, LEVEL) result, ROWNUM rn
FROM TEST
connect BY LEVEL <= REGEXP_COUNT(col, ',') + 1
);

【讨论】:

    【解决方案2】:

    抱歉描述不好。 我想首先将名字作为 FirstName ,然后将日期作为 Date ,然后将日期作为 Day 。所以我想每次一行都返回我。我将执行 4 次以检索所有结果

    结果:

    Name:
    Jayson
    
    Date:
     1990
    
    Day:
    3
    

    【讨论】:

      【解决方案3】:

      我想在这里获取所有值

      “这里”在哪里?

      大概是这样的吧?

      SQL> with test (col) as
        2    (select 'Jayson,1990,3,july' from dual)
        3  select regexp_substr(col, '[^,]+', 1, level) result
        4  from test
        5  connect by level <= regexp_count(col, ',') + 1;
      
      RESULT
      ------------------
      Jayson
      1990
      3
      july
      
      SQL>
      

      [编辑,看到评论后]

      两个简单选项:一个是使用REGEXP_SUBSTR,另一个是使用传统的SUBSTR + INSTR组合:

      SQL> with test (col) as
        2    (select 'Jayson,1990,3,july' from dual)
        3  select
        4    regexp_substr(col, '\w+', 1, 1) name,
        5    regexp_substr(col, '\w+', 1, 2) year,
        6    regexp_substr(col, '\w+', 1, 3) day,
        7    regexp_substr(col, '\w+', 1, 1) month,
        8    --
        9    substr(col, 1, instr(col, ',', 1, 1) - 1) name_2,
       10    substr(col, instr(col, ',', 1, 1) + 1, instr(col, ',', 1, 2) - instr(col, ',', 1, 1) - 1) year_2,
       11    substr(col, instr(col, ',', 1, 2) + 1, instr(col, ',', 1, 3) - instr(col, ',', 1, 2) - 1) day_2,
       12    substr(col, instr(col, ',', 1, 3) + 1) month_2
       13  from test;
      
      NAME   YEAR D MONTH  NAME_2 YEAR D MONT
      ------ ---- - ------ ------ ---- - ----
      Jayson 1990 3 Jayson Jayson 1990 3 july
      
      SQL>
      

      【讨论】:

      • 抱歉描述不正确。我想首先将名字设为 FirstName ,然后将日期设为 Date ,然后将日期设为 Day RESULT: Name: Jayson Date: 1990 Day: 3
      • 我已经修改了我的消息;看看吧。
      猜你喜欢
      • 2011-11-21
      • 1970-01-01
      • 2015-06-30
      • 2019-07-22
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      相关资源
      最近更新 更多