通过db2中的递归查询检索字段偏移量

时间:2019-06-17 11:36:23

标签: sql recursion db2

假设我有field_name-field_len对的键值表。

如下:

-----------------------------------
field_name       |    field_len   |
-----------------------------------
FIELD_A          |    10          |
-----------------------------------
FIELD_B          |    20          |
-----------------------------------
...
-----------------------------------
FIELD_X          |    2           |
-----------------------------------
FIELD_Y          |    100         |
-----------------------------------

然后我需要每个字段的偏移量在第三列中。 像这样:

-----------------------------------------------------
field_name       |    field_len   |      offset     |
-----------------------------------------------------
FIELD_A          |    10          |         0       |
-----------------------------------------------------
FIELD_B          |    20          |        10       |
-----------------------------------------------------
...
-----------------------------------------------------
FIELD_X          |    2           |       250       |
-----------------------------------------------------
FIELD_Y          |    100         |       252       |
-----------------------------------------------------

因此,我已根据一些手册(12)编写了此脚本:

with offsets (column_name, length, offset) as
 ((select column_name, length, CAST(0 AS SMALLINT)
     from myschema.sizes a
     start with rrn(a) = 1)
  union all
  (select b.column_name, b.length, offset + o.length
  from offsets o, myschema.sizes b
    where rrn(b) between 2 and 100))
select * from offsets;

但是,它不断陷入无限循环。

此版本也提供了相同的结果:

with offsets (column_name, length, offset) as
 ((select column_name, length, CAST(0 AS SMALLINT)
     from myschema.sizes a
     fetch first row only)
  union all
  (select b.column_name, b.length, offset + o.length
  from offsets o join myschema.sizes b on b.column_name = o.column_name
    where o.column_name <>'LAST_FIELD'))
select * from offsets;

我猜想,这与退出条件混为一谈,但无法找到修复它的确切位置。

最好避免任何特定于表的元数据,例如行数。

1 个答案:

答案 0 :(得分:2)

您不需要递归CTE。只是一个累加的总和。像这样:

select s.*,
       (sum(field_len) over (order by rrn(s)) - field_len) as offset
from myschema.sizes s;

我不确定如何定义顺序。它似乎基于函数rrn()