Re: ERROR: syntax error at or near "IF"... why? - Mailing list pgsql-general

From Sam Mason
Subject Re: ERROR: syntax error at or near "IF"... why?
Date
Msg-id 20090501131021.GK12225@frubble.xen.chris-lamb.co.uk
Whole thread Raw
In response to ERROR: syntax error at or near "IF"... why?  (DaNieL <daniele.pignedoli@gmail.com>)
List pgsql-general
On Wed, Apr 29, 2009 at 07:54:20AM -0700, DaNieL wrote:
> ERROR:  syntax error at or near "IF"
>
> Where am i mistaken?
>
> p.s: dont focus on the example functionality, its just a trial for me
> to understand the transactions.. and now, the IF clause...

As others have said, IF statements are only valid in plpgsql functions,
not in plain SQL.  Probably not relevant but in this example can work
around it by doing something like:

  CREATE FUNCTION failif(BOOL,TEXT) RETURNS VOID AS $$
    BEGIN IF $1 THEN RAISE EXCEPTION '%', $2; END IF; END $$ LANGUAGE plpgsql;

  BEGIN;
  INSERT INTO ...
  UPDATE ...
  UPDATE ...
  SELECT failif((SELECT credit FROM users WHERE name = 'mary') < 0,
                'error, credit can't be less than zero');
  COMMIT;

In general, you're probably better off writing the whole thing in
plpgsql.

Hope that helps.

--
  Sam  http://samason.me.uk/

pgsql-general by date:

Previous
From: Bill Moran
Date:
Subject: Re: Re: Mapping output from a SEQUENCE into something non-repeating/colliding but random-looking?
Next
From: Tom Lane
Date:
Subject: Re: Connecting to a postgreSQL database with windows CE over wi-fi; failing gracefully