如何在PL / SQL中将CSV字符串转换为多列结果?

时间:2017-07-18 05:12:45

标签: csv plsql

我们假设我有一个这样的字符串:

a;b;c#d,e,f#g,h,i#j,k,l#m,n,o

;用于分隔列,#用于分隔行,因此结果应该与上面的示例类似:

+---------+---------+---------+
| Column1 | Column2 | Column3 |
+---------+---------+---------+
| a       | b       | c       |
+---------+---------+---------+
| d       | e       | f       |
+---------+---------+---------+
| g       | h       | i       |
+---------+---------+---------+
| j       | k       | l       |
+---------+---------+---------+

问题是 - 正如我在标题中写的那样 - 是否可以编写一个给出预期结果的SQL SELECT

1 个答案:

答案 0 :(得分:0)

我设法解决了我的问题,抱歉这个noob问题。这是解决方案代码,将来可能会对其他人有所帮助:

WITH
  splitted_rows as (
    SELECT TRIM(regexp_substr('a;b;c#d,e,f#g,h,i#j,k,l#m,n,o', '[^#]+', 1, LEVEL)) AS str
      FROM dual
    CONNECT BY LEVEL <= regexp_count('a;b;c#d,e,f#g,h,i#j,k,l#m,n,o', '#') + 1)
SELECT regexp_substr(sr.str, '[^#]+', 1, 1) as column1
      ,regexp_substr(sr.str, '[^#]+', 1, 2) as column2
      ,regexp_substr(sr.str, '[^#]+', 1, 3) as column3
  FROM splitted_rows sr