2016-12-15 92 views
1

我想问如何返回光标到有限的表? 我的意思是一个函数,它需要(如果绝对位置,如果向前或向后,多少条记录,绝对位置),并作为获取绝对+向前。 我试过这个,但没有工作。函数返回有限的光标

drop function func(text,text,integer,integer); 
create function func(text,text,integer,integer=0) returns refcursor as ' 
declare 
    ref refcursor; 
begin 
    open ref for select * from test; 
    if $1="A" then 
     if $2="F" then 
      move absolute $4 in ref; 
      return fetch forward $3 from ref; 
     elseif $2="B" 
      move absolute $4 in ref; 
      return fetch backward $3 from ref; 
     end if; 
    elseif $1="B" then 
     if $2="F" then 
      return fetch forward $3 from ref; 
     elseif $2="B" 
      return fetch backward $3 from ref; 
     end if; 
    end if; 
end; 
'language plpgsql; 

回答

0

而不是试图操纵游标,我想你可能需要在查询本身中应用这些约束。

我假设你真正的查询将有一个ORDER BY条款,因为没有它的FETCH方向是相当没有意义的。此外,“绝对”参数似乎没有多大用处,因为指定'B'与指定'A'的位置0相同,因此您应该可以将其删除。

最终的结果会是这样的:

create or replace function func(dir text, num integer, pos integer=0) returns refcursor as $$ 
declare 
    ref refcursor; 
begin 
    open ref for execute 
    ' select * from test ' 
    ' order by x ' || case dir when 'F' then 'ASC' when 'B' then 'DESC' end || 
    ' limit ' || num || 
    ' offset ' || pos; 
    return ref; 
end; 
$$ language plpgsql;