在for循环中检测最后一条记录

3

我有一系列循环,从一个数据表中以奇怪的伪 JSON 格式组合一个 clob。

我的问题是每个循环都需要用相关字符结束该部分,但我无法确定如何识别最后一条记录。

到目前为止,我已经尝试了:

for y in (select distinct ident from table(an_object))
loop
  pseudojson := pseudojson || '{';

  the_row := y.ident;
  for z in (select * from table(an_object) where ident = the_row)
    loop
    pseudojson := pseudojson || z.the_key ||': "' || z.the_value ||'"';
    -- (1)
    end loop;

  pseudojson := pseudojson || '}';
  -- (2)
end loop;

pseudojson := pseudojson || '}';
an_object 包含未旋转的数据,通过 ident 分组成为以前的行。
对于逻辑上说,我试图塞入以下内容:
(1)
if not z.last 
then 
  pseudojson := pseudojson || ','; 
end if;

并且(2)
if not y.last
then 
  pseudojson := pseudojson || ','; 
end if;

但是这些运算符在for循环中无法使用。有谁能给我指点一下方向吗?

如果是最后一条记录呢?它应该长什么样子? - XING
@XING 如果是最后一个,则不做任何操作,退出循环。 - JohnHC
2个回答

4
这样怎么样:不管你做什么,在循环中连接常规字符,包括“最后”一行。
一旦退出循环,使用RTRIM去掉多余的字符(逗号,对吧?)。类似这样:
for y in (select distinct ident from table(an_object))
loop
  pseudojson := pseudojson || '{';

  the_row := y.ident;
  for z in (select * from table(an_object) where ident = the_row)
    loop
    pseudojson := pseudojson || z.the_key ||': "' || z.the_value ||'"';
    -- (1)
    pseudojson := pseudojson ||',';
    end loop;

    pseudojson := rtrim(pseudojson, ',');  --> this

  pseudojson := pseudojson || '}';
  -- (2)
  pseudojson := pseudojson ||',';
end loop;

pseudojson := rtrim(pseudojson, ',');      --> this
pseudojson := pseudojson || '}';

4
你可以这样做。需要一个布尔变量:
first := true;

循环体内:

if not first then
    pseudojson := pseudojson || ','; 
end if;
first := false;
-- Add the element
...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接