postgresql 在触发器函数中,是否可以使用可变字段名来读取新记录?

ar5n3qh5  于 2023-01-25  发布在  PostgreSQL
关注(0)|答案(1)|浏览(103)

在触发器函数中,我想使用一个变量(fieldName)从新记录中读取值。

DECLARE

_fieldName VARCHAR:='';
_fieldValue VARCHAR;

BEGIN 

_fieldName = 'field1';

_fieldValue =  new[_fieldName];

或者像这样
execute 'select NEW.$1', into _fieldValue using _fieldName;

这是解决方案:

execute 'select $1.' || _fieldName using NEW into _fieldValue;
jgwigjjp

jgwigjjp1#

如果要在触发器上使用动态字段名,请尝试以下示例:

CREATE TABLE books (
    id serial NOT NULL, 
    bookcode int4 NULL,
    bookname text NULL
);

CREATE TABLE books_log (
    id serial4 NOT NULL,
    bookcode text NULL
);

CREATE OR REPLACE FUNCTION books_before_insert()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
declare 
    v_field_name text;
    v_field_values text;
begin

    v_field_name = 'bookname';

    EXECUTE 'SELECT $1.' || v_field_name
    USING NEW
    INTO v_field_values;

    insert into books_log (bookcode) values (v_field_values);
  
    RETURN new;
end;
$function$
;

create trigger trigger_book_before_insert before
insert
    on
    public.books for each row execute function books_before_insert();

相关问题