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


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);  

相关内容