填充多维数组 [英] Populate multidimensional array

查看:99
本文介绍了填充多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在PostgreSQL上填充多维数组,但是它不起作用.在我的代码下面:

I'm trying populate a multidimensional array on PostgreSQL, but it not work. Below my code:

CREATE OR REPLACE FUNCTION teste()
  RETURNS void AS
$BODY$
DECLARE
    tarifas NUMERIC[7][24];
    a INTEGER;
    b INTEGER;

    BEGIN
        FOR a IN 0..6 LOOP
            RAISE NOTICE 'TESTE TESTE %', a;
            FOR b IN 0..23 LOOP
                RAISE NOTICE 'tarifas[%][%] = 0;', a, b;
                tarifas[a][b] = 0;
            END LOOP;
        END LOOP;
    END
$BODY$
  LANGUAGE plpgsql VOLATILE;

推荐答案

Postgres正是出于该目的具有专用功能:

Postgres has a dedicated function for that purpose exactly: array_fill():

返回一个使用提供的值和维初始化的数组, 可选的下限不是1

returns an array initialized with supplied value and dimensions, optionally with lower bounds other than 1

使用它:

CREATE OR REPLACE FUNCTION teste()
  RETURNS void AS
$func$
DECLARE
    tarifas numeric[7][24] := array_fill(0, ARRAY[7,24]);
    a int;
    b int;
BEGIN
   -- do something
END
$func$  LANGUAGE plpgsql;

注释

    numeric[7][24]中的
  • 数组维只是文档. 手册:
  • Notes

    • Array dimensions in numeric[7][24] are just documentation. The manual:
    • 当前实现不强制声明的数量 尺寸.特定元素类型的数组都是 不论大小或数量,均被视为同一类型 方面.因此,声明数组的大小或维数 CREATE TABLE只是文档.它不会影响运行时行为.

      The current implementation does not enforce the declared number of dimensions either. Arrays of a particular element type are all considered to be of the same type, regardless of size or number of dimensions. So, declaring the array size or number of dimensions in CREATE TABLE is simply documentation; it does not affect run-time behavior.

      • 关于plpgsql中的赋值运算符: := =:

        通常不可能直接写入数组元素.您可以串联或附加/前置元素.或整体分配一个数组. 手册中的详细信息.但是这样的声明是不可能的:

        It's generally not possible to write to an array element directly. You can concatenate or append / prepend elements. Or assign an array as a whole. Details in the manual. But a statement like this is not possible:

        tarifas[%][%] = 0

      • 数组的默认下限是1,而不是0.但是您可以定义任意数组维.示例:

      • Default lower bound of an array is 1, not 0. But you can define arbitrary array dimension. Example:

        SELECT '[2:3][2:4]={{7,7,7},{7,7,7}}'::int[]
        

      • 这篇关于填充多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆