1

I have this piece of code (which actually works):

    CREATE or replace FUNCTION checkRank() RETURNS trigger AS $checkRank$

    DECLARE
    old_rank varChar;
    old_date date;

    BEGIN 

--  SELECT a.rank INTO old_rank from RANK a where a.account = new.account;
    SELECT a.rank, a.date INTO old_rank, old_date from RANK a where a.account = new.account order by date desc LIMIT 1;

        -- Check if inserted rank != current rank           
        if old_rank = new.rank THEN
            RAISE EXCEPTION 'rank unchanged';
        END IF;
                if new.date < old_date THEN
            RAISE EXCEPTION 'old rank';
        END IF;

        RETURN NEW;
    END
$checkRank$ LANGUAGE plpgsql;

which actually fails when I use an IF ELSE instead:

CREATE or replace FUNCTION checkRank() RETURNS trigger AS $checkRank$

    DECLARE
    old_rank varChar;
    old_date date;

    BEGIN 

--  SELECT a.rank INTO old_rank from RANK a where a.account = new.account;
    SELECT a.rank, a.date INTO old_rank, old_date from RANK a where a.account = new.account order by date desc LIMIT 1;

        -- Check if inserted rank != current rank           
        IF old_rank = new.rank THEN
            RAISE EXCEPTION 'rank unchanged';
        ELSE IF new.date < old_date THEN
            RAISE EXCEPTION 'old rank';
        ELSE
        RETURN NEW;
        END IF;
    END
$checkRank$ LANGUAGE plpgsql;

with the following error:

ERROR: syntax error at end of input

LINE 21: $checkRank$ LANGUAGE plpgsql;

Anyone has a clue what's going wrong, I can't figure it out with Google...

1 Answer 1

1

You need to use ELSIF instead of ELSE IF:

IF old_rank = new.rank THEN
    RAISE EXCEPTION 'rank unchanged';
ELSIF new.date < old_date THEN
    RAISE EXCEPTION 'old rank';
ELSE
    RETURN NEW;
END IF;

db<>fiddle demo


41.6.2. Conditionals

PL/pgSQL has three forms of IF:

  • IF ... THEN ... END IF

  • IF ... THEN ... ELSE ... END IF

  • IF ... THEN ... ELSIF ... THEN ... ELSE ... END IF

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.