Search code examples
postgresqlstored-proceduresinsert-into

Insert a result from a stored procedure in postgresql


I'm trying to understand how to deal with procedures in Postgresql.

I get the idea of creating a function that returns a variable. What I don't get is how I can use such variable, for instance, in an insert.

Imagine this, I have a function called getName(), that returns a variable $name$.

What I want is to insert such variable in another table... How can I do this?


Solution

  • If the function returns a single value, you can use it anywhere a constant could be used.

    insert into some_table (id, name)
    values (42, get_name());
    

    this is the same as using a built-in function:

    insert into some_table (id, modified_at)
    values (42, now());
    

    It can be used the same way in an update statement

    update some_table
      set name = get_name()
    where id = 42;