一尘不染

在Oracle中将此路径z / y / x反转为x / y / z

sql

我将如何在SELECT查询中反转此路径:

z/y/x

为了

x/y/z

其中/是定界符,并且在一行中可以有许多定界符

ex: select (... z/y/x/w/v/u ...) reversed_path from ...

阅读 266

收藏
2021-03-10

共1个答案

一尘不染

最简单的方法可能是编写一个存储的pl / sql函数,但是可以单独使用SQL(Oracle)来完成。

这将分解子路径中的路径:

SQL> variable path varchar2(4000);
SQL> exec :path := 'a/b/c/def';

PL/SQL procedure successfully completed
SQL> SELECT regexp_substr(:path, '[^/]+', 1, ROWNUM) sub_path, ROWNUM rk
  2    FROM dual
  3  CONNECT BY LEVEL <= length(regexp_replace(:path, '[^/]', '')) + 1;

SUB_P RK
----- --
a      1
b      2
c      3
def    4

然后,我们使用来重构反向路径sys_connect_by_path

SQL> SELECT MAX(sys_connect_by_path(sub_path, '/')) reversed_path
  2    FROM (SELECT regexp_substr(:path, '[^/]+', 1, ROWNUM) sub_path,
  3                 ROWNUM rk
  4             FROM dual
  5           CONNECT BY LEVEL <= length(regexp_replace(:path, '[^/]', '')) + 1)
  6  CONNECT BY PRIOR rk = rk + 1
  7   START WITH rk = length(regexp_replace(:path, '[^/]', '')) + 1;

REVERSED_PATH
-------------
/def/c/b/a
2021-03-10