PostgreSQL 遍历表的PLSQL列举
发布时间:2020-12-13 17:30:44 所属栏目:百科 来源:网络整理
导读:我们经常会对数据字典中的系统表进行遍历,从而写一些SHELL脚本或者动态造数据等等。 这里我用PLSQL演示了三种方法来遍历一张表。 表结构如下, 1 2 3 4 5 6 t_girl=# d tmp_1; Unlogged table "public.tmp_1" Column | Type | Modifiers ----------+------
1
|
create
type ytt_record
as
(id
int
,log_time
zone);
|
6
7
8
9
10
11
12
13
14
15
16
17
18
19
or
replace
function
sp_test_record1(
IN
f_id
int
)
returns
setof ytt_record
as
$ytt$
declare
i
;
cnt
;
o_out ytt_record;
begin
i := 0;
cnt := 0;
select
count
(*)
into
from
tmp_1
where
id > f_id;
while i < cnt
loop
select
id,monospace!important; font-size:1em!important; min-height:inherit!important">strict o_out
id > f_id
order
by
log_time
desc
limit 1 offset i;
i := i + 1;
return
next
o_out;
end
loop;
;
$ytt$ language plpgsql;
15
*
sp_test_record1(60);
id | log_time
----+----------------------------
85 | 2014-01-11 17:52:11.696354
73 | 2014-01-09 17:52:11.696354
77 | 2014-01-04 17:52:11.696354
80 | 2014-01-03 17:52:11.696354
76 | 2014-01-02 17:52:11.696354
65 | 2013-12-31 17:52:11.696354
80 | 2013-12-30 17:52:11.098336
85 | 2013-12-27 17:52:11.098336
97 | 2013-12-26 17:52:11.696354
94 | 2013-12-24 17:52:09.321394
(10
rows
)
Time
: 3.338 ms