postgresqlvariable-assignmentplpgsqldynamic-sql

How to assign selected values from a table to specific variables in Pl/pgSQL?


For example, here is what I am trying to accomplish:

EXECUTE 'SELECT name, address INTO variable1, variable2
         FROM employee WHERE id=1';

Solution

  • Better alternative

    Actually, there is nothing indicating a need for dynamic SQL. All identifiers are stable. Assuming you only want to parameterize the id value, simplify to:

    SELECT name, address FROM employee WHERE id = $1
    INTO   variable1, variable2
    

    Or:

    SELECT INTO variable1, variable2
                e.name,    e.address
    FROM   employee e
    WHERE  e.id = _my_variable;
    

    The according chapter in the manual: "Executing a Query with a Single-row Result"

    Dynamic SQL would be indicated when working with parameterized table or column names.
    Here is a list of related question for dynamic SQL

    Cause for immediate problem

    The reason why your original code did not work, per documentation:

    SELECT INTO is not currently supported within EXECUTE; instead, execute a plain SELECT command and specify INTO as part of the EXECUTE itself.

    a_horse demonstrates valid syntax in his answer.

    Either alternative relies on the query to return a single row. If your id is defined unique, that cannot break.