我正在使用PostgreSQL 8.4
并编写如下函数。我遇到了一个问题,如何将结果集转换为数组。我的意思是,假设我有一个查询只返回一个整数类型的列,比如
SELECT amount from daily_profit;
我一直在尝试写以下内容:
CREATE OR REPLACE FUNCTION fill_daily_profit() RETURNS void AS $$
DECLARE
arr integer[] := cast ((SELECT amount from partner.daily_profit) as integer[]);
-- doesn't work, the following error was produced:
-- cannot cast type integer to integer[]
BEGIN
END $$
LANGUAGE plpgsql;
有什么想法吗?
答案 0 :(得分:3)
我建议使用更简单,更快速的 ARRAY constructor :
CREATE OR REPLACE FUNCTION fill_daily_profit()
RETURNS void AS
$func$
DECLARE
arr integer[] := ARRAY (SELECT amount FROM partner_daily_profit);
BEGIN
...
END
$func$ LANGUAGE plpgsql;
如果您想要特定订单中的元素,请向ORDER BY
添加SELECT
子句。
然而,通常会有一个基于集合的解决方案,无需先验地保留对此类阵列的需求。
答案 1 :(得分:2)
您需要将值聚合到一个数组中:
CREATE OR REPLACE FUNCTION fill_daily_profit() RETURNS void AS $$
DECLARE
arr integer[];
BEGIN
select array_agg(amount)
into arr
from partner_daily_profit;
END $$
LANGUAGE plpgsql;