Sql 将逗号分隔的值拆分为列oracle

Sql 将逗号分隔的值拆分为列oracle,sql,oracle,delimiter,Sql,Oracle,Delimiter,我在这里基于一个类似的问题构建了这个解决方案,但是我的示例比这里引用的示例要大得多。我的解决方案可行,但我想知道它是否是最好/最有效的 有一个警告:我需要它能够像直接查询一样运行 我构建这个SQL是为了将字符串拆分为多列。我将变量留在那里,因为: 它比真正的字符串短,而且 问这个问题并不重要 在运行时,该变量将替换为一个字符串,该字符串由14个值和13个逗号分隔。我需要将最后3个值连接在一起 不用多说,我的问题是: select regexp_substr('$CSV

我在这里基于一个类似的问题构建了这个解决方案,但是我的示例比这里引用的示例要大得多。我的解决方案可行,但我想知道它是否是最好/最有效的

有一个警告:我需要它能够像直接查询一样运行

我构建这个SQL是为了将字符串拆分为多列。我将变量留在那里,因为:

  • 它比真正的字符串短,而且
  • 问这个问题并不重要
  • 在运行时,该变量将替换为一个字符串,该字符串由14个值和13个逗号分隔。我需要将最后3个值连接在一起

    不用多说,我的问题是:

    select  
                regexp_substr('$CSV Text Single Line$','[^,]+',1,  1)   c1, 
                regexp_substr('$CSV Text Single Line$','[^,]+',1,  2)   c2, 
                regexp_substr('$CSV Text Single Line$','[^,]+',1,  3)   c3, 
                regexp_substr('$CSV Text Single Line$','[^,]+',1,  4)   c4, 
                regexp_substr('$CSV Text Single Line$','[^,]+',1,  5)   c5, 
                regexp_substr('$CSV Text Single Line$','[^,]+',1,  6)   c6, 
                regexp_substr('$CSV Text Single Line$','[^,]+',1,  7)   c7, 
                regexp_substr('$CSV Text Single Line$','[^,]+',1,  8)   c8, 
                regexp_substr('$CSV Text Single Line$','[^,]+',1,  9)   c9, 
                regexp_substr('$CSV Text Single Line$','[^,]+',1, 10)  c10, 
                regexp_substr('$CSV Text Single Line$','[^,]+',1, 11)  c11, 
        replace(regexp_substr('$CSV Text Single Line$','[^,]+',1, 12)  
                ||','|| 
                regexp_substr('$CSV Text Single Line$','[^,]+',1, 13)  
                ||','|| 
                regexp_substr('$CSV Text Single Line$','[^,]+',1, 14) 
                ,'"','')                                               c12 
    from dual 
    

    提前感谢您的建议。

    最糟糕的是CSV字符串在查询中出现了不止一次。我看到的一个改进是在子查询中隔离该字符串:

    with
      csv as (
        select '$CSV Text Single Line$' str 
          from dual)
    select regexp_substr(str,'[^,]+', 1,  1)   c1, 
           regexp_substr(str,'[^,]+', 1,  2)   c2, 
           regexp_substr(str,'[^,]+', 1,  6)   c6, 
           regexp_substr(str,'[^,]+', 1,  7)   c7, 
           regexp_substr(str,'[^,]+', 1,  8)   c8, 
           regexp_substr(str,'[^,]+', 1,  9)   c9, 
           regexp_substr(str,'[^,]+', 1, 10)  c10, 
           regexp_substr(str,'[^,]+', 1, 11)  c11, 
           replace(regexp_substr(str,'[^,]+', 1, 12)  ||','|| 
              regexp_substr(str,'[^,]+', 1, 13)  ||','|| 
              regexp_substr(str,'[^,]+', 1, 14) ,'"','') c12 
    from csv;
    

    对于长CSV字符串,您可以在共享池区域中节省宝贵的空间,特别是如果您经常使用不同的硬编码CSV字符串执行此查询。如果使用绑定,其优点是只需绑定一个变量而不是11个变量就足够了。

    正则表达式可能会很昂贵。对于最后一列,不要使用3个正则表达式函数,然后将它们串联起来, 您可以使用简单的SUBSTR

    select replace(
                   substr('$CSV Text Single Line$', 
                          instr('$CSV Text Single Line$',',',-1,3) + 1
                         ),
                  '"',''
                  ) as c12
    from dual;