将每个查询的结果推入数组

时间:2019-07-19 09:23:06

标签: plpgsql

我已经创建了函数:

CREATE FUNCTION citiesById(integer[]) RETURNS text[] AS
$$
DECLARE

element int;
result text[];

BEGIN
  FOREACH element IN ARRAY $1
   LOOP
     WITH t1 as (SELECT city FROM cities WHERE id = element)
     SELECT city FROM t1 INTO result;
   END LOOP;

RETURN result;

END

$$
LANGUAGE plpgsql;

我正在尝试循环执行查询,并将每个查询的结果插入数组以获取类似['London', 'Paris', 'Moscow']的内容。但是我遇到一个错误:

error

有正确的方法吗?

1 个答案:

答案 0 :(得分:0)

CREATE FUNCTION citiesById(integer[]) RETURNS text[] AS
$$
DECLARE

element int;
result text[];

BEGIN
  FOREACH element IN ARRAY $1
   LOOP
     result := array_append(result, (SELECT city FROM cities WHERE id = element)::text);
   END LOOP;

RETURN result;

END

$$
LANGUAGE plpgsql;