PostgreSQL:在函数中使用RECORD类型变量显示结果

时间:2014-04-01 11:31:29

标签: postgresql record plpgsql

我将列名和表名作为参数传递给动态查询的函数,如下例所示。

问题:执行" SELECT"在函数内查询,它只显示表的结构而不是行。

示例:

- 表

create table test1
(
   rollno integer,
   fname text,
   lname text,
   age integer,
   branch text,
   phno integer,
   email text,
   address text,
   city text,
   state text,
   country text
 );

- 插入一些行

insert into tes1 values(1,'aaa','bbb',25,'CS',1234567890,'abc@gmail.com','sector1','xyz','zyx','yxz');

insert into tes1 values(2,'zzz','xxx',25,'EE',987654321,'zzz@gmail.com','sector2','uvw','wvu','vuw');

- 功能

create or replace function fun1(colB text,vname varchar)
returns setof record as
$body$
declare 
       str text;
       grp text;
       addi text;
       sqlq varchar;
       tname varchar;
begin
       if colB='fname' then
         str:='fname';
         grp:='rollno'||','||'fname';
         addi:='city'||','||'state'||','||'country';
         tname:=vname;

       elsif colB='lname' then
         str:='lname';
         grp:='rollno'||','||'lname';
         addi:='city'||','||'state'||','||'country';
         tname:=vname;
       end if;

   raise info '%',str;
   raise info '%',grp;
   raise info '%',addi;
   raise info '%',vname;
   raise info '%',tname;

   sqlq:='select rollno,'||str||',age,branch,'||addi||' from '|| tname;
   raise info '%',sqlq;
   execute sqlq;    

end;
$body$
language plpgsql; 

- 调用函数

select * from fun1('lname','test1') as ("rollno" integer,"lname" text,
"age" integer,"branch" text,"city" text,"state" text,"country" text);

INFO:  lname
INFO:  rollno,lname
INFO:  city,state,country
INFO:  tes1
INFO:  tes1
INFO:  select rollno,lname,age,branch,city,state,country from tes1
rollno | lname | age | branch | city | state | country
--------+-------+-----+--------+------+-------+---------
(0 rows)

1 个答案:

答案 0 :(得分:2)

你必须return在函数中包含结果(除非是RETURNS VOID),例如

RETURN QUERY EXECUTE sqlq;

而且, 应正确escape列名,f.ex。使用format()功能,例如

RETURN QUERY EXECUTE format('SELECT "col1", %I FROM %I', 'col2', 'test1');