postgresqlref-cursor

how to handle refcursor not retrieving data in PGSQL


How to handle refcursor not retrieving data(empty resultset) in PGSQL?

create or replace function function_1( In tblname varchar(15))
 returns refcursor
 language plpgsql
 as $$
    declare
    v_cnt integer;
    r_ref refcursor='ref2';
    v_sql text='select * from tbl where 1=2';--default statement;shld return empty if 
                                              --input is invalid
begin

    if tblname ilike 'scientist' then
         v_sql:='select * from tbl'; --table name 1
   end if;
   
open r_ref for
     execute v_sql;
 return r_ref;  


end;
$$;

Is there any other way to handle without using dynamic sql? execution: Test case 1 : should return empty result set

select * from function_1('invalid');  
fetch all in "ref2";

execution: Test case 2 : should return proper data from able

select * from function_1('scientist');  
fetch all in "ref2";

Thanks


Solution

  • You don't need a dynamic query when you only have one test case to cover = 'scientist'. In this case, you can simply do :

    create or replace function function_1( In tblname varchar(15))
     returns setof scientist language plpgsql as $$
    begin
        if tblname ilike 'scientist' then
             return query
               select * from scientist ;
       end if;
    end;
    $$;