42883 ERROR: operator does not exist: record -> unknown

42883 ERROR: operator does not exist: record -> unknown

我如何调用函数:

SELECT opportunity_price_total(($$
        [{"value_price": 10, "value_period": {"value_period_id": 1}},{"value_price": 1, "value_period": {"value_period_id": 2}},{"value_price": 10, "value_period": {"value_period_id": 4}}]
    $$)::jsonb);

opportunity_price_total函数:

CREATE FUNCTION opportunity_price_total(prices jsonb) RETURNS BIGINT
    LANGUAGE plpgsql
AS
    $$
        DECLARE
            price record;
            total_annually BIGINT = 0;
        BEGIN
            FOR price IN SELECT * FROM jsonb_array_elements(prices) LOOP
                total_annually := total_annually + opportunity_price_annually((price->'value_price')::bigint,(price->'value_period'->>'value_period_id')::int);
            END LOOP;
            RETURN total_annually;
        END
    $$;

我得到的输出是:

[42883] ERROR: operator does not exist: record -> unknown

我应该如何解决问题?

您不能在 record(复合类型)上使用 -> 运算符。您要么必须先获得适当的列。最好对循环变量使用 jsonb

DECLARE
    price jsonb;
    total_annually BIGINT := 0;
BEGIN
    FOR price IN
        SELECT x FROM jsonb_array_elements(prices) AS j(x)
    LOOP
        total_annually := total_annually +
               opportunity_price_annually(
                   (price->'value_price')::bigint,
                   (price->'value_period'->>'value_period_id')::int
               );
    END LOOP;
    RETURN total_annually;
END