简体   繁体   中英

Check constraint in database db2

I'm designing a database that has, amongst others, the following entities:

create table Director(
    ID integer not null,
    YearsExperience integer not null,
    StudioAffiliation varchar(30),
    NetWorth REAL,
    primary key (ID)
);

create table Movie(
    ID varchar(20) not null,
    Title varchar(40) not null,
    Genre char(1) not null,
    ReleaseDate date not null,
    Earning real not null,
    primary key (ID)
);

Now Director and Movie have 2 relationship: Direct and WonAward. The later is to record whether a director has won an award or more with the movie he/she directed:

create table Directs(
    DirectorID integer not null,
    MovieID varchar(20) not null,
    primary key (DirectorID, MovieID),
    foreign key (DirectorID) references Director (ID) on delete cascade,
    foreign key (MovieID) references Movie (ID) on delete cascade
);

create table WonAward(
    DirectorID integer not null,
    MovieID varchar(20) not null,
    AwardName varchar(30) not null,
    Year integer not null,
    Budget REAL not null,
    primary key (DirectorID, MovieID),
    foreign key (DirectorID) references Director (ID) on delete cascade,
    foreign key (MovieID) references Movie (ID) on delete cascade
);

I need to make sure that a Director gets awards for only movies he/she has directed. Now I have tried using Check to achieve that but it keeps giving me error for the following 2 condition at the end of the WonAward relationship:

check (DirectorID = (SELECT DirectorID FROM Directs WHERE Directs.MovieID = MovieID)),
 check (MovieID = (SELECT MovieID FROM Directs WHERE Directs.DirectorID = DirectorID))

This is the error I keep getting:

DB21034E  The command was processed as an SQL statement because it was not a 
valid Command Line Processor command.  During SQL processing it returned:
SQL0548N  A check constraint or generated column that is defined with "SELECT" 
is invalid.  SQLSTATE=42621

Without these constraints I found out that a user can enter into a database an award won for a director for a movie that wasn't directed by them. How can I make this happen?

You cannot create check constraints that query data outside the row in question. What you could do is create a BEFORE TRIGGER to verify the conditions are met. There are some examples in the CREATE TRIGGER documentation that could be customized to your needs.

Define a foreign key from WonAward to Directs , instead:

create table WonAward(
    DirectorID integer not null,
    MovieID varchar(20) not null,
    AwardName varchar(30) not null,
    Year integer not null,
    Budget REAL not null,
    primary key (DirectorID, MovieID),
    foreign key (DirectorID, MovieID) references Directs
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM