将SELECT结果作为参数传递给postgreSQL函数

问题描述 投票:11回答:3

我有一个表“UserState”,其中包含以下字段:id,userid,ctime,state,endtime。我有一个简单的查询:

SELECT userid FROM "UserState" WHERE ctime>'2014-07-14'::timestamp

我有一个plpgsql函数,它必须将此查询的结果作为参数:

get_timeinstate(SELECT userid FROM "UserState" WHERE ctime>'2014-07-14'::timestamp);

如何正确创建函数以将查询结果作为参数传递?有必要理解,该函数返回另一个SQL结果,我需要在那里使用“IN”条件:

$func$
BEGIN
 RETURN QUERY
 SELECT 
...myanotherquery...
 WHERE "UserState".userid IN (HERE I NEED TO INSERT MY QUERY RESULT)
END;
$func$
postgresql plpgsql
3个回答
5
投票

将返回的user_id设置为数组。创建接受整数数组的函数

create function get_timeinstate (
    user_id_set integer[],
    another_param...

然后调用它传递array_agg生成的数组

get_timeinstate(
    (
        select array_agg(userid)
        from "UserState"
        where ctime>'2014-07-14'::timestamp
    ),
    another_param
);

功能内部:

where "UserState".userid = any (user_id_set)

顺便说一句,如果你使用的是plpgsql,你可以将查询放在函数中并只传递日期:

create function get_timeinstate (
    p_ctime timestamp,
    another_param...
$func$
declare
    user_id_set integer[] := (
        select array_agg(userid)
        from "UserState"
        where ctime > p_ctime
    );
begin
    return query
    select 
    ...myanotherquery...
    where "UserState".userid = any (user_id_set)
end;
$func$

1
投票

只需用圆括号括起来:

get_timeinstate(
(
  SELECT userid FROM "UserState" WHERE ctime>'2014-07-14'::timestamp)
);

0
投票

我认为接受的答案过于复杂这是我自我描述的例子:

with p as
(
    select id, xyz geometry from insar1.point
)
, extent as
(
    select st_extent(st_force2d(geometry)) geometry from p
)
INSERT INTO insar1.grid (geometry)
SELECT (
    ST_Dump(
      makegrid_2d(
        --maybe you need limit 1
        (SELECT e.geometry from extent e), --just use braces
        --this works too:
        --(ARRAY(SELECT e.geometry from extent e))[1],
         100,
         100
       )
    )
  ) .geom geometry
© www.soinside.com 2019 - 2024. All rights reserved.