About me:Oracle ACE pro,optimistic,passionate and harmonious. Focus on ORACLE,MySQL and other database programming,peformance tuning,db design, j2ee,Linux/AIX,Architecture tech,etc
全部博文(172)
分类: Oracle
2022-04-12 09:55:38
SQL> WITH t AS 2 ( 3 SELECT 1 ID,5 times FROM dual 4 ) 5 SELECT ID FROM t 6 CONNECT BY LEVEL<=times; ID ---------- 1 1 1 1 1 |
1)根据TIMES构造序列,然后关联判断 WITH t AS ( SELECT 1 ID,5 times FROM dual UNION ALL SELECT 2,3 FROM dual ) SELECT ID FROM t, (SELECT LEVEL mlevel FROM dual CONNECT BY LEVEL<=( SELECT MAX(times) FROM t )) tmp WHERE t.times>=tmp.mlevel ORDER BY ID; 2)使用CONNECT BY,但是需要自身与自身递归 因为自身与自身递归,CONNECT BY PRIOR ID=ID会报循环错误,因此为了欺骗ORACLE,我每次递归的条件是没有循环的,增加PRIOR DBMS_RANDOM.VALUE IS NOT NULL,如下: WITH t AS ( SELECT 1 ID,5 times FROM dual UNION ALL SELECT 2,3 FROM dual ) SELECT ID FROM t CONNECT BY PRIOR ID=ID AND LEVEL<=times AND PRIOR DBMS_RANDOM.VALUE IS NOT NULL 结果都是: 1 1 1 1 1 2 2 2 |
SELECT REGEXP_SUBSTR('&str', '[^,]+', 1, LEVEL) AS value_str FROM DUAL CONNECT BY LEVEL <= LENGTH('&str')-LENGTH(REPLACE('&str',',','')) + 1; SELECT SUBSTR (inlist, INSTR (inlist, ',', 1, LEVEL ) + 1, INSTR (inlist, ',', 1, LEVEL+1) - INSTR (inlist, ',', 1, LEVEL) -1 ) AS value_str FROM (SELECT ','||'&str'||',' AS inlist FROM DUAL) CONNECT BY LEVEL <= LENGTH('&str')-LENGTH(REPLACE('&str',',','')) + 1; 输入ab,cd,efg,mm,结果为: ab cd efg mm |
1)使用传统数据构造方法 SELECT ID,rn,list_str,REGEXP_SUBSTR(list_str,'[^,]+',1,rn) str FROM t,(SELECT LEVEL rn FROM DUAL CONNECT BY LEVEL<=(SELECT MAX(length(trim(translate(list_str,replace(list_str,','),' '))))+1 FROM t)) WHERE REGEXP_SUBSTR(list_str,'[^,]+',1,rn) IS NOT NULL ORDER BY ID,rn; 2)使用DBMS_RANDOM递归技巧 SELECT id,level lv,list_str, rtrim(regexp_substr(list_str || ',', '.*?' || ',', 1, LEVEL), ',') AS str FROM t CONNECT BY id = PRIOR id AND PRIOR DBMS_RANDOM.VALUE IS NOT NULL AND LEVEL <= length(regexp_replace(list_str, '[^,]'))+1 ORDER BY ID,lv ; 结果都是: ID LV LIST_STR STR ---- ---------- -------------------- ---------- 1 1 xyy,m,ab xyy 1 2 xyy,m,ab m 1 3 xyy,m,ab ab 2 1 o,pn,nnnn,bb o 2 2 o,pn,nnnn,bb pn 2 3 o,pn,nnnn,bb nnnn 2 4 o,pn,nnnn,bb bb 3 1 M M |