0

I'm getting the ERROR: syntax error at or near "IF" error form the following sample code.

Note: I did replace the queries to ease complexity.

CREATE OR REPLACE FUNCTION get_return_dev(
"Title" character varying,
"ID" character varying)
RETURNS x_returntype AS $$

select item from table1

IF NOT found THEN
select item from table2
END IF;
$$

Any suggestion would help!

2
  • I would expect a begin/``end` block as well as a return statement. Commented Jul 12, 2015 at 20:40
  • Instead of scaring away a new user with down votes or off-the-cuff comments, why not help the guy on his way? Commented Jul 13, 2015 at 1:15

1 Answer 1

3

You seem to be confused about the language of the function. You structure the function as if it is a SQL language function (no BEGIN \ END statements), but you use elements of the PL/pgSQL language. Since you obviously need the additional features of PL/pgSQL (conditional branching), I would suggest that you start by learning how a PL/pgSQL function is structured.

A SELECT statement returning a single row inside of a PL/pgSQL function needs a target to store its result.

If you need to return a result from a function, you need a RETURN statement inside the function body.

CREATE OR REPLACE FUNCTION get_return_dev(
  "Title" character varying,
  "ID" character varying)
  RETURNS x_returntype AS $$
DECLARE
  item_var   same_type_as_item_column;
  return_var x_returntype;
BEGIN
  SELECT item INTO item_var FROM table1;

  IF NOT found THEN
    SELECT item INTO item_var FROM table2;
  END IF;

  -- Do your processing
  ...
  return_var := ...;

  RETURN return_var;
END
$$ LANGUAGE plpgsql;
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.