Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yet another stored procedure syntax error - IF-THEN-ELSE

Using postgresql 8.4, I'm trying to write a function, and it looks like this:

CREATE OR REPLACE FUNCTION addorupdate( smallint, varchar(7) ) RETURNS void AS
$$
BEGIN
 IF EXISTS (SELECT * FROM consist WHERE slave = $1) THEN
   UPDATE consist SET
    master = $2
    where slave = $1;
 ELSE
   INSERT INTO consist(slave, master) VALUES ( $2, $1 );
 END IF;
END;
$$
LANGUAGE SQL;

However, it fails like this:

ERROR:  syntax error at or near "IF"
LINE 4:  IF EXISTS (SELECT * FROM consist WHERE slave = $1) THEN

...and I've been wasting too much time and caffeine on figuring out why and could use someone with fresh eyes to help me out.

If it's not clear what i'm trying to achieve: slaves is a column of unique values. If it exists, UPDATE it with the current master. If not, INSERT.

UPDATE: Changed language to plpgsql, and it now throws:

ERROR:  language "plpgsql" does not exist

UPDATE:

CREATE LANGUAGE plpgsql;

(: RESOLVED :)

like image 877
Jarmund Avatar asked Oct 07 '22 04:10

Jarmund


1 Answers

Your language needs to be plpgsql not sql.

like image 177
Colin 't Hart Avatar answered Oct 09 '22 15:10

Colin 't Hart