简体   繁体   中英

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

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. The loop variable then will contain arrays of the same type whatever[] , each containing a single element of the original array. If you choose SLICE 2 , the loop variable will contain arrays of size 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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