Gargoyle
Gargoyle

Reputation: 10324

Return ID of last inserted row in PostgreSQL with RETURNING clause

I've got a pretty simple function defined like so:

CREATE OR REPLACE FUNCTION create_new_order(....) RETURNS integer AS
$BODY$
BEGIN
    PERFORM add_points_to_usage(client_id_p, date_in_p, total_points_p);

INSERT INTO orders (...) VALUES (...)
    RETURNING ident;
END;
$BODY$ LANGUAGE plpgsql;

Where I'm struggling is how to actually RETURN the value stored in the ident field back via the RETURNING clause. I've tried setting the value to a variable but that either doesn't work or I'm just messing up the syntax.

Upvotes: 1

Views: 116

Answers (1)

Daniel Vérité
Daniel Vérité

Reputation: 61526

You're missing the variable declaration, the INTO clause and the final RETURN:

CREATE OR REPLACE FUNCTION create_new_order(....) RETURNS integer AS
$BODY$
DECLARE
  var_ident int;
BEGIN
    PERFORM add_points_to_usage(client_id_p, date_in_p, total_points_p);
    INSERT INTO orders (...) VALUES (...)
       RETURNING ident INTO var_ident;
    RETURN var_ident;
END;
$BODY$ LANGUAGE plpgsql;

Upvotes: 1

Related Questions