oracle使用CTE递归分解字符串
背景
给定一个不定长度字符串 并且以,分割例如 '1,2,3,4' 使用sql查询 返回1,2,3,4四行 如果'1,2' 则返回 1,2 两行 使用sql实现
实现sql
sql
WITH RECURSIVE split_strings AS (
-- 初始查询,处理第一个值
SELECT
id,
SUBSTRING_INDEX(column1, ',', 1) AS value,
SUBSTRING(column1, LENGTH(SUBSTRING_INDEX(column1, ',', 1)) + 2) AS remaining
FROM fs.my_table
WHERE column1 != ''
UNION ALL
SELECT
s.id,
SUBSTRING_INDEX(s.remaining, ',', 1) AS value,
SUBSTRING(s.remaining, LENGTH(SUBSTRING_INDEX(s.remaining, ',', 1)) + 2) AS remaining
FROM split_strings s
WHERE s.remaining != ''
)
SELECT id, value
FROM split_strings
ORDER BY id, value;