我正在尝试编写一个比较旧值和新值的SQL触发器。如果这两个值不同,那么我需要显示一个错误,表示您无法更新名称。我的触发器的确切定义是
编写一个名为disallow_team_name_update的触发函数进行比较 OLD和NEW记录团队字段。如果他们是不同的提高 表示不允许更改团队名称的例外情况。 然后,将此触发器附加到名为tr disallow team的表中 名称更新并指定在任何可能的更新之前触发 表中的团队领域。
我正在使用的表格是:
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();
答案 0 :(得分:3)
PostgreSQL可以使用raise exception
来引发异常。
CREATE OR REPLACE FUNCTION disallow_team_name_update()
RETURNS trigger AS
$$
BEGIN
if(NEW.team <> OLD.team) then
raise exception 'Invalid update.'
using hint = 'Changes to team name are not allowed.';
end if;
END
$$
LANGUAGE plpgsql;
您肯定不希望禁止对 insert 上的团队名称进行更改。 (无论如何,PostgreSQL都不允许你这样做。)
CREATE TRIGGER tr_disallow_team_name_update
BEFORE UPDATE OF team ON group_standings
FOR EACH ROW EXECUTE PROCEDURE disallow_team_name_update();