Oracle SQL 没有存储的分隔符分割 Procedure/Function

Oracle SQL Split by Delimiters Without Store Procedure/Function

我想在 oracle 数据库中通过分隔符 (|) 拆分列。我该怎么做?

在 db 中,值将存储为:

字段

AP1|Apple Juice|100

我想把它分开成:

字段 1 |字段 2 |字段 3

AP1 Apple Juice 100    

我不知道确切的查询,但基本上下面是我想要的。

select split(Field) as Field1, split(Field) as Field2, split(Field) as Field3

我只想使用 SQL(不创建任何存储过程或函数)。

您可以使用 SUBSTRINSTR 在纯 SQL 中完成提取分隔符 |.

之间的子字符串

对于简单的字符串操作,我更喜欢 SUBSTR + INSTR 方法,因为它是 still faster than the REGEXP。当然,对于最近的版本,性能差异正在缩小,但是,REGEXP 仍然比旧的 SUBTR+INSTR.

更密集 CPU

例如,

SQL> WITH sample_data AS
  2    (SELECT 'AP1|Apple Juice|100' str
  3    FROM dual
  4    )
  5  -- end of sample_data mocking as a table
  6  SELECT str,
  7         SUBSTR(str, 1, instr(str, '|', 1,1) -1) str1,
  8         SUBSTR(str, instr(str, '|', 1, 1) + 1,
  9                   instr(str, '|', 1, 2) -
 10                  instr(str, '|', 1, 1) -1) str2,
 11         SUBSTR(str, instr(str, '|', 1, 2) + 1) str3
 12  FROM sample_data;

STR                 STR1                STR2                STR3
------------------- ------------------- ------------------- ----
AP1|Apple Juice|100 AP1                 Apple Juice         100

附带说明一下,您不应将数据存储为 分隔字符串 ,这确实是一个糟糕的设计。您应该规范化它作为永久修复。尽可能将 属性 存储在 不同的列 中,这样您就没有操作字符串来提取各个属性的开销。

使用正则表达式:

with sample_data as
    (select 'AP1|Apple Juice|100' str
    from dual
)
select str,
     regexp_substr(str, '[^|]+', 1, 1) str1,
     regexp_substr(str, '[^|]+', 1, 2) str2,
     regexp_substr(str, '[^|]+', 1, 3) str3
from sample_data;