Andrés Rivas
Andrés Rivas

Reputation: 153

returning value from execute query string in plpgsql

I'm trying to return an ID from a function like this:

CREATE OR REPLACE FUNCTION fx (myTable text, myValue text) returns int
as $$
DECLARE
  sqlQuery TEXT;
  resultId INT;
BEGIN
  sqlQuery :=
    'INSERT INTO '
    || myTable || ' (id, some_column) values'
    || ' ('
    || 'nextval(' ||  quote_literal('seq_' || myTable) || ')'
    || ',' || myValue
    || ') RETURNING id INTO ' || resultId;

  EXECUTE sqlQuery;
  RETURN resultId;

END;
$$
LANGUAGE plpgsql;

select fx('some_table', 'some_value');

But is not working.

How can I get this ID from sql query string executed?

Upvotes: 2

Views: 3439

Answers (1)

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125434

create or replace function fx (mytable text, myvalue text)
returns int as $body$
declare
    sqlquery text;
    resultId int;
begin

    sqlquery := format ($$
        insert into %I (id, some_column) values ($1, $2)
        returning id
        $$, mytable
    );
    execute sqlquery
        into resultId
        using nextval('seq_' || mytable), myvalue;
    return resultId;

end;
$body$ language plpgsql;

Use %I format specifier to pass identifiers and execute using to pass data parameters.

Upvotes: 2

Related Questions