替换++存在SQL的字符串

时间:2017-06-06 09:13:26

标签: sql oracle oracle11g

这与我的previous question

有关

我现在想要做的是在我的值列中,如果有任何++实例将其替换为999。

因此,例如如果我有1+2++3,则应将其更新为1+2+999+3

我如何实现这一目标?

由于

1 个答案:

答案 0 :(得分:0)

Oracle安装程序

CREATE TABLE your_table ( value ) AS
  SELECT NULL     FROM DUAL UNION ALL
  SELECT '1'      FROM DUAL UNION ALL
  SELECT '1+2'    FROM DUAL UNION ALL
  SELECT '1++2'   FROM DUAL UNION ALL
  SELECT '+1'     FROM DUAL UNION ALL
  SELECT '1+'     FROM DUAL UNION ALL
  SELECT '1+2++3' FROM DUAL;

<强>查询

SELECT TRIM( BOTH '+' FROM REPLACE( '+' || value || '+', '++', '+999+' ) )
FROM   your_table

<强>输出

VALUE
---------
999
1
1+2
1+999+2
999+1
1+999
1+2+999+3

如果你可以连续替换多个缺失元素,那么你需要一个更复杂的解决方案:

Oracle安装程序

CREATE TABLE your_table ( value ) AS
  SELECT NULL      FROM DUAL UNION ALL
  SELECT '1'       FROM DUAL UNION ALL
  SELECT '1+2'     FROM DUAL UNION ALL
  SELECT '1++2'    FROM DUAL UNION ALL
  SELECT '+1'      FROM DUAL UNION ALL
  SELECT '1+'      FROM DUAL UNION ALL
  SELECT '1+2++3'  FROM DUAL UNION ALL
  SELECT '1+2+++3' FROM DUAL UNION ALL
  SELECT '+'       FROM DUAL;

<强>查询

SELECT ( SELECT LISTAGG(
                  COALESCE(
                    REGEXP_SUBSTR( t.value, '(.*?)(\+|$)', 1, LEVEL, NULL, 1 ),
                    '999'
                  ),
                  '+'
                ) WITHIN GROUP ( ORDER BY LEVEL )
         FROM   DUAL
         CONNECT BY LEVEL <= REGEXP_COUNT( t.value, '\+' ) + 1
       ) AS value
FROM   your_table t

<强>输出

VALUE
-------------
999
1
1+2
1+999+2
999+1
1+999
1+2+999+3
1+2+999+999+3
999+999