0

I'm facing an issue from yesterday and I can't understand why my SQL is not working.. This may be a simple error since i'm a beginner in SQL but I can't find where it is.

Here is what I try to do:

CREATE FUNCTION test() RETURN integer AS $$
BEGIN
    FOR i IN 1..5 LOOP
    SELECT * from result WHERE id=i;
end loop;
    RETURN 1;
END;
$$ LANGUAGE plpgsql;

This is just a simple loop as I can find in the documentation but I have this error:

Error report -
ERROR: syntax error at or near "RETURN" (this is the first RETURN statement in the function)

The database is in PostgreSQL and the version is 9.4.5

Why it's not working ?

4
  • This code does not make any sense to me. What exactly are you trying to do there? Why are you running the same query over and over again and then discarding the result? Commented Feb 14, 2020 at 8:44
  • Unrelated to your problem, but: Postgres 9.4 is no longer supported you should plan an upgrade as soon as possible. Commented Feb 14, 2020 at 8:45
  • @a_horse_with_no_name It's just to test the LOOP function, the main objective of my function is to migrate 6 columns from a table to another which is new, and add the foreign key referencing the new table into the old table, but as every statement I use makes errors I just try to made a simple loop and add my process after. Commented Feb 14, 2020 at 8:47
  • 1
    I think you have to type RETURNS with the final S. postgresql.org/docs/9.4/sql-createfunction.html Commented Feb 14, 2020 at 8:54

1 Answer 1

1

There are several problems, apart from the fact that the function isn't doing anything useful:

  • It must be RETURNS integer, not RETURN integer.

    That't what causes the error.

  • The SELECT has no destination. Either add an INTO clause or discard the result with

    PERFORM * from result WHERE id=i;
    
  • You should indent the code correctly, so that you can read and understand it.

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.