Oracle SQL需求:按分隔符拆分字符串至多列
Oracle SQL按$拆分字符串到多列的实现方案
方法一:使用SUBSTR + INSTR组合
这是你提到的传统字符串函数方案,核心是通过INSTR定位第N个$分隔符的位置,再用SUBSTR截取对应区间的内容:
WITH sample_data AS ( SELECT 'NA$Sales$India/Blore$Hardware$Sold' AS str FROM dual ) SELECT -- 提取第一个$之前的内容(Region) SUBSTR(str, 1, INSTR(str, '$') - 1) AS Region, -- 提取第一个$和第二个$之间的内容(Department) SUBSTR(str, INSTR(str, '$') + 1, INSTR(str, '$', 1, 2) - INSTR(str, '$') - 1) AS Department, -- 提取第二个$和第三个$之间的内容(Country) SUBSTR(str, INSTR(str, '$', 1, 2) + 1, INSTR(str, '$', 1, 3) - INSTR(str, '$', 1, 2) - 1) AS Country, -- 提取第三个$和第四个$之间的内容(Product_type) SUBSTR(str, INSTR(str, '$', 1, 3) + 1, INSTR(str, '$', 1, 4) - INSTR(str, '$', 1, 3) - 1) AS Product_type, -- 提取第四个$之后的内容(Status) SUBSTR(str, INSTR(str, '$', 1, 4) + 1) AS Status FROM sample_data;
关键函数说明
INSTR(str, '$', 1, n):返回字符串str中第n个$的位置,第三个参数1表示从字符串起始位置开始查找,第四个参数n指定要找的是第几个匹配项。SUBSTR(str, start_pos, length):从start_pos位置开始,截取length长度的内容;如果省略length,则截取到字符串末尾。
方法二:使用REGEXP_SUBSTR正则截取(更简洁)
如果Oracle版本支持正则函数(11g及以上),可以用REGEXP_SUBSTR直接按分隔符提取第N个分段,代码更简洁:
WITH sample_data AS ( SELECT 'NA$Sales$India/Blore$Hardware$Sold' AS str FROM dual ) SELECT REGEXP_SUBSTR(str, '[^$]+', 1, 1) AS Region, REGEXP_SUBSTR(str, '[^$]+', 1, 2) AS Department, REGEXP_SUBSTR(str, '[^$]+', 1, 3) AS Country, REGEXP_SUBSTR(str, '[^$]+', 1, 4) AS Product_type, REGEXP_SUBSTR(str, '[^$]+', 1, 5) AS Status FROM sample_data;
正则说明
[^$]+:匹配任意**非$**的连续字符,也就是两个$之间的内容。- 最后一个参数
n指定提取第n个匹配到的分段。
内容的提问来源于stack exchange,提问作者Waseem
相关产品推荐
相关产品推荐

