我们经常会对数据字典中的系统表进行遍历,从而写一些SHELL脚本或者动态造数据等等。 这里我用PLSQL演示了三种方法来遍历一张表。
表结构如下,t_girl=# \d tmp_1;
Unlogged table "public.tmp_1"
Column | Type | Modifiers
----------+-----------------------------+-----------
id | integer |
log_time | timestamp without time zone |
在这里我创建里一个自定义类型来保存我的函数返回值。create type ytt_record as (id int,log_time timestamp without time zone);
现在来看第一个函数。 也是用最笨的方法来遍历。create or replace function sp_test_record1(
IN f_id int
) returns setof ytt_record as
$ytt$
declare i int;
declare cnt int;
declare o_out ytt_record;
begin
i := 0;
cnt := 0;
select count(*) into cnt from tmp_1 where id > f_id;
while i < cnt
loop
select id,log_time into strict o_out from tmp_1 where id > f_id order by log_time desc limit 1 offset