如何创建一个检查值的触发器?

时间:2014-05-04 19:01:18

标签: postgresql

我的触发器需要帮助。例如,我有像这样的查询

INSERT INTO test(id_users,id_type,id_color) VALUES(1,3,4);

在我的数据库中,我有一个名为test的表:test

ghost, id, id_users, id_type, id_color

我需要在插入或更新之前检查

Create trigger
Begin
select id from test where ghost = false and id_users = 26 and id_type = 3
if NO execute INSERT
if YEST exit with no action
END

我如何创建此触发器?

2 个答案:

答案 0 :(得分:1)

有两种方法,具体取决于您希望如何管理问题。

如果你想让它静音,请使用before触发器并返回null:

create function ignore_invalid_row() returns trigger as $$
begin
  if not exists(
     select 1
       from test
      where not ghost
        and id_users = new.id_users
        and id_type = new.id_type
     )
  then
    return null;
  end if;

  return new;
end;
$$ language plpgsql;

create trigger ignore_invalid_row_tg before insert on test
for each row execute procedure ignore_invalid_row();

如果您想提高它,请使用约束触发器并引发异常:

create function reject_invalid_row() returns trigger as $$
begin
  if not exists(
     select 1
       from test
      where not ghost
        and id_users = new.id_users
        and id_type = new.id_type
     )
  then
    raise exception 'message';
  end if;

  return null;
end;
$$ language plpgsql;

create constraint trigger reject_invalid_row_tg after insert on test
for each row execute procedure reject_invalid_row();

http://www.postgresql.org/docs/current/static/sql-createtrigger.html

答案 1 :(得分:0)

首先,您需要创建一个触发器功能,然后根据它创建触发器:

CREATE OR REPLACE FUNCTION my_trigger_function() RETURNS TRIGGER AS $BODY$ BEGIN
IF EXISTS (SELECT id FROM test WHERE ghost = false AND id_users = 26 AND id_type = 3) THEN
  return NEW;
ELSE
  return NULL;
END IF; END; $BODY$ LANGUAGE 'plpgsql';

然后,您可以根据此功能创建触发器:

CREATE TRIGGER t_my_trigger BEFORE INSERT ON test FOR EACH ROW EXECUTE PROCEDURE my_trigger_function();

有关触发器的更多信息,请参阅postgres docs