简体   繁体   English

使用表值参数过滤函数中的表

[英]Filter table in a function using a table valued parameter

I have a table-valued function that uses a parameter to filter a table and returns the results: 我有一个表值函数,该函数使用参数过滤表并返回结果:

drop table if exists mytbl;
create table mytbl (i int);
insert into mytbl (i) values (1),(2),(3);

CREATE FUNCTION filterer(
    _filter int
)
RETURNS TABLE(i_ret int)
    LANGUAGE 'plpgsql'
AS $BODY$
BEGIN
    RETURN  QUERY   SELECT  i 
                    FROM    mytbl
                    WHERE   i = _filter;
END;
$BODY$;
select * from filterer(1);

it returns: 它返回:

在此处输入图片说明

So far so good. 到现在为止还挺好。 However what I really want to do is filter on a list of values rather than just one. 但是,我真正想要做的是对值列表进行筛选,而不只是对一个值进行筛选。 I figured the way to do it is create a table-valued parameter using a type that I define using CREATE TYPE, but I can't get it working. 我想办法是使用我使用CREATE TYPE定义的类型创建一个表值参数,但是我无法使其正常工作。 Here's what I have so far: 这是我到目前为止的内容:

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   i IN (_filter);
END;
$BODY$;

select * from filterer(1);

When I run that code it fails with: 当我运行该代码时,它失败并显示:

ERROR: function filterer(integer) does not exist LINE 23: select * from filterer(1); 错误:函数filterer(integer)不存在第23行:从filterer(1)中选择*;

How do I declare a variable of type tp and pass it into my function? 如何声明tp类型的变量并将其传递给函数?

working example 工作实例

Two things here: 这里有两件事:

 WHERE   i IN (_filter);

should be replaced with 应该替换为

 WHERE   row(i) IN (_filter);

and calling: 并致电:

select * from filterer(row(1));

I assume the question is purely academic, as I can't see any use of such type?.. 我认为这个问题纯粹是学术性的,因为我看不到这种类型的用法。

CREATE TYPE tp AS (i int);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM