1

I am trying to create a very simple PostgreSQL function, though I keep getting a very strange syntax error. The syntax I use is different from anything I have seen online (though this is the one the textbook uses), and thus I can't figure out why it fails...

This is the SQL:

CREATE OR REPLACE FUNCTION gsum(graphID integer)
    RETURNS integer
    BEGIN
        DECLARE total integer DEFAULT 0
        SELECT sum(weight) INTO total
        FROM Edge
        WHERE gno = graphID
    RETURN total;
    END;

The error is:

ERROR:  syntax error at or near "BEGIN"
LINE 3:  BEGIN
         ^
********** Error **********

ERROR: syntax error at or near "BEGIN"
SQL state: 42601
Character: 68
1
  • Your syntax looks like PSM - but it is wrong in PostgreSQL - There more languages than one are supported (and it needs little bit strange syntax for CREATE FUNCTION). PLpgSQL is based on ADA language - or more on PL/SQL - what is simplified ADA. Commented Jul 17, 2014 at 5:11

3 Answers 3

2

Your basic mistakes:

  • DECLARE must come before BEGIN.
  • Statements need to be terminated with ;.
  • Function body of a plpgsql function is a string and needs to be quoted. Use dollar-quoting to avoid complications with quotes in the body.
  • Missing keyword AS.
  • Missing language declaration LANGUAGE plpgsql.
  • Type mismatch.
  • You don't need a default.
  • This would still return NULL if the sum is NULL.

CREATE OR REPLACE FUNCTION gsum(graphID integer)
  RETURNS integer AS
$func$
DECLARE
   total integer;
BEGIN
   SELECT sum(weight)::int INTO total
   FROM   edge
   WHERE  gno = graphID;

   RETURN COALESCE(total, 0);
END
$func$ LANGUAGE plpgsql;

And you'd better use a simple SQL function for this like @Clodoaldo advised. Just add COALESCE().

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

Comments

1

It can be plain SQL in instead of plpgsql

create or replace function gsum(graphid integer)
returns bigint as $$

    select sum(weight) as total
    from edge
    where gno = graphid;

$$ language sql;

Notice that if weight is integer sum will return bigint not integer.

2 Comments

Is it possible to accomplish the task with the type of syntax I use?
@byteSlayer Check Erwin's answer
0
CREATE OR REPLACE FUNCTION  gsum(graphID integer)
    RETURNS integer AS
    $BODY$        
DECLARE 
    total integer DEFAULT 0;
    BEGIN

        SELECT sum(weight) INTO total
        FROM Edge
        WHERE gno = graphID;
    RETURN total;
    END;
    $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

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.