触发以检查一个表中的重复值

时间:2016-11-20 11:10:21

标签: triggers

我有一个足球系统数据库,其中有一个表match

  • Match_ID int主键
  • Home_ID int(表Clubs的外键)
  • Visitor_ID int(表Clubs的外键)

我已经写了一个触发器来检查,我成功创建了但不是为了更新。

CREATE TABLE Clubs
(
    Club_ID int,
    Name varchar2(100),
    Stadium varchar2(100),
    League_ID int,
    primary key(Club_ID),
    foreign key(League_ID) references Leagues(League_ID)
)

CREATE TABLE Matches
(
    Match_ID int,
    Home_ID int,
    Visitor_ID int,
    Official_ID int,
    DateMatch date,

    primary key(Match_ID),
    foreign key(Home_ID) references Clubs(Club_ID),
    foreign key(Visitor_ID) references Clubs(Club_ID),
    foreign key(Official_ID) references Officials(Official_ID)
)

CREATE OR REPLACE TRIGGER Check_Duplicate
before insert or update on Matches
FOR each ROW
   declare v_dup number;
begin
    select count(Match_ID) INTO v_dup 
    from Matches 
    where :NEW.Home_ID =:NEW.Visitor_ID;

    if v_dup > 0 then
        Raise_Application_Error (-20100, 'This team already exists. The insert is cancelled.');
    end if;
end;

0 个答案:

没有答案