Как передать таблицу как argtype в функцию postgres? - PullRequest
0 голосов
/ 16 мая 2019
create table test_tbl (id int, name character varying(10));

insert test_tbl values(1,'A');
insert test_tbl values(2,'B');
insert test_tbl values(3,'C');
insert test_tbl values(4,'D');
insert test_tbl values(5,'F');

Теперь я хочу передать эту таблицу в качестве входного аргумента функции.

create function myfn (in tbl (how to define the table input))
as 
return set of <some type>
begin 
 return query AS
 select concat(id,name)  
 from test_tbl 
 where id in (select id from in_tbl);

end;

Как объявить входной аргумент табличного типа?Как вызвать эту функцию при вводе таблицы?

select * from myfn(<pass the table - test_tbl>);

1 Ответ

0 голосов
/ 16 мая 2019

Вы можете использовать тип regclass и создать динамический запрос

create or replace function myfn (in tbl regclass)

returns TABLE(id INT)
as  $$
begin 

RETURN QUERY EXECUTE format('select id 
 from test 
 where id in (select id from %s)',tbl);

end 
$$  LANGUAGE plpgsql;

, и вы вызываете его, используя

select * from myfn('mytablename');
...