在 pl/pgsql 函数中动态访问 RECORD 值

Dynamically access RECORD value in pl/pgsql function

为什么像这样访问 RECORD 参数的值有效:

CREATE OR REPLACE FUNCTION TT_GetVal1(a RECORD)
RETURNS text AS $$
  DECLARE
  BEGIN
    RETURN a.val1::text;
  END;
$$ LANGUAGE plpgsql VOLATILE;

SELECT TT_GetVal1(foo.*)
FROM (SELECT 1 id, 'a' val1) foo;

但不是这样的:

CREATE OR REPLACE FUNCTION TT_GetVal2(a RECORD)
RETURNS text AS $$
  DECLARE
    query text;
    result text;
  BEGIN
    query = 'SELECT ().val1::text';
    EXECUTE query INTO result USING a;
    RETURN result;
  END;
$$ LANGUAGE plpgsql VOLATILE;

SELECT TT_GetVal2(foo.*)
FROM (SELECT 1 id, 'a' val1) foo;

哪个returns:

ERROR:  could not identify column "val1" in record data type
LINE 1: SELECT ().val1::text

如何动态访问 RECORD 值?

RECORD 仅存在于 plpgsql 范围内。这些值被传递给执行而不是列名。

你可以 - 如果记录来自 table - 做这样的事情:

create table table1 (
  id integer,
  val1 text
 );

CREATE OR REPLACE FUNCTION TT_GetVal2(a RECORD)
RETURNS text AS $$
  DECLARE
    query text;
    result text;
  BEGIN
    query = 'SELECT (::text::table1).val1';
    EXECUTE query INTO result USING a;
    RETURN result;
  END;
$$ LANGUAGE plpgsql VOLATILE;

SELECT TT_GetVal2(foo)
FROM (SELECT 1 id, 'a' val1) foo;

此致,
比亚尼