手机版
你好,游客 登录 注册
背景:
阅读新闻

PostgreSQL游标示例(创建游标,并在函数中遍历之)

[日期:2012-03-04] 来源:Linux社区  作者:lslxdx [字体:大 中 小]

PostgreSQL游标示例(创建游标,并在函数中遍历之)

  1. --drop function top100cur(refcursor);   
  2. create function top100cur(refcursor) returns refcursor as $$  
  3. begin  
  4.     open $1 for select * from person limit 100;  
  5.     return $1;  
  6. end  
  7. $$language plpgsql;  
  8.   
  9. ----------测试游标---------   
  10. -- SELECT top100cur('abc');   
  11. -- fetch all from abc;   
  12.   
  13. -- drop function from2cur(refcursor,int,int);   
  14. --这是一个返回游标中在一定范围内记录的函数--   
  15. create function from2cur(refcursor,int,int)returns setof text as $$  
  16. declare--声明一些下标变量   
  17.     pnam text;  
  18.     pno text;  
  19.     index int;  
  20.     lower int;  
  21.     upper int;  
  22. begin  
  23.     index:=1;  
  24.     lower:=$2;  
  25.     upper:=$3;  
  26.       
  27.     fetch $1 into pnam,pno;--必须先fetch一条,否则found为false   
  28.     while found loop  
  29.         --只在[lower,upper]区间的记录才返回--   
  30.         if lower<=index and upper>=index then  
  31.             return next pnam||pno;  
  32.         end if;  
  33.           
  34.         fetch $1 into pnam,pno;  
  35.         index:=index+1;  
  36.   
  37.         --超过upper后,函数返回--   
  38.         if index>upper then   
  39.             return;  
  40.         end if;  
  41.     end loop;  
  42. end  
  43. $$language plpgsql;  
  44.   
  45. select top100cur('abc');--创建一个名字为abc的游标   
  46. -- fetch all in abc;--测试游标   
  47. select * from from2cur('abc',2,5);  
linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款