
我们经常会对数据字典中的系统表进行遍历,从而写一些SHELL脚本或者动态造数据等等。 这里我用PLsql演示了三种方法来遍历一张表。
表结构如下,
| 1 2 3 4 5 6 | t_girl=# \d tmp_1; Unlogged table "public.tmp_1" Column | Type | ModifIErs ----------+-----------------------------+----------- ID | integer | log_time | timestamp without time zone | |
在这里我创建里一个自定义类型来保存我的函数返回值。
1create type ytt_record as (ID int ,log_time zone); 现在来看第一个函数。 也是用最笨的方法来遍历。
6 7 8 9 10 11 12 13 14 15 16 17 18 19or 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; 我们来执行下结果,花费了3毫秒左右。
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 现在来看第二个函数,这个就比较优化了, 用了系统自带的循环遍历结构。
12o_out ytt_record; begin for o_out in desc loop o_out; loop; ; 这次运行结果看看,时间不到1毫秒。 sp_test_record2(60); : 0.660 ms 最后一个函数, 利用RETURN query 直接返回结果集。
8begin return query ; 这个结果其实等同于直接从表SELECT,响应时间和第二个差不多。 16 sp_test_record3 ----------------------------------- (85, "2014-01-11 17:52:11.696354" ) (73,monospace!important; Font-size:1em!important; min-height:inherit!important; color:blue!important">"2014-01-09 17:52:11.696354" ) (77,monospace!important; Font-size:1em!important; min-height:inherit!important; color:blue!important">"2014-01-04 17:52:11.696354" ) (80,monospace!important; Font-size:1em!important; min-height:inherit!important; color:blue!important">"2014-01-03 17:52:11.696354" ) (76,monospace!important; Font-size:1em!important; min-height:inherit!important; color:blue!important">"2014-01-02 17:52:11.696354" ) (65,monospace!important; Font-size:1em!important; min-height:inherit!important; color:blue!important">"2013-12-31 17:52:11.696354" ) "2013-12-30 17:52:11.098336" ) "2013-12-27 17:52:11.098336" ) (97,monospace!important; Font-size:1em!important; min-height:inherit!important; color:blue!important">"2013-12-26 17:52:11.696354" ) (94,monospace!important; Font-size:1em!important; min-height:inherit!important; color:blue!important">"2013-12-24 17:52:09.321394" ) : 0.877 ms t_girl=#
转贴:http://yueliangdao0608.blog.51cto.com/397025/1351039 总结
以上是内存溢出为你收集整理的PostgreSQL 遍历表的PLSQL列举全部内容,希望文章能够帮你解决PostgreSQL 遍历表的PLSQL列举所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)