我有以下代码通过表值参数将值传递给函数,然后使用WHERE
运算符在IN
子句中使用该参数:
drop table if exists mytbl;
create table mytbl (i int);
DO $$
BEGIN
IF NOT EXISTS (SELECT * FROM pg_type t WHERE t.typname = 'tp') THEN
CREATE TYPE tp AS (i int);
END IF;
END$$;
insert into mytbl (i) values (1),(2),(3);
DROP FUNCTION public.filterer(tp);
CREATE FUNCTION filterer(
_filter tp
)
RETURNS TABLE(i_ret int)
LANGUAGE 'plpgsql'
AS $BODY$
BEGIN
RETURN QUERY SELECT i
FROM mytbl
WHERE row(i) IN (_filter);
END;
$BODY$;
select * from filterer(row(1));
我正在使用row()
来定义要传递的值,但我想要做的是传递多个值,本质上我想传递一个列表。我怎么能这样做?
答案 0 :(得分:0)
例如:
t=# create or replace function fn (a variadic int[]) returns table(i int, c text)as $$
begin
return query select *,chr(100+g) from generate_series(1,9) g where g = any(a);
end;
$$ language plpgsql;
CREATE FUNCTION
和执行:
t=# select * from fn(4,5,8);
i | c
---+---
4 | h
5 | i
8 | l
(3 rows)