Postgres中的子句将大字符列串成行。

问题描述 投票:0回答:1

问题:我写的代码有局限性,不能以列> 4K字节的方式进行读取

因为:将单行变成多行,并有新的最大长度,并有序数来保持它们的顺序。

我之前在DB2中使用with子句和递归查询做了这个活动,我正试图将代码转换为Postgres的工作。我没有那么多Postgres经验,不知道有没有更好的方法。

首先,我有一个表格

Create table test_long_text (
   test_id numeric(12,0) NOT NULL,
   long_text varchar(64000)
)

下面是我一直想写的查询,但失败了。

WITH RECURSIVE rec(test_id, len, ord, pos) as (
   select test_id, octet_length(long_text), 1, 1 from test_long_text
   union all
   select test_id, len, ord+1, pos+4096 from rec where len >=4096)
select A.test_id, ord, substr(long_text, pos, 4096) from test_long_text A
inner join rec using (test_id)
order by A.test_id, ord

目前,我得到了一个错误负子串长度不允许或它挂起无限期。

预期结果:其中文本是最大4096字节长的文本块,假设ABC是一个较长的字符串。

+--------------+
| ID |ORD|TEXT |
| 1  |1  |ABC  |
+--------------+
| 2  |1  |ABC  |
+--------------+
| 2  |2  |DEF  |
+--------------+
| 3  |1  |ABC  |
+--------------+
| 3  |2  |DEF  |
+--------------+
| 3  |3  |GHI  |
+--------------+
postgresql common-table-expression recursive-query
1个回答
1
投票

这个例子展示了如何将文本列的值分割成3个字符部分。

with t(x) as (values('1234567890abcdef'::text), ('qwertyuiop'))
select *, substring(x, f.p, 3)
from t, generate_series(1, length(x), 3) with ordinality as f(p, i);
        ││ 1234567890abcdef │ 10 │ 4 │ 0ab ││ 1234567890abcdef │ 13 │ 5 │ cde ││ 1234567890abcdef │ 16 │ 6 │ f ││ qwertyuiop │ 1 │ 1 │ qwe ││ qwertyuiop │ 4 │ 2 │。

你可以根据你的数据简单地调整它。

© www.soinside.com 2019 - 2024. All rights reserved.