I have a table named member
. I want to create a function that inserts a new email if it doesn’t exist in the table, and then return a boolean.
CREATE OR REPLACE FUNCTION
add_member(member_email TEXT)
RETURNS BOOLEAN AS
$$
BEGIN
IF NOT EXISTS (SELECT email FROM "community".member WHERE email = $1) THEN
INSERT INTO "community".member (email) VALUES ($1) RETURNING TRUE;
ELSE
RETURN FALSE;
END IF;
END;
$$
LANGUAGE PLPGSQL;
SELECT add_member('[email protected]');
I get this error ERROR: query has no destination for result data
.
Is the INSERT
not returning the expected data? Or wrapping it in another data type? Is this how you use the INSERT
with the returning?
2
Answers
read the docs
just do this in 2 statements.
or
Read Executing a Command with a Single-Row Result.
You need to DECLARE a variable to hold the RETURN of the insert.
Using
INSERT ... RETURNING ... INTO
from here:https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-ONEROW
DECLARE
thereturn_val
variable asboolean
and with default value ofFALSE
. Then do test for existing value and if present doINSERT
and update thereturn_val
variable with theTRUE
returning value from the insert. ThenRETURN return_val
which will beFALSE
if an existingmember_email
is found andTRUE
if one is not found.