0
我將列名和表名作爲參數傳遞給動態查詢的函數,如下面的示例所示。PostgreSQL:在函數中使用RECORD類型變量顯示結果
問題:在函數中執行「SELECT」查詢時,它只顯示錶格的結構而不是行。
實施例:
--Table
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
);
--Inserting某些行
insert into tes1 values(1,'aaa','bbb',25,'CS',1234567890,'[email protected]','sector1','xyz','zyx','yxz');
insert into tes1 values(2,'zzz','xxx',25,'EE',987654321,'[email protected]','sector2','uvw','wvu','vuw');
--Function
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;
--Function主叫
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)
太棒了!非常感謝你。 – Meem
消毒動態輸入是必須的,但在這種情況下僅適用於表名(在原始示例中,答案有偏差)。 「col1」的雙引號和「col2」的處理在這裏沒有任何用處 - 它們都是硬編碼的,合法的,小寫的名字。 [詳細](http://stackoverflow.com/questions/10705616/table-name-as-a-postgresql-function-parameter/10711349#10711349) –
@ErwinBrandstetter他們只是一個例子,如何使用格式化功能以此目的。 – pozs