簡體   English   中英

如何循環遍歷 PostgreSQL 中的二維數組

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

我試圖遍歷一個二維數組,從每一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] ]);

文檔中有一個例子:

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}

嘗試口頭描述:如果類型為whatever[]的數組並且您使用SLICE 1循環,則該數組將被切割成每個包含一個元素的切片。 然后循環變量將包含相同類型的數組whatever[] ,每個數組包含原始數組的一個元素。 如果選擇SLICE 2 ,循環變量將包含大小為 2 的數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM