有表t_col_str,数据如下:
现要将表中c123列,根据逗号,拆分成多列。
1)substr + instr
适用范围:8i,9i,10g及以后版本
注:上面代码可简化为下面格式:
2)regexp_substr
适用范围:10g及以后版本
点击(此处)折叠或打开
- SQL> select * from t_str_col;
-
- ID C123
- ---------- --------------------
-
- 1 v11,v21,v31
- 2 v12,v22,
- 3 v13,,v33
- 4 ,v24,v34
- 5 v15,,
- 6 ,,v35
- 7 ,,
-
- 已选择7行。
现要将表中c123列,根据逗号,拆分成多列。
1)substr + instr
适用范围:8i,9i,10g及以后版本
点击(此处)折叠或打开
- SQL> SELECT id,
- 2 c123,
- 3 substr(c123, 1, instr(c123 || ',', ',', 1, 1) - 1) c1,
- 4 substr(c123,
- 5 instr(c123 || ',', ',', 1, 1) + 1,
- 6 instr(c123 || ',', ',', 1, 2) - instr(c123 || ',', ',', 1, 1) - 1) c2,
- 7 substr(c123,
- 8 instr(c123 || ',', ',', 1, 2) + 1,
- 9 instr(c123 || ',', ',', 1, 3) - instr(c123 || ',', ',', 1, 2) - 1) c3
- 10 FROM t_str_col
- 11 ORDER BY 1;
-
- ID C123 C1 C2 C3
- ---------- ------------------------------ ---------- ---------- ----------
-
- 1 v11,v21,v31 v11 v21 v31
- 2 v12,v22, v12 v22
- 3 v13,,v33 v13 v33
- 4 ,v24,v34 v24 v34
- 5 v15,, v15
- 6 ,,v35 v35
- 7 ,,
-
- 已选择7行。
点击(此处)折叠或打开
- SQL> edit
- 已写入 file afiedt.buf
-
- 1 SELECT id,
- 2 c123,
- 3 substr(c123, 1, instr(c123, ',', 1, 1) - 1) c1,
- 4 substr(c123,
- 5 instr(c123, ',', 1, 1) + 1,
- 6 instr(c123, ',', 1, 2) - instr(c123, ',', 1, 1) - 1) c2,
- 7 substr(c123,
- 8 instr(c123, ',', 1, 2) + 1) c3
- 9 FROM t_str_col
- 10* ORDER BY 1
- SQL> /
-
- ID C123 C1 C2 C3
- ---------- ------------------------------ ---------- ---------- ----------
-
- 1 v11,v21,v31 v11 v21 v31
- 2 v12,v22, v12 v22
- 3 v13,,v33 v13 v33
- 4 ,v24,v34 v24 v34
- 5 v15,, v15
- 6 ,,v35 v35
- 7 ,,
-
- 已选择7行。
-
- SQL>
2)regexp_substr
适用范围:10g及以后版本
点击(此处)折叠或打开
- SQL> SELECT id,
- 2 c123,
- 3 rtrim(regexp_substr(c123 || ',', '.*?' || ',', 1, 1), ',') AS c1,
- 4 rtrim(regexp_substr(c123 || ',', '.*?' || ',', 1, 2), ',') AS c2,
- 5 rtrim(regexp_substr(c123 || ',', '.*?' || ',', 1, 3), ',') AS c3
- 6 FROM t_str_col
- 7 ORDER BY 1;
-
- ID C123 C1 C2 C3
- ---------- ------------------------------ ---------- ---------- ----------
-
- 1 v11,v21,v31 v11 v21 v31
- 2 v12,v22, v12 v22
- 3 v13,,v33 v13 v33
- 4 ,v24,v34 v24 v34
- 5 v15,, v15
- 6 ,,v35 v35
- 7 ,,
-
- 已选择7行。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/21251711/viewspace-1067535/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/21251711/viewspace-1067535/