如何分配和提取 RECORD 类型中定义的 table 值

How to assign and extract table values defined in RECORD type

这里是示例代码

CREATE TYPE entity AS
(
    record_init boolean,
    b_modified boolean,
    custom_name character varying(8000),
    customer_rec customer,     --- customer is a table 
    lang_pref boolean,
)
do 
$$
declare 
entity_rec entity;
Begin

    entity_rec.record_init := TRUE;
    entity_rec.customer_rec.customer_id := 100;
    raise notice ' Customer Id is %', entity_rec.customer_rec.customer_id;
end;
$$;

从 entity_rec.customer_rec

引用 customer_id 时出错

PLpgSQL 不支持赋值语句左侧的复杂表达式。您应该将此操作划分为更多操作(此问题已在准备好的 PostgreSQL 14 中修复):

DECLARE
  entity_rec entity;
  customer_rec customer;
BEGIN
  entity_rec.record_init := TRUE;
  customer_rec.customer_id := 100;
  entity_rec.customer_rec := customer_rec;
  raise notice ' Customer Id is %', entity_rec.customer_rec.customer_id;
END;

第二个问题可能是取消引用嵌套记录。 Postgres 默认使用模式 schema.table.name。使用嵌套复合值时,应使用括号:

postgres=# do $$
DECLARE
  entity_rec entity;
  customer_rec customer;
BEGIN
  entity_rec.record_init := TRUE;
  customer_rec.customer_id := 100;
  entity_rec.customer_rec := customer_rec;
  raise notice ' Customer Id is %', entity_rec.customer_rec.customer_id;
END;
$$;
ERROR:  missing FROM-clause entry for table "customer_rec"
LINE 1: SELECT entity_rec.customer_rec.customer_id
               ^
QUERY:  SELECT entity_rec.customer_rec.customer_id
CONTEXT:  PL/pgSQL function inline_code_block line 9 at RAISE

正确:

postgres=# do $$
DECLARE
  entity_rec entity;
  customer_rec customer;
BEGIN
  entity_rec.record_init := TRUE;
  customer_rec.customer_id := 100;
  entity_rec.customer_rec := customer_rec;
  raise notice ' Customer Id is %', (entity_rec).customer_rec.customer_id;
END;
$$;
NOTICE:   Customer Id is 100
DO