2014-06-20 45 views
2

我一直試圖找出如何扭轉結果的路徑。假設結果路徑是abc/def/ghi,所以我需要將其反轉,以便將結果讀作「ghi/def/abc」。SQL扭轉路徑(例如,ABC/DEF/GHI到GHI/DEF/ABC)

...我已經尋找這一點,有一個解決方案由文森特(Reverse in Oracle this path z/y/x to x/y/z)。

然而,當我試圖做同樣的,我得到一個錯誤「的說法‘0’超出範圍」。

下面是我所做的:

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

    PL/SQL procedure successfully completed 
    path 

    a/b/c/def 

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

    SUB_PATH RK 

    a 1 b 2 c 3 def 4 
    path 

a/b/c/def 

    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; 

    ORA-01428: argument '0' is out of range 
    path 

a/b/c/def 

我試過,但有一個很難弄清楚這個錯誤的原因。一旦我能夠理解,那麼也許我可以使用這個查詢來生成反向路徑。僅供參考,REVERSE功能將不起作用,因爲它只反轉不是所需結果的字符。

任何幫助或提示是非常讚賞。非常感謝!!

+0

的小提琴爲我工作:http://sqlfiddle.com /#!4/6023b/3 – Joe

回答

0

@Joe感謝很多! 雖然我無法找出解決方案,但SQL小提琴幫助我找到了答案,但下面的查詢提供了我需要的結果。

SELECT MAX(sys_connect_by_path(sub_path, '/')) reversed_path 
FROM 
(SELECT regexp_substr(:path, '[^/]+', 1, ROWNUM) sub_path, 
ROWNUM rk FROM duh 
CONNECT BY LEVEL <= length(regexp_replace(:path, '[^/]', '')) + 1) 
CONNECT BY PRIOR rk = rk + 1 
0

@ user3761113

嘗試此查詢,

SELECT REGEXP_SUBSTR(PATH,'[^/]+',1,4) || '/' || REGEXP_SUBSTR(PATH,'[^/]+',1,3) || '/' || REGEXP_SUBSTR(PATH,'[^/]+',1,2) || '/' || REGEXP_SUBSTR(PATH,'[^/]+',1,1) "Reverse of Path" 
    FROM (SELECT 'a/bc/def/ghij' PATH FROM DUAL); 

這將做到這一點我想:-)