0

I'm trying to create a function which returns either X rows or 0 rows.

This is my code:

    ...
    IF var != '' THEN
        RETURN var;
    ELSE
        RETURN NULL;
    END IF;
END;
$$
LANGUAGE 'plpgsql';

If I do:

    ...
    IF var != '' THEN
        RETURN var;
    ELSE
        RETURN;
    END IF;
END;
$$
LANGUAGE 'plpgsql';

I get the error:

ERROR:  missing expression at or near ";"
LINE 19: RETURN;
6
  • does it return void?.. Commented Jan 20, 2017 at 13:03
  • It returns text: RETURNS text AS $$ Commented Jan 20, 2017 at 13:07
  • Please show us the complete code Commented Jan 20, 2017 at 13:07
  • I'm unable to, as StackOVerflow denies the update. Says there's more code than text. Commented Jan 20, 2017 at 13:11
  • did you declare output variables?.. I mean you cant return without anything if you did not Commented Jan 20, 2017 at 13:12

1 Answer 1

4

A normal function like the one you defined (RETURNS text) will always return exactly one value.

So unless the function is defined as RETURNS void, you'll have to return a value, i.e. you cannot use RETURN; without an argument.

If you want to return a different number of rows (0 or a number greater than 1), you need a set returning function.

Such a function is declared as RETURNS SETOF text (or some other type), and from inside the function you use RETURN NEXT val; to add a row to the function output and RETURN; without argument to terminate execution.

Such a function can be used like a table in queries.

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

Comments

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.