我将列名和表名作为参数传递给动态查询的函数,如下例所示。
问题:执行" 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)