I can return id as an INSERT
result, like
INSERT INTO table(id,field) VALUES($id,$value) RETURNING id;
But i cannot return it and assign to variable into my function
var = INSERT INTO table(id,field) VALUES($id,$value) RETURNING id;
or
SELECT INTO var INSERT INTO table(id,field) VALUES($id,$value) RETURNING id;
don't work. How can i do it?
It can contain column names of the command's target table, or value expressions using those columns. A common shorthand is RETURNING * , which selects all columns of the target table in order. In an INSERT , the data available to RETURNING is the row as it was inserted.
A Postgres FUNCTION is always atomic (runs inside a single transaction wrapper) and cannot handle transactions. So COMMIT is disallowed.
A PROCEDURE can return values, but in a very limited fashion (as of Postgres 13). The manual on CALL : CALL executes a procedure. If the procedure has any output parameters, then a result row will be returned, containing the values of those parameters.
The UPSERT statement is a DBMS feature that allows a DML statement's author to either insert a row or if the row already exists, UPDATE that existing row instead. That is why the action is known as UPSERT (simply a mix of Update and Insert).
Try this:
INSERT INTO table(id,field) VALUES($id,$value) RETURNING id into var;
You could also use:
var := (INSERT INTO table(id,field) VALUES($id,$value) RETURNING id);
Readability is of course a personal preference, but I like this syntax because it shows an obvious assignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With