Trigger with dynamic field name

后端 未结 3 661
别跟我提以往
别跟我提以往 2020-12-19 09:35

I have a problem on creating PostgreSQL (9.3) trigger on update table. I want set new values in the loop as

EXECUTE \'NEW.\'|| fieldName || \':=\'\'some prep         


        
3条回答
  •  梦毁少年i
    2020-12-19 10:17

    Your problem is that EXECUTE can only be used to execute SQL statements and not PL/pgSQL statements like the assignment in your question.

    You can maybe work around that like this:

    Let's assume that table testtab is defined like this:

    CREATE TABLE testtab (
       id integer primary key,
       val text
    );
    

    Then a trigger function like the following will work:

    BEGIN
       EXECUTE 'SELECT $1.id, ''prefix '' || $1.val' INTO NEW USING NEW;
       RETURN NEW;
    END;
    

    I used hard-coded idand val in my example, but that is not necessary.

提交回复
热议问题