为PL / PgSQL中的函数创建特定的异常

时间:2014-11-17 02:35:27

标签: postgresql triggers plpgsql

我正在尝试编写一个比较旧值和新值的sql触发器。如果这两个值不同,那么我需要显示一个错误,表示您无法更新名称。这就是我似乎遇到的问题,我不明白如何在PSQL中显示异常错误我的触发器的确切定义是

write a trigger function named disallow_team_name_update that compares the OLD and NEW records 
team fields. If they are different raise an exception that states that changing the team name is 
not allowed. 

我正在使用的表格是

  Table "table.group_standings"
    Column |         Type          | Modifiers
   --------+-----------------------+-----------
    team   | character varying(25) | not null
    wins   | smallint | not null   
    losses | smallint | not null
    draws  | smallint | not null
    points | smallint| not null
   Indexes:
     "group_standings_pkey" PRIMARY KEY, btree (team)
  Check constraints:
   "group_standings_draws_check" CHECK (draws >= 0)
   "group_standings_losses_check" CHECK (losses >= 0)
   "group_standings_points_check" CHECK (points >= 0)
   "group_standings_wins_check" CHECK (wins >= 0)

我现在的代码,我需要帮助告诉用户他们没有大声改变团队名称,但我遇到了问题。

 CREATE OR REPLACE FUNCTION disallow_team_name_update() RETURNS trigger AS $$
    BEGIN
            if(NEW.team <> OLD.team)
            /*tell the user to not change team names*/

    END;
$$ LANGUAGE plpgsql;


CREATE TRIGGER tr_disallow_team_name_update BEFORE INSERT OR UPDATE OF team ON group_standings 
FOR EACH ROW EXECUTE PROCEDURE disallow_team_name_update();

1 个答案:

答案 0 :(得分:0)

您需要RAISE statement来引发异常。手册中有一些例子。

RAISE EXCEPTION ....

(这看起来像是家庭作业,之前你曾经问过家庭作业,所以我故意不给出完整的答案)