Frage

I'm basically trying to return the updated id from the following function. The following is a simplified version of my code:

CREATE FUNCTION confirmUser(_token varchar(255)) RETURNS integer AS $$
BEGIN
   return (UPDATE users SET isConfirmed = true where _token = token RETURNING id));
END;
$$ LANGUAGE plpgsql;

What is wrong with this?

War es hilfreich?

Lösung

I don't think you can return the value like that. You need to store it into a variable and then return that variable:

CREATE FUNCTION confirmUser(_token varchar(255)) RETURNS integer 
AS 
$$
declare
   _id integer;
BEGIN
   UPDATE users SET isConfirmed = true where _token = token 
   RETURNING id
   into _id;

   return _id;
END;
$$ 
LANGUAGE plpgsql;

But you don't need a PL/pgSQL function for this. A plain SQL function will do just as well:

CREATE FUNCTION confirmUser(_token varchar(255)) RETURNS integer 
AS 
$$
   UPDATE users SET isConfirmed = true where _token = token 
   RETURNING id
$$ LANGUAGE sql;

But you have to make sure that token is unique, otherwise this will fail.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top