1

I am trying to create a function to update the password of an user. Here is my function.

CREATE OR REPLACE FUNCTION update_user(userid int, upassword text) RETURNS integer AS  $$
    BEGIN
 UPDATE tbl_user 
     SET password= upassword 
 WHERE user_id = userid;
 SELECT 1;
 END;
 $$
 LANGUAGE plpgsql;

And I tried to execute this functions using.

SELECT update_user(1, 'test');

I got an error as

ERROR:  control reached end of function without RETURN CONTEXT:  PL/pgSQL function

I'm not sure where I go wrong. Please help me on this. I'm new to creating functions. Thanks in advance.

3
  • You say the function RETURNS integer, but you don't tell it what to return. What do you expect it to do? Commented Mar 27, 2014 at 3:47
  • Thanks, I have added "SELECT 1;" before "END;", the functions got execution and the password has been updated. Can you help me to capture the affected rows so that i would pass it a return value for validation. Commented Mar 27, 2014 at 3:56
  • It's in the manual - see GET DIAGNOSTICS. But I really don't understand why you're wrapping the statement in a function like this, rather than just doing that directly in the call site. Commented Mar 27, 2014 at 3:59

1 Answer 1

3

Every PL/pgSQL function needs a RETURN statement. But in your case you can do with a SQL language function:

CREATE OR REPLACE FUNCTION update_user(userid int, upassword text) RETURNS void AS $$
  UPDATE tbl_user 
    SET password = upassword 
    WHERE user_id = userid;
$$ LANGUAGE sql;

Only when you need to do more elaborate processing (for instance, using local variables, processing logic, or a trigger) do you need a PL/pgSQL function.

Sign up to request clarification or add additional context in comments.

1 Comment

Or just redefine your function as RETURNS VOID.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.