如何在PostgreSQL中循环2d数组

时间:2017-12-06 10:41:34

标签: arrays postgresql

我正在尝试遍历2D数组,从每个row获取第一个和第二个值来更新表

CREATE OR REPLACE FUNCTION fc_update_arrangement(input_arrangementid int, input_NAME text, input_price money, input_expirationdate date, products int[][])
RETURNS void AS
$BODY$
BEGIN
update arrangement set "NAME" = $2, price = $3, expirationdate = $4 where arrangementid = $1;
-- loop through array getting the first and second value
-- update productinarrangement set amount = arrayinputnumber2 where productid = arrayinputnumber1 and arrangementid = $1
END;
$BODY$ LANGUAGE plpgsql STRICT;

在帮助下我得到了函数调用权限,它不再返回错误。我不明白我如何循环数组获取值?我已经注释掉了这些线条,我不知道该怎么做。我在这一行中调用该函数:

select fc_update_arrangement(1::int, 'tom'::text, 15::money, now()::date, array[ array[1,2], array[3,4] ]);

1 个答案:

答案 0 :(得分:0)

the documentation中有一个例子:

CREATE FUNCTION scan_rows(int[]) RETURNS void AS $$
DECLARE
  x int[];
BEGIN
  FOREACH x SLICE 1 IN ARRAY $1
  LOOP
    RAISE NOTICE 'row = %', x;
  END LOOP;
END;
$$ LANGUAGE plpgsql;

SELECT scan_rows(ARRAY[[1,2,3],[4,5,6],[7,8,9],[10,11,12]]);

NOTICE:  row = {1,2,3}
NOTICE:  row = {4,5,6}
NOTICE:  row = {7,8,9}
NOTICE:  row = {10,11,12}