0

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

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

我构建了这个 SQL 来将一个字符串拆分为多个列。我把我的变量放在那里是因为:

  1. 它比真正的字符串短并且
  2. 问这个问题并不重要。

在运行时,该变量将替换为一个字符串,该字符串包含 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 

提前感谢您的任何建议。

4

2 回答 2

1

丑陋的部分是 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个就足够了。

于 2013-11-13T10:06:58.407 回答
0

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

select replace(
               substr('$CSV Text Single Line$', 
                      instr('$CSV Text Single Line$',',',-1,3) + 1
                     ),
              '"',''
              ) as c12
from dual;
于 2013-11-13T11:26:32.800 回答