我的一位同事在做COBOL程序时遇到了这个问题,最终在应用程序层面解决了它。
我仍然很好奇是否可以使用 SQL 在数据访问级别上解决它。
这在某种程度上与这另一个问题 https://stackoverflow.com/questions/29039410/can-i-use-sql-to-split-contents-of-a-table-column-stored-as-csv-comma-seperated,但我只想使用 ANSI SQL。
我正在寻找一个作用于包含可变长度 CSV 行的 VARCHAR 字段的单个 SQL 选择查询。查询的目的是将每个 CSV 字段拆分到其自己的结果集行中。
这是一个包含模式和数据的示例(这是fiddle http://sqlfiddle.com/#!9/20a9b):
CREATE TABLE table1 (`field` varchar(100));
INSERT INTO table1 (`field`)
VALUES
('Hello,world,!') ,
('Haloa,!') ,
('Have,a,nice,day,!');
这是我希望从查询中获得的输出:
Hello
world
!
Haloa
!
Have
a
nice
day
!
使用的 CSV 分隔符是逗号,现在我不用担心转义。
据我所知,这是 ANSI SQL:
with recursive word_list (field, word, rest, field_id, level) as (
select field,
substring(field from 1 for position(',' in field) - 1) as word,
substring(field from position(',' in field) + 1) as rest,
row_number() over () as field_id,
1
from table1
union all
select c.field,
case
when position(',' in p.rest) = 0 then p.rest
else substring(p.rest from 1 for position(',' in p.rest) - 1)
end as word,
case
when position(',' in p.rest) = 0 then null
else substring(p.rest from position(',' in p.rest) + 1)
end as rest,
p.field_id,
p.level + 1
from table1 as c
join word_list p on c.field = p.field and position(',' in p.rest) >= 0
)
select word
from word_list
order by field_id, level;
这假设中的值field
是独一无二的。
这里有一个
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)