首页 > 解决方案 > SQL 获取字符之间或字符串结尾的字符串

问题描述

我正在尝试获取字符两个字符之间的字符串以及字符串的结尾,如下所示

输入:

Id=3117;GrpType=UPDATE_116;Status=X

我需要的输出如下:

3117
UPDATE_116
X

我正在使用下面的查询,但没有获取确切的结果

SELECT regexp_substr('Id=3117;GrpType=UPDATE_116;Status=X', '.*[^Id=]+') FROM DUAL;

SELECT regexp_substr('Id=3117;GrpType=UPDATE_116;Status=X', '.*[^GrpType=]+') FROM DUAL;

SELECT regexp_substr('Id=3117;GrpType=UPDATE_116;Status=X', '.*[^Status=]+') FROM DUAL;

标签: sqloraclesplit

解决方案


为什么要使用正则表达式;substr+instr做得很好

SQL> with test (col) as
  2    (select 'Id=3117;GrpType=UPDATE_116;Status=X' from dual)
  3  select substr(col, instr(col, '=', 1, 1) + 1,
  4                     instr(col, ';', 1, 1) - instr(col, '=', 1, 1) - 1
  5               ) id,
  6         substr(col, instr(col, '=', 1, 2) + 1,
  7                     instr(col, ';', 1, 2) - instr(col, '=', 1, 2) - 1
  8               ) GrpType,
  9         substr(col, instr(col, '=', 1, 3) + 1) status
 10  from test;

ID   GRPTYPE    STATUS
---- ---------- ----------
3117 UPDATE_116 X

SQL>

或者,正则表达式:

SQL> with test (col) as
  2    (select 'Id=3117;GrpType=UPDATE_116;Status=X' from dual)
  3  select ltrim(regexp_substr(col, '=\w+', 1, level), '=') result
  4  from test
  5  connect by level <= regexp_count(col, '=');

RESULT
-----------------------------------
3117
UPDATE_116
X

SQL>

推荐阅读