【问题标题】:is it possible tu use variable field name for read new record in a trigger function?是否可以在触发器函数中使用变量字段名称来读取新记录?
【发布时间】:2023-01-20 03:26:00
【问题描述】:

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

DECLARE

_fieldName VARCHAR:='';
_fieldValue VARCHAR;


BEGIN 

_fieldName = 'field1';


_fieldValue =  new[_fieldName];

或者像这样

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

【问题讨论】:

标签: postgresql


【解决方案1】:

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

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();

【讨论】:

    猜你喜欢
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    相关资源
    最近更新 更多