将PL / pgSQL SELECT转换为数组

时间:2012-07-31 00:19:11

标签: sql postgresql plpgsql postgresql-9.1

这是我的函数声明和正文的一部分:

CREATE OR REPLACE FUNCTION access_update()
RETURNS void AS $$
DECLARE team_ids bigint[];
BEGIN
    SELECT INTO team_ids "team_id" FROM "tmp_team_list";

    UPDATE "team_prsnl"
    SET "updt_dt_tm" = NOW(), "last_access_dt_tm" = NOW()
    WHERE "team_id" IN team_ids;
END; $$ LANGUAGE plpgsql;

我希望team_ids是一个int的数组,然后我可以在UPDATE语句中使用它。这个函数给我这样的错误:

psql:functions.sql:62: ERROR:  syntax error at or near "team_ids"
LINE 13:  AND "team_id" IN team_ids;

2 个答案:

答案 0 :(得分:11)

使用FROM clause in your UPDATE statement

更快更简单
UPDATE team_prsnl p
SET    updt_dt_tm = now()
      ,last_access_dt_tm = now()
FROM   tmp_team_list t
WHERE  p.team_id = t.team_id;

除此之外,在使用数组操作时,WHERE子句必须是

WHERE team_id = ANY (team_ids)

IN构造适用于集合,而不适用于数组。

答案 1 :(得分:4)

SELECT创建数组:

# select array(  select id from tmp_team_list ) ;
 ?column? 
----------
 {1,2}
(1 row)

IN运算符为documented,为右侧操作数采用子查询。例如:

UPDATE team_prsnl SET updt_dt_tm = NOW()
 WHERE team_id IN (SELECT id FROM tmp_team_list);

也许您可以完全避免使用数组,或者尝试提供数组或select from team_ids