Search code examples
sqlpostgresqlsql-insertplpgsqlsql-function

Use Record As Function Argument in RETURNING Statement


I have a plpgsql function that takes a record as an argument.

I would like to call this function in the RETURNING statement of an insert, but am unsure what to put as the argument (* does not work) i.e.,

-- Postgres 12

INSERT INTO some_table (a, b, c)
VALUES .....
RETURNING
function_that_takes_record_argument(<the_new_record>)

What can I use in place of <the_new_record>?


Solution

  • To pass a record/row to a function you need to explicitly specify the record type:

    create table t(a int, b text);
    
    create or replace function f(r record) returns int language plpgsql as $$
    begin
        return r.a;
    end $$;
    
    insert into t values(2, 'b');
    
    select f(t.*), f(t), f((a,b)::t) from t;
    
     f | f | f 
    ---+---+---
     2 | 2 | 2
    
    insert into t values(3, 'c') returning f(t);
    
     f 
    ---
     3