PostgreSQL:如何在函数中只显示CASE表达式中单个表的选定列?

时间:2014-04-01 07:08:34

标签: postgresql case plpgsql

示例:我将两个参数传递给函数,即n(案例编号)和tname(表名),并希望相应地显示行。

- 表"测试"

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

- 行插入

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

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

- 功能" f1()"

create or replace function f1(n integer,tname varchar)/*n for case number and tname for table name */
returns setof tname as 
$body$
begin
     case n
     when 1 then
     return query execute format ($$ select rollno,fname from %I $$,tname);

     when 2 then 
     return query execute format ($$ select lname,age,branch from %I $$,tname);

     when 3 then
     return query execute format ($$ select phno,email,address,city,country from %I $$,tname);

     end case;
end
$body$
language plpgsql;

- 调用函数

select * from f1(1,'testing');
/*Show only case "1" select query result*/

select * from f1(2,'testing');
/*Show only case "2" select query result*/

select * from f1(3,'testing');
/*Show only case "3" select query result*/

1 个答案:

答案 0 :(得分:2)

虽然返回类型的Craig is correct在函数声明中不能是动态的,但 可以通过polymorphic types解决这个问题。这非常简单,实际上可以完美运行:

CREATE OR REPLACE FUNCTION data_of(_tbl_type anyelement)
  RETURNS SETOF anyelement AS
$func$
BEGIN
RETURN QUERY EXECUTE 'SELECT * FROM '|| pg_typeof(_tbl_type);
END
$func$ LANGUAGE plpgsql;

致电(重要!):

SELECT rollno,fname FROM data_of(NULL::testing);
SELECT * FROM data_of(NULL::my_schema.my_table);
SELECT * FROM data_of(NULL::my_custom_type);

您需要的是一种众所周知的类型。对于每个表,自动有一个众所周知的类型。但您可以创建任何类型,向其投射NULL并将其传递给该函数。通过这种方式,您可以准确地构建问题中的内容......

更详细的相关答案
Refactor a PL/pgSQL function to return the output of various SELECT queries