简体   繁体   English

如何循环遍历 PostgreSQL 中的二维数组

[英]How can I loop over a 2d array in PostgreSQL

I am trying to loop over a 2D array getting the first and second value from each row to update a table我试图遍历一个二维数组,从每一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;

With help I got the function call right, which doesn't return errors anymore.在帮助下,我得到了正确的函数调用,它不再返回错误。 I don't understand how I can loop through the array getting the values within?我不明白如何遍历数组以获取其中的值? I've commented out the lines and I don't know what to do.我已经注释掉了这些行,但我不知道该怎么做。 I call the function within this line:我在这一行中调用函数:

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

There is an example in 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}

To try a verbal description: If the array of of type whatever[] and you loop with SLICE 1 , the array gets cut into slices of one element each.尝试口头描述:如果类型为whatever[]的数组并且您使用SLICE 1循环,则该数组将被切割成每个包含一个元素的切片。 The loop variable then will contain arrays of the same type whatever[] , each containing a single element of the original array.然后循环变量将包含相同类型的数组whatever[] ,每个数组包含原始数组的一个元素。 If you choose SLICE 2 , the loop variable will contain arrays of size 2.如果选择SLICE 2 ,循环变量将包含大小为 2 的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM