使用IF ELSE时Postgresql触发器失败

时间:2018-10-14 14:03:51

标签: postgresql triggers

我有这段代码(实际上有效):

    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;

当我改用IF ELSE时实际上失败了:

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;

,出现以下错误:

  

错误:输入结尾的语法错误

     

第21行:$ checkRank $语言plpgsql;

任何人都知道发生了什么问题,我无法通过Google知道...

1 个答案:

答案 0 :(得分:1)

您需要使用ELSIF而不是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具有三种形式的IF:

     
      
  • 如果...然后...如果...结束

  •   
  • 如果...然后...否则...结束...如果

  •   
  • 如果...则... ELSIF ... THEN ... ELSE ...结束如果

  •