使用 XMLTable 拆分分隔字符串
样本数据 :
CREATE TABLE table_name ( id, list ) AS
SELECT 1, 'a,b,c,d' FROM DUAL UNION ALL -- Multiple items in the list
SELECT 2, 'e' FROM DUAL UNION ALL -- Single item in the list
SELECT 3, NULL FROM DUAL UNION ALL -- NULL list
SELECT 4, 'f,,g' FROM DUAL; -- NULL item in the list
查询 :
SELECT t.id,
SUBSTR( x.item.getStringVal(), 2 ) AS item,
x.lvl
FROM table_name t
CROSS JOIN
XMLTABLE(
( '"#' || REPLACE( t.list, ',', '","#' ) || '"' )
COLUMNS item XMLTYPE PATH '.',
lvl FOR ORDINALITY
) x;
(注意:附加 #
字符以便于提取 NULL
值;稍后使用 SUBSTR( item, 2 )
删除它。如果不需要 NULL
值,那么你可以简化查询并省略它。)
输出 :
ID ITEM LVL
---------- ------- ----------
1 a 1
1 b 2
1 c 3
1 d 4
2 e 1
3 (NULL) 1
4 f 1
4 (NULL) 2
4 g 3