Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL plpgsql - variable column names

I am creating a trigger, which uses dynamic names for columns

NEW.name:=2222; -- works fine !

but

dynamic_column:='name';
EXECUTE '$1.'||dynamic_column||':=2222 ' USING NEW; -- raises error

gives an error:

ERROR: syntax error at or near "$1" LINE 1: $1.name:=2222

like image 479
vencedor Avatar asked Jul 21 '17 06:07

vencedor


People also ask

How do I assign a variable in Plpgsql?

An assignment of a value to a PL/pgSQL variable is written as: variable { := | = } expression ; As explained previously, the expression in such a statement is evaluated by means of an SQL SELECT command sent to the main database engine.

What is $$ in PostgreSQL?

It can be used to replace single quotes enclosing string literals (constants) anywhere in SQL scripts. The body of a function happens to be such a string literal. Dollar-quoting is a PostgreSQL-specific substitute for single quotes to avoid escaping of nested single quotes (recursively).

Can you use variables in PostgreSQL?

PL/pgSQL variables can have any SQL data type, such as integer , varchar , and char . Here are some examples of variable declarations: user_id integer; quantity numeric(5); url varchar; myrow tablename%ROWTYPE; myfield tablename.

How do you assign a selected value to a variable in PostgreSQL?

In PostgreSQL, the select into statement to select data from the database and assign it to a variable. Syntax: select select_list into variable_name from table_expression; In this syntax, one can place the variable after the into keyword.


1 Answers

I found info here: Assign to NEW by key in a Postgres trigger

If we enable the module hstore by:

CREATE EXTENSION hstore;

We can do this:

dynamic_column:='name';    
temp_sql_string:='"'||dynamic_column||'"=>"2222"';
NEW := NEW #= temp_sql_string::hstore;

And the RECORD NEW.name now is set to the value 2222.

Thank you tough for making an effort to find a solution @Laurenz Albe

like image 91
vencedor Avatar answered Oct 10 '22 12:10

vencedor